zig icon indicating copy to clipboard operation
zig copied to clipboard

@fieldParentPtr on packed struct gives wrong address at runtime

Open diffuty opened this issue 1 year ago • 3 comments

Zig Version

0.13.0

Steps to Reproduce and Observed Behavior

I'm new to zig. Please feel free to let me know if I misunderstood things.

The following test fails for me. Briefly, I expect @fieldParentPtr("c", &a.b.c) would always be the same as &a.b, but seems they could be different on packed structs.

const expectEqual = @import("std").testing.expectEqual;

const Packed2 = packed struct {
    a3: i3 = -2,
};

const Packed1 = packed struct {
    a2: u1 = 0, // Padding to give .packed2 an offset from byte boundary.
    packed2: Packed2 = .{},
};

test "@fieldParentPtr behavior on packed struct" {
    var packed1: Packed1 = .{};
    const ptr: @TypeOf(&packed1.packed2) = @fieldParentPtr("a3", &packed1.packed2.a3);
    try expectEqual(&packed1.packed2, ptr); // Fail.
}

// $ zig test behavior1.zig
// expected behavior1.Packed2@7ffc5ca856d7, found behavior1.Packed2@7ffc5ca856d4

Environment is Ubuntu 22.04 on x86_64.

Zig installed with snap install zig --classic --beta

Expected Behavior

The test should pass.

diffuty avatar Jun 30 '24 11:06 diffuty

it seems like packed structs aren't supported for @fieldParentPtr based on this. but that also makes it seem like it shouldn't even compile

JonathanHallstrom avatar Jul 04 '24 14:07 JonathanHallstrom

it seems like packed structs aren't supported for @fieldParentPtr based on this. but that also makes it seem like it shouldn't even compile

The link has expired. Guess it is this line:

assert(struct_type.layout != .@"packed");

diffuty avatar Jul 14 '24 10:07 diffuty

The compiler does explicitly implement @fieldParentPtr for packed structs and the example works at comptime.

Vexu avatar Jul 15 '24 12:07 Vexu