Sema: don't try to initialize global union pointer at comptime

Resolves: #19832
This commit is contained in:
mlugg 2025-01-18 14:28:15 +00:00
parent f7b9f84df2
commit 3b6e5ba490
No known key found for this signature in database
GPG Key ID: 3F5B7DCCBF4AF02E
2 changed files with 23 additions and 0 deletions

View File

@ -28498,6 +28498,10 @@ fn unionFieldPtr(
if (try sema.resolveDefinedValue(block, src, union_ptr)) |union_ptr_val| ct: {
switch (union_obj.flagsUnordered(ip).layout) {
.auto => if (initializing) {
if (!sema.isComptimeMutablePtr(union_ptr_val)) {
// The initialization is a runtime operation.
break :ct;
}
// Store to the union to initialize the tag.
const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
const payload_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);

View File

@ -2303,3 +2303,22 @@ test "extern union @FieldType" {
comptime assert(@FieldType(U, "b") == f64);
comptime assert(@FieldType(U, "c") == *U);
}
test "assign global tagged union" {
const U = union(enum) {
a: u16,
b: u32,
var global: @This() = undefined;
};
U.global = .{ .a = 123 };
try expect(U.global == .a);
try expect(U.global != .b);
try expect(U.global.a == 123);
U.global = .{ .b = 123456 };
try expect(U.global != .a);
try expect(U.global == .b);
try expect(U.global.b == 123456);
}