ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
35.06k stars 2.56k forks source link

zig translate-c Produces Incorrect Zig Code for Array Pointer Access #22045

Open Yeaseen opened 11 hours ago

Yeaseen commented 11 hours ago

Zig Version

0.14.0-dev.2064+b5cafe223

Steps to Reproduce and Observed Behavior

Input C Code

typedef int (*myarr)[2];

void main() {
    // Define an array and set `a` to point to it
    int array[2] = {10, 20};
    int (*a)[2] = &array;  // `a` points to `array`

    // Set `b` to point to the same array, casted to `myarr`
    myarr b = (myarr)a;

    // Modify array elements through `b`
    (*b)[0] = 30;
}

Translated zig code

pub const myarr = [*c][2]c_int;
pub export fn main() void {
    var array: [2]c_int = [2]c_int{
        10,
        20,
    };
    _ = &array;
    var a: [*c][2]c_int = &array;
    _ = &a;
    var b: myarr = @as(myarr, @ptrCast(@alignCast(a)));
    _ = &b;
    b.*[@as(c_uint, @intCast(@as(c_int, 0)))] = 30;
}

zig build failure

runner.zig:68:49: error: expected type '[2]c_int', found 'comptime_int'
    b.*[@as(c_uint, @intCast(@as(c_int, 0)))] = 30;
                                                ^~

The generated zig code incorrectly uses a cast that results in a comptime_int type mismatch, making it impossible to modify the array elements as intended.

Expected Behavior

The zig translate-c tool should generate the correct zig code that allows accessing and modifying array elements through a pointer. For example, the output zig code should correctly handle the array pointer and allow the assignment.

rohlem commented 8 hours ago

I don't see the issue in the generated code, rather something in the type check / access pattern of b.*[n] = x might be wrong in the compiler: