Files
zig/test/cases/compile_errors/initialize_empty_union.zig
Matthew Lugg 5f74e4f3f8 Sema: make loading uninstantiable types a runtime safety panic
For generic code, it is far more useful to consider this equivalent to
`unreachable`. Meanwhile, it is difficult to accidentally write concrete
code which performs this operation, so very little is actually lost from
not having a compile error.

If we accept that this operation does not trigger a compile error, then
it already has the potential to invoke Illegal Behavior today, because
uninstantiable types have an unspecified size in memory, so the
dereference always potentially exceeds the pointer's provenance. (That
said, this only means it is *possible* for the operation to invoke IB,
so the langspec should nonetheless explicitly specify that dereferencing
a pointer to an uninstantiable type is itself Illegal Behavior.)

Storing uninstantiable types into memory does not require any specific
language rules, because that operation can never be reached anyway due
to it requiring an operand (the RHS of `a = b`) whose type is the store
type, which is (by definition) impossible for uninstantiable types.

Resolves: https://codeberg.org/ziglang/zig/issues/36247
2026-08-04 22:29:50 +02:00

51 lines
1.6 KiB
Zig

const EnumInferred = enum {};
const EnumExplicit = enum(noreturn) {};
const EnumNonexhaustive = enum(u8) { _ };
const U0 = union {};
const U1 = union(enum) {};
const U2 = union(enum(noreturn)) {};
const U3 = union(EnumInferred) {};
const U4 = union(EnumExplicit) {};
const U5 = union(EnumNonexhaustive) {};
export fn init0() void {
_ = @as(U0, undefined);
}
export fn init1() void {
_ = @as(U1, undefined);
}
export fn init2() void {
_ = @as(U2, undefined);
}
export fn init3() void {
_ = @as(U3, undefined);
}
export fn init4() void {
_ = @as(U4, undefined);
}
export fn init5() void {
_ = @as(U5, undefined);
}
// error
//
// :13:17: error: expected type 'tmp.U0', found '@TypeOf(undefined)'
// :13:17: note: cannot coerce to uninstantiable type 'tmp.U0'
// :5:12: note: union declared here
// :16:17: error: expected type 'tmp.U1', found '@TypeOf(undefined)'
// :16:17: note: cannot coerce to uninstantiable type 'tmp.U1'
// :6:12: note: union declared here
// :19:17: error: expected type 'tmp.U2', found '@TypeOf(undefined)'
// :19:17: note: cannot coerce to uninstantiable type 'tmp.U2'
// :7:12: note: union declared here
// :22:17: error: expected type 'tmp.U3', found '@TypeOf(undefined)'
// :22:17: note: cannot coerce to uninstantiable type 'tmp.U3'
// :8:12: note: union declared here
// :25:17: error: expected type 'tmp.U4', found '@TypeOf(undefined)'
// :25:17: note: cannot coerce to uninstantiable type 'tmp.U4'
// :9:12: note: union declared here
// :28:17: error: expected type 'tmp.U5', found '@TypeOf(undefined)'
// :28:17: note: cannot coerce to uninstantiable type 'tmp.U5'
// :10:12: note: union declared here