# Compile-Time Recipes

Use compile-time evaluation to make a decision once, then keep the resulting
application code ordinary Vex. These recipes cover a bounded configuration
calculation and a field traversal driven by typed reflection. For generated
functions and types, continue with [Structural Declaration
Generation](comptime-declarations.md).

## Calculate a bounded retry schedule

Suppose a client starts with a 25 ms delay, doubles it for each retry, and caps
it at 400 ms. The policy below clamps the exponent before multiplication, so a
large attempt count cannot overflow the calculation or create a long loop.
Negative attempt counts use the initial delay.

```vex [comptime-backoff.vx]
const fn retryDelay(attempt: i32): i32 {
    let! steps = attempt;
    if steps < 0 { steps = 0; }
    if steps > 4 { steps = 4; }
    let! delay = 25;
    while steps > 0 { delay *= 2; steps -= 1; }
    return delay;
}
fn main(): i32 {
    let initial = #const { retryDelay(0) };
    let later = #const { retryDelay(3) };
    let capped = #const { retryDelay(20) };
    #Diag.staticAssert(retryDelay(20) == 400, "retry cap changed");
    $println(initial); $println(later); $println(capped);
    if initial != 25 || later != 200 || capped != 400 { return 1; }
    return 0;
}
```

Run `vex run comptime-backoff.vx`. Expected output:

```text
25
200
400
```

`const fn` makes the algorithm available to the compile-time evaluator. Each
`#const { ... }` requires its result during compilation; `staticAssert` checks
that the cap agrees with the policy. The resulting values can be passed to a
runtime timer without evaluating the loop again at runtime.

The function describes a delay, not an automatic retry mechanism. The caller
still decides which errors are retryable, when to stop, and whether repeating
an operation is safe. Keep clocks, sleeping, network calls, and runtime state
outside this required-comptime calculation. The same function can also accept
a runtime attempt count in an ordinary call.

## Select fields by their exact type

A metrics record can contain counters and a sequence identifier. This example
sums and clears only `i32` fields; the `i64` sequence stays intact. Both helpers
are generic, and the reflected field access is checked for each concrete type.

```vex [comptime-counters.vx]
struct Counters: Copy { accepted: i32, retried: i32, sequence: i64 }
fn counterTotal<T>(value: T): i32 {
    let! total = 0;
    #for field in #Type.info<T>().fields {
        #if #Reflect.fieldIs<i32>(field) {
            total += #Reflect.getField(value, field);
        }
    }
    return total;
}
fn clearCounters<T>(target: &T!) {
    #for field in #Type.info<T>().fields {
        #if #Reflect.fieldIs<i32>(field) {
            #Reflect.setField(target, field, 0);
        }
    }
}
fn main(): i32 {
    let! counters = Counters { accepted: 7, retried: 2, sequence: 100i64 };
    let before = counterTotal(counters);
    clearCounters(&counters);
    let after = counterTotal(counters);
    $println(before); $println(after); $println(counters.sequence);
    if before != 9 || after != 0 || counters.sequence != 100i64 { return 1; }
    return 0;
}
```

Run `vex run comptime-counters.vx`. Expected output:

```text
9
0
100
```

The three lines are the original counter sum, the sum after clearing, and the
unchanged sequence identifier.

During expansion, `#for` visits the metadata fields of `T`. The typed predicate
`#Reflect.fieldIs<i32>(field)` decides which body to keep. Each retained
`getField` or `setField` becomes access to that exact field, so the generated
program does not search a dictionary of field names. The integer values being
summed or changed are still runtime data.

`Counters: Copy` allows the summing helper to take a value while the caller
retains its record. Clearing instead takes a mutable reference: it changes
the original record and requires exclusive access. The unused `i64` field is
neither converted nor reset.

Type selection expresses a policy, not a universal meaning of `i32`. If a
record also uses `i32` for an identifier that must survive clearing, use a
separate counter record or an explicit field/tag policy. For heterogeneous
serialization, inspect each field's type and metadata instead of assuming all
fields support one arithmetic operation.

## Choose the right compile-time boundary

| Need | Mechanism | Runtime behavior |
| --- | --- | --- |
| A value must be known while compiling | `#const { ... }` or `#Const.eval(...)` | Uses the evaluated value. |
| Select code for a target or reflected type | `#if` | The selected body can still contain runtime work. |
| Repeat a field-specific body | `#for field in #Type.info<T>().fields` | Executes the expanded, typed operations. |
| Define new named functions or types | An authorized `DeclSet` module generator | Uses generated declarations through normal name resolution and calls. |

A useful separation is to compute **structure** at compile time and process
**data** at runtime. A serializer can choose fields during compilation while
reading a particular message's contents at runtime; a target-specific wrapper
can select an implementation during compilation while accepting ordinary
runtime arguments.

## Next steps

- [Compile-Time Evaluation](comptime.md)
- [Structural Declaration Generation](comptime-declarations.md)
- [Compiler Directives](compiler-directives.md)
- [Comptime Pipeline](../../architecture/comptime-pipeline.md)
