Skip to content

Commit 583e698

Browse files
authored
Sema: disallow casting to opaque
1 parent d404d8a commit 583e698

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

src/Sema.zig

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10188,9 +10188,15 @@ fn analyzeAs(
1018810188
const dest_ty_tag = dest_ty.zigTypeTagOrPoison(mod) catch |err| switch (err) {
1018910189
error.GenericPoison => return operand,
1019010190
};
10191+
10192+
if (dest_ty_tag == .Opaque) {
10193+
return sema.fail(block, src, "cannot cast to opaque type '{}'", .{dest_ty.fmt(pt)});
10194+
}
10195+
1019110196
if (dest_ty_tag == .NoReturn) {
1019210197
return sema.fail(block, src, "cannot cast to noreturn", .{});
1019310198
}
10199+
1019410200
const is_ret = if (zir_dest_type.toIndex()) |ptr_index|
1019510201
sema.code.instructions.items(.tag)[@intFromEnum(ptr_index)] == .ret_type
1019610202
else

test/cases/compile_errors/directly_embedding_opaque_type_in_struct_and_union.zig

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,13 @@ export fn b() void {
1515
_ = &bar;
1616
}
1717
export fn c() void {
18-
const baz = &@as(O, undefined);
19-
const qux = .{baz.*};
20-
_ = qux;
18+
const baz = @as(O, undefined);
19+
_ = baz;
2120
}
2221
export fn d() void {
23-
const baz = &@as(O, undefined);
24-
const qux = .{ .a = baz.* };
25-
_ = qux;
22+
const ptr: *O = @ptrFromInt(0x1000);
23+
const x = .{ptr.*};
24+
_ = x;
2625
}
2726

2827
// error
@@ -33,7 +32,7 @@ export fn d() void {
3332
// :1:11: note: opaque declared here
3433
// :7:10: error: opaque types have unknown size and therefore cannot be directly embedded in unions
3534
// :1:11: note: opaque declared here
36-
// :19:22: error: cannot load opaque type 'tmp.O'
35+
// :18:24: error: cannot cast to opaque type 'tmp.O'
3736
// :1:11: note: opaque declared here
38-
// :24:28: error: cannot load opaque type 'tmp.O'
37+
// :23:20: error: cannot load opaque type 'tmp.O'
3938
// :1:11: note: opaque declared here

0 commit comments

Comments
 (0)