zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 8111d3d63cf3662b5aecbd0ddd10567e025694a7 (tree)
parent 2c6e5006ed3adb02f3bc7b364b2bbc688271d9f7
Author: glowsquid <sachabarsayuracko@gmail.com>
Date:   Fri, 10 Apr 2026 23:31:21 +0200

fix comptime @ptrcasting from a larger type to a smaller one (#31774)

closes #30180

Note from mlugg: this fix is very much a hack, but it definitely won't break anything and it demonstrably fixes one case, so I'm merging it for now with the expectation that I'll be replacing the broken code soon.

Reviewed-on: https://codeberg.org/ziglang/zig/pulls/31774
Reviewed-by: mlugg <mlugg@noreply.codeberg.org>
Co-authored-by: glowsquid <sachabarsayuracko@gmail.com>
Co-committed-by: glowsquid <sachabarsayuracko@gmail.com>

Diffstat:
Msrc/Sema/comptime_ptr_access.zig | 12+++++++++++-
Mtest/behavior/ptrcast.zig | 8++++++++
2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/src/Sema/comptime_ptr_access.zig b/src/Sema/comptime_ptr_access.zig @@ -498,8 +498,18 @@ fn loadComptimePtrInner( return .{ .success = cur_val }; } + var bitcast_src_val = try cur_val.intern(sema.pt, sema.arena); + + if (host_bits != 0) { + const src_bit_size = bitcast_src_val.typeOf(zcu).bitSize(zcu); + if (src_bit_size > host_bits) { + const truncate_ty = try pt.intType(.unsigned, @intCast(host_bits)); + bitcast_src_val = try pt.getCoerced(bitcast_src_val, truncate_ty); + } + } + const result_val = try sema.bitCastVal( - try cur_val.intern(sema.pt, sema.arena), + bitcast_src_val, load_ty, cur_offset, host_bits, diff --git a/test/behavior/ptrcast.zig b/test/behavior/ptrcast.zig @@ -562,3 +562,11 @@ test "@ptrCast array pointer removing sentinel" { comptime assert(out[2] == 3); comptime assert(out[3] == 4); } + +test "@ptrcast larger type to smaller one" { + const T = packed struct { x: u17 }; + const a: u32 = 0; + const b: *const T = @ptrCast(&a); + const c = b.x; + _ = c; +}