How to cache comptime evaluations via the build system?

As an example, here’s a main.zig and a lib.zig that should contain a cached comptime evaluation:


const std = @import("std");
const lib = @import("lib.zig");

pub fn main() void {"{}\n", .{lib.cachedConstant});


const std = @import("std");

pub const cachedConstant: u32 = slowFn();

// This takes a few seconds to evaluate
fn slowFn() u32 {
    var x: u32 = 1;
    var i: u32 = 0;
    // @compileLog("x1");
    while (i < (1 << 19)) : (i += 1) {
        x ^= (x << 3) +% 1;
        x ^= x >> 1;
    // @compileLog("x2");
    return x;

Changing just main.zig always results in a reevaluation of cachedConstant in lib.zig (zig 0.9.1).
Is there a way to cache comptime evals with the zig build system?

You could generate code with the result of the computation (using print) then import the result of code generation as a module. Should be good enough for this case.

1 Like

As tauoverpi said, you can find work arounds (also using the build system would make that easier) but if you want a generic seamless way of caching comptime evaluations you will have to wait for the new incremental compilation system to be released, which will be the next thing being worked on once self-hosted is released.