Merge pull request #24381 from Justus2308/switch-better-underscore

Enhance switch on non-exhaustive enums
This commit is contained in:
Matthew Lugg
2025-08-13 13:54:15 +01:00
committed by GitHub
12 changed files with 925 additions and 322 deletions

View File

@@ -1073,3 +1073,50 @@ test "switch on 8-bit mod result" {
else => unreachable,
}
}
test "switch on non-exhaustive enum" {
if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest; // TODO
const E = enum(u4) {
a,
b,
c,
_,
fn doTheTest(e: @This()) !void {
switch (e) {
.a, .b => {},
else => return error.TestFailed,
}
switch (e) {
.a, .b => {},
.c => return error.TestFailed,
_ => return error.TestFailed,
}
switch (e) {
.a, .b => {},
.c, _ => return error.TestFailed,
}
switch (e) {
.a => {},
.b, .c, _ => return error.TestFailed,
}
switch (e) {
.b => return error.TestFailed,
else => {},
_ => return error.TestFailed,
}
switch (e) {
else => {},
_ => return error.TestFailed,
}
switch (e) {
inline else => {},
_ => return error.TestFailed,
}
}
};
try E.doTheTest(.a);
try comptime E.doTheTest(.a);
}

View File

@@ -249,3 +249,27 @@ test "switch loop on larger than pointer integer" {
}
try expect(entry == 3);
}
test "switch loop on non-exhaustive enum" {
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest; // TODO
const S = struct {
const E = enum(u8) { a, b, c, _ };
fn doTheTest() !void {
var start: E = undefined;
start = .a;
const result: u32 = s: switch (start) {
.a => continue :s .c,
else => continue :s @enumFromInt(123),
.b, _ => |x| break :s @intFromEnum(x),
};
try expect(result == 123);
}
};
try S.doTheTest();
try comptime S.doTheTest();
}