Commit 711b4e93e2

Anton Lilja <12533691+antlilja@users.noreply.github.com>
2023-07-12 08:37:42
Fixes crash when a struct is given as the first parameter to the unionInit builtin (#16385)
1 parent ff0e2ab
Changed files (2)
src/Sema.zig
@@ -18727,6 +18727,15 @@ fn zirUnionInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
     const init_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
     const extra = sema.code.extraData(Zir.Inst.UnionInit, inst_data.payload_index).data;
     const union_ty = try sema.resolveType(block, ty_src, extra.union_type);
+    if (union_ty.zigTypeTag(sema.mod) != .Union) {
+        const msg = msg: {
+            const msg = try sema.errMsg(block, ty_src, "expected union type, found '{}'", .{union_ty.fmt(sema.mod)});
+            errdefer msg.destroy(sema.gpa);
+            try sema.addDeclaredHereNote(msg, union_ty);
+            break :msg msg;
+        };
+        return sema.failWithOwnedErrorMsg(msg);
+    }
     const field_name = try sema.resolveConstStringIntern(block, field_src, extra.field_name, "name of field being initialized must be comptime-known");
     const init = try sema.resolveInst(extra.init);
     return sema.unionInit(block, init, init_src, union_ty, ty_src, field_name, field_src);
test/cases/compile_errors/union_init_with_struct_as_first_param.zig
@@ -0,0 +1,14 @@
+const S = struct {
+    a: u8,
+};
+
+export fn u() void {
+    _ = @unionInit(S, "a", 5);
+}
+
+// error
+// backend=stage2
+// target=native
+//
+// :6:20: error: expected union type, found 'tmp.S'
+// :1:11: note: struct declared here