Commit 3b6e5ba490

mlugg <mlugg@mlugg.co.uk>
2025-01-18 15:28:15
Sema: don't try to initialize global union pointer at comptime
Resolves: #19832
1 parent f7b9f84
Changed files (2)
src
test
behavior
src/Sema.zig
@@ -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]);
test/behavior/union.zig
@@ -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);
+}