From 8111d3d63cf3662b5aecbd0ddd10567e025694a7 Mon Sep 17 00:00:00 2001 From: glowsquid Date: Fri, 10 Apr 2026 23:31:21 +0200 Subject: [PATCH] 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 Co-authored-by: glowsquid Co-committed-by: glowsquid --- src/Sema/comptime_ptr_access.zig | 12 +++++++++++- test/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 index 63a3caefc9..396cbc0d5a 100644 --- 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 index 7b6e6edbb8..4d974e8132 100644 --- 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; +}