Does the quota set by @setEvalBranchQuota take effect in the whole function scope?

I haven’t get the sure answer via web searching, but the following code verifies my guess, though, I’m still not sure about the exact rules.

fn sum(v: u64) @TypeOf(v) {
    var r = v;
    if (v > 1) {
        var i = v-1;
        while (i > 0) {
            r += i;
            i -= 1;
        }
    }
    return r;
}

pub fn main() void {
    const n = 10_000;

    {
        @setEvalBranchQuota(n); // This line works (for the next sum call).
    }
    {
        const x = comptime sum(n);
        @import("std").debug.print("x = {}\n", .{ x });
    }
    
 
    opaque {
        fn foo() void {
           @setEvalBranchQuota(n); // This line doesn't work (for the next sum call).
        }
    }.foo();
    {
        const y = comptime sum(n);
        @import("std").debug.print("y = {}\n", .{ y });
    }
}

Yes, the branch quota is at function scope.

1 Like

In the following code, the last @setEvalBranchQuota call works, but the second one to last one (being commented out) doesn’t.

This is by design:

Increase the maximum number of backwards branches that compile-time code execution can use before giving up and making a compile error.

But, is it better to increase the minimum remaining quota instead?

fn sum(n: u64) @TypeOf(n) {
    var r = n;
    if (n > 1) {
        var i = n-1;
        while (i > 0) {
            r += i;
            i -= 1;
        }
    }
    return r;
}

pub fn main() void {
    const print = @import("std").debug.print;
    const n = 10_000;
    
    @setEvalBranchQuota(n);
    const y = comptime sum(n);
    print("y = {}\n", .{ y });
    
    //@setEvalBranchQuota(n); // This line doesn't work.
    @setEvalBranchQuota(n + n); // This line works.
    comptime var z = sum(n);
    z = z;
    print("z = {}\n", .{ z });
}