authorgravatar for sachabarsayuracko@gmail.comglowsquid <sachabarsayuracko@gmail.com> 2026-04-10 23:31:21+02:00
committergravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2026-04-10 23:31:21+02:00
log8111d3d63cf3662b5aecbd0ddd10567e025694a7
treedb471a1d98be6cba54a04cf2db414ee679bc036c
parent2c6e5006ed3adb02f3bc7b364b2bbc688271d9f7

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>

2 files changed, 19 insertions(+), 1 deletions(-)

src/Sema/comptime_ptr_access.zig+11-1
...@@ -498,8 +498,18 @@ fn loadComptimePtrInner(...@@ -498,8 +498,18 @@ fn loadComptimePtrInner(
498 return .{ .success = cur_val };498 return .{ .success = cur_val };
499 }499 }
500500
501 var bitcast_src_val = try cur_val.intern(sema.pt, sema.arena);
502
503 if (host_bits != 0) {
504 const src_bit_size = bitcast_src_val.typeOf(zcu).bitSize(zcu);
505 if (src_bit_size > host_bits) {
506 const truncate_ty = try pt.intType(.unsigned, @intCast(host_bits));
507 bitcast_src_val = try pt.getCoerced(bitcast_src_val, truncate_ty);
508 }
509 }
510
501 const result_val = try sema.bitCastVal(511 const result_val = try sema.bitCastVal(
502 try cur_val.intern(sema.pt, sema.arena),512 bitcast_src_val,
503 load_ty,513 load_ty,
504 cur_offset,514 cur_offset,
505 host_bits,515 host_bits,
test/behavior/ptrcast.zig+8
...@@ -562,3 +562,11 @@ test "@ptrCast array pointer removing sentinel" {...@@ -562,3 +562,11 @@ test "@ptrCast array pointer removing sentinel" {
562 comptime assert(out[2] == 3);562 comptime assert(out[2] == 3);
563 comptime assert(out[3] == 4);563 comptime assert(out[3] == 4);
564}564}
565
566test "@ptrcast larger type to smaller one" {
567 const T = packed struct { x: u17 };
568 const a: u32 = 0;
569 const b: *const T = @ptrCast(&a);
570 const c = b.x;
571 _ = c;
572}