Skip to content

Docs/Language/Comptime

Comptime

Compile-time evaluation and type reflection in ordinary Fid code, instead of a macro system.

~2 min read

On this page

Fid has no macros. Compile-time work is ordinary Fid code marked comptime.

Comptime functions and blocks

comptime fn fibonacci(n: i64) -> i64 {
    if n <= 1 { return n; }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

const FIB_10: i64 = comptime fibonacci(10);

const TABLE_SIZE: i64 = comptime {
    val base = 1000;
    base + 24
};

fn main() -> i64 {
    println(FIB_10);       // 55
    println(TABLE_SIZE);   // 1024
    return 0;
}

A call to a comptime fn with constant arguments is evaluated by the compiler. for loops with constant bounds (up to 16 iterations) are unrolled at compile time.

Reflection

comptime op(Type) inspects a type at compile time:

struct Point { x: i64, y: i64 }
enum Shape { Circle, Square }

fn main() -> i64 {
    println(comptime type_name(Point));     // Point
    println(comptime is_struct(Point));     // true
    println(comptime field_count(Point));   // 2
    for f in comptime field_names(Point) { println(f); }     // x y
    for v in comptime enum_variants(Shape) { println(v); }   // Circle Square
    return 0;
}

Also available: is_enum(T) and field_types(T).

@derive

@derive on a struct generates functions named after the struct:

@derive(Clone, Serialize)
struct Point { x: i64, y: i64 }

fn main() -> i64 {
    val p = Point { x: 1, y: 2 };
    val q = Point_clone(p);
    println(Point_to_json(q));   // {"x":1,"y":2}
    return 0;
}

Report an issue