Skip to content

Endless loop in Semantic Analysis [x/y] #4572

@ikskuh

Description

@ikskuh

When compiling the following code, the compiler will run into an endless loop trying to analyze whatever it is to analyze:

const std = @import("std");

const Value = union(enum) {
    array: Array,
    item: i32,

    /// Checks if two values are equal.
    pub fn format(value: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, context: var, comptime Errors: type, comptime output: fn (@TypeOf(context), []const u8) Errors!void) Errors!void {
        return switch (value) {
            .item => |i| std.fmt.format(context, Errors, output, "{d}", .{i}),
            .array => |array| {
                for (array) |item| {
                    try std.fmt.format(context, Errors, output, " {}", .{item}); // <= @0 will analyze forever
                    // try format(item, fmt, options, context, Errors, output); // <= @1 works
                }
                // try arrayFormat(array, context, Errors, output); // @2 works as well
            },
        };
    }

    fn arrayFormat(array: Array, context: var, comptime Errors: type, comptime output: fn (@TypeOf(context), []const u8) Errors!void) Errors!void {
        for (array) |item| {
            try std.fmt.format(context, Errors, output, " {}", .{item}); // <= @2 works as well
        }
    }
};

const Array = []const Value;

test "will analyze forever" {
    const v: Value = Value{ .item = 1 };
    std.debug.warn("{}\n", .{v}); // this will call `format` on our struct
}

This code will run into an endless loop of semantic analysis when using variant @0:

[felix@denkplatte-v2 bugreports]$ zig test recursion-error.zig 
Semantic Analysis [3552/5909] ^C

It will run when using variant @1 (using direct recursion) or variant @2 (calling a function that will call the formatter)

Zig version: 0.5.0+330e30aec

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorstage1The process of building from source via WebAssembly and the C backend.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions