Skip to content

Commit 3b6e5ba

Browse files
committed
Sema: don't try to initialize global union pointer at comptime
Resolves: #19832
1 parent f7b9f84 commit 3b6e5ba

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/Sema.zig

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28498,6 +28498,10 @@ fn unionFieldPtr(
2849828498
if (try sema.resolveDefinedValue(block, src, union_ptr)) |union_ptr_val| ct: {
2849928499
switch (union_obj.flagsUnordered(ip).layout) {
2850028500
.auto => if (initializing) {
28501+
if (!sema.isComptimeMutablePtr(union_ptr_val)) {
28502+
// The initialization is a runtime operation.
28503+
break :ct;
28504+
}
2850128505
// Store to the union to initialize the tag.
2850228506
const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2850328507
const payload_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);

test/behavior/union.zig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2303,3 +2303,22 @@ test "extern union @FieldType" {
23032303
comptime assert(@FieldType(U, "b") == f64);
23042304
comptime assert(@FieldType(U, "c") == *U);
23052305
}
2306+
2307+
test "assign global tagged union" {
2308+
const U = union(enum) {
2309+
a: u16,
2310+
b: u32,
2311+
2312+
var global: @This() = undefined;
2313+
};
2314+
2315+
U.global = .{ .a = 123 };
2316+
try expect(U.global == .a);
2317+
try expect(U.global != .b);
2318+
try expect(U.global.a == 123);
2319+
2320+
U.global = .{ .b = 123456 };
2321+
try expect(U.global != .a);
2322+
try expect(U.global == .b);
2323+
try expect(U.global.b == 123456);
2324+
}

0 commit comments

Comments
 (0)