Help: zig 0.16.0 compiler hung in infinite loop without any info

Hi,

I am new to zig, currently stumble upon issue with zig 0.16.0.

I encountered if the code path has white(true), it can make the zig 0.16.0 compiler hang forever.

// code example (ai generated)
const std = @import("std");

fn comptimeLoop() u32 {
    @setEvalBranchQuota(1_000_000_000);
    var i: u32 = 0;
    while (true) {
        i +%= 1;
    }
    return i;
}

test "compiler hangs at comptime" {
    const result = comptime comptimeLoop();
    try std.testing.expect(result > 0);
}

or a simple test:

test "runtime infinite loop hangs test runner" {
    while (true) {}
}

.

Is it expected for the latest zig compiler?

1 Like

It’s trying to run this loop 10^9 times, so it makes sense it’s taking forever. Did you try this with a managable number like 1000?

1 Like

Tests arent run in the compiler. zig test builds a test executable then runs it, so its not the compiler hanging in that case

4 Likes

Above is just a simple example. Do we have mechanism to detect the loop? or we can only do guessing.

No, Zig has no way of detecting infinite loops. If you have a real problem with hanging tests, the debugging mechanisms involve debuggers and prints. Run the test and interrupt it after some time, see the stack trace. If it’s multi threaded or depends on timing, adding prints might work better.

The backward branch quota is the mechanism :slight_smile:

There is a reason why the default quota is 1000 backward branches and why users are discouraged from calling @setEvalBranchQuota with std.math.maxInt(u32) or some other arbitrarily huge number. It’s better calculate and use an upper bound based on the specific context of the comptime loop, for example, @setEvalBranchQuota(2 * @typeInfo(T).@"struct".fields.len if you know you will be iterating over a struct’s fields two times over.

The compiler could probably be improved to detect that trivial cases such as while (true) {} never break, but it has been proven that it is impossible to determine whether any arbitrary loop will ever break or not.

6 Likes

9 posts were split to a new topic: Zon parsing and eval quota

Lookup the “halting problem”. It’s an unsolvable problem in the “general case”. Zig solves it by adding its branch quota.

3 Likes