authorgravatar for justus@klausecker.deJustus Klausecker <justus@klausecker.de> 2026-05-06 09:42:40+02:00
committergravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2026-05-07 06:25:43+02:00
log6d0b8879728722d14561d747717f616cd4e7ae0c
treedb3b272e121832e6b3eaddbd6ab84dea12725eec
parentfecd28371d5c0e25357dfb91f75c8790f8b4155b

Sema: disallow pointer cast from pointer to opaque type to slice

Fixes a regression where this conversion crashes. When the conversion was still possible it would produce a slice with a length of zero, which doesn't really make a lot of sense either. There's no way to determine the length of the destination slice from a pointer to an opaque type, so it's a compile error now. Users should just cast to a many-item pointer and slice to the desired length manually instead.

2 files changed, 24 insertions(+), 0 deletions(-)

src/Sema.zig+10
......@@ -21154,6 +21154,16 @@ fn ptrCastFull(
2115421154 break :len if (opt_src_len) |l| .{ .constant = l } else .equal_runtime_src_slice;
2115521155 }
2115621156 if (!src_elem_ty.comptimeOnly(zcu) and !dest_elem_ty.comptimeOnly(zcu)) {
21157 if (src_elem_ty.zigTypeTag(zcu) == .@"opaque") {
21158 return sema.failWithOwnedErrorMsg(block, msg: {
21159 const msg = try sema.errMsg(src, "cannot infer length of slice of '{f}' from pointer to opaque type '{f}' with unknown size", .{
21160 dest_elem_ty.fmt(pt), src_elem_ty.fmt(pt),
21161 });
21162 errdefer msg.destroy(gpa);
21163 try sema.addDeclaredHereNote(msg, src_elem_ty);
21164 break :msg msg;
21165 });
21166 }
2115721167 const src_elem_size = src_elem_ty.abiSize(zcu);
2115821168 const dest_elem_size = dest_elem_ty.abiSize(zcu);
2115921169 if (dest_elem_size == 0) {
test/cases/compile_errors/ptrcast_anyopaque_to_slice.zig created+14
......@@ -0,0 +1,14 @@
1export fn entry1(x: *anyopaque) void {
2 _ = @as([]u8, @ptrCast(x));
3}
4
5const Opaque = opaque {};
6export fn entry2(x: *Opaque) void {
7 _ = @as([]u8, @ptrCast(x));
8}
9
10// error
11//
12// :2:19: error: cannot infer length of slice of 'u8' from pointer to opaque type 'anyopaque' with unknown size
13// :7:19: error: cannot infer length of slice of 'u8' from pointer to opaque type 'tmp.Opaque' with unknown size
14// :5:16: note: opaque declared here