Skip to content

Unable to evaluate pointer subtraction between struct fields in comptime #21480

@rohlem

Description

@rohlem

Zig Version

0.14.0-dev.1579+f3445f8f6

Steps to Reproduce and Observed Behavior

Reduced from #21478, repro zig test .zig:

pub const S = struct {
    data: [2]u8,
};
const s: S = undefined;
const offset = &s.data[1] - @as(*const u8, @ptrCast(&s)); //triggers compile error
//const offset = @offsetOf(S, "data") + (&s.data[1] - &s.data[0]); //works
test {
    @compileLog(offset);
}

zig test .zig output:

.zig:5:27: error: unable to evaluate comptime expression
const offset = &s.data[1] - @as(*const u8, @ptrCast(&s)); //triggers compile error
               ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.zig:5:27: note: operation is runtime due to this operand

The other definition of offset, which in my understanding should be equivalent, works.
It's generally possible to rewrite code to use @offsetOf and manual calculation, however it's error prone if you already have a way to get a pointer having to duplicate the same logic to calculate the offset.
Furthermore, since the initializer expression is in a comptime context, I think the error stating that an operand is "runtime" is factually incorrect.
The note also doesn't point out one particular operand, which makes it seem incorrect/incomplete.

Expected Behavior

Both equivalent definitions of offset should be resolvable at comptime.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorfrontendTokenization, parsing, AstGen, Sema, and Liveness.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions