Commit 583e698256

fmaggi <61335294+fmaggi@users.noreply.github.com>
2024-07-15 09:58:33
Sema: disallow casting to opaque
1 parent d404d8a
Changed files (2)
src/Sema.zig
@@ -10188,9 +10188,15 @@ fn analyzeAs(
     const dest_ty_tag = dest_ty.zigTypeTagOrPoison(mod) catch |err| switch (err) {
         error.GenericPoison => return operand,
     };
+
+    if (dest_ty_tag == .Opaque) {
+        return sema.fail(block, src, "cannot cast to opaque type '{}'", .{dest_ty.fmt(pt)});
+    }
+
     if (dest_ty_tag == .NoReturn) {
         return sema.fail(block, src, "cannot cast to noreturn", .{});
     }
+
     const is_ret = if (zir_dest_type.toIndex()) |ptr_index|
         sema.code.instructions.items(.tag)[@intFromEnum(ptr_index)] == .ret_type
     else
test/cases/compile_errors/directly_embedding_opaque_type_in_struct_and_union.zig
@@ -15,14 +15,13 @@ export fn b() void {
     _ = &bar;
 }
 export fn c() void {
-    const baz = &@as(O, undefined);
-    const qux = .{baz.*};
-    _ = qux;
+    const baz = @as(O, undefined);
+    _ = baz;
 }
 export fn d() void {
-    const baz = &@as(O, undefined);
-    const qux = .{ .a = baz.* };
-    _ = qux;
+    const ptr: *O = @ptrFromInt(0x1000);
+    const x = .{ptr.*};
+    _ = x;
 }
 
 // error
@@ -33,7 +32,7 @@ export fn d() void {
 // :1:11: note: opaque declared here
 // :7:10: error: opaque types have unknown size and therefore cannot be directly embedded in unions
 // :1:11: note: opaque declared here
-// :19:22: error: cannot load opaque type 'tmp.O'
+// :18:24: error: cannot cast to opaque type 'tmp.O'
 // :1:11: note: opaque declared here
-// :24:28: error: cannot load opaque type 'tmp.O'
+// :23:20: error: cannot load opaque type 'tmp.O'
 // :1:11: note: opaque declared here