Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/Sema.zig
Original file line number Diff line number Diff line change
Expand Up @@ -22837,11 +22837,14 @@ fn ptrCastFull(
if (src_slice_like_elem.comptimeOnly(zcu) or dest_elem.comptimeOnly(zcu)) {
return sema.fail(block, src, "cannot infer length of slice of '{}' from slice of '{}'", .{ dest_elem.fmt(pt), src_slice_like_elem.fmt(pt) });
}
const src_elem_size = src_slice_like_elem.abiSize(zcu);
// It's okay for `src_slice_like_elem` to be 0-bit; the resulting slice will just always have 0 elements.
// However, `dest_elem` can't be 0-bit. If it were, then either the source slice has 0 bits and we don't
// know how what `result.len` should be, or the source has >0 bits and there is no valid `result.len`.
const dest_elem_size = dest_elem.abiSize(zcu);
if (src_elem_size == 0 or dest_elem_size == 0) {
if (dest_elem_size == 0) {
return sema.fail(block, src, "cannot infer length of slice of '{}' from slice of '{}'", .{ dest_elem.fmt(pt), src_slice_like_elem.fmt(pt) });
}
const src_elem_size = src_slice_like_elem.abiSize(zcu);
break :need_len_change src_elem_size != dest_elem_size;
} else false;

Expand Down
20 changes: 20 additions & 0 deletions test/behavior/ptrcast.zig
Original file line number Diff line number Diff line change
Expand Up @@ -507,3 +507,23 @@ test "@ptrCast array pointer to slice with complex length decrease" {
try S.doTheTest(@splat(0));
try comptime S.doTheTest(@splat(0));
}

test "@ptrCast slice of zero-bit type to different slice" {
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;

const S = struct {
fn doTheTest(comptime T: type, zero_bits: []const T) !void {
const out: []const u8 = @ptrCast(zero_bits);
try expect(out.len == 0);
}
};
try S.doTheTest(void, &.{ {}, {}, {} });
try S.doTheTest(u0, &.{ 0, 0, 0, 0 });
try S.doTheTest(packed struct(u0) {}, &.{ .{}, .{} });
try comptime S.doTheTest(void, &.{ {}, {}, {} });
try comptime S.doTheTest(u0, &.{ 0, 0, 0, 0 });
try comptime S.doTheTest(packed struct(u0) {}, &.{ .{}, .{} });
}