zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 95a87e88fac3fc563ac3baaf4eb8027341f4131e (tree)
parent 51ef31a8331e92103253a37ddfdacbd263cee81d
Author: Andrew Kelley <andrew@ziglang.org>
Date:   Mon,  4 Apr 2022 22:46:05 -0700

Sema: forward switch condition to captures

Diffstat:
Msrc/Sema.zig | 11++++++++---
Mtest/behavior/switch.zig | 22++++++++++++++++++++++
2 files changed, 30 insertions(+), 3 deletions(-)

diff --git a/src/Sema.zig b/src/Sema.zig @@ -7273,9 +7273,14 @@ fn zirSwitchCapture( } }, else => { - return sema.fail(block, operand_src, "switch on type '{}' provides no capture value", .{ - operand_ty.fmt(target), - }); + // In this case the capture value is just the passed-through value of the + // switch condition. + if (is_ref) { + assert(operand_is_ref); + return operand_ptr; + } else { + return operand; + } }, } } diff --git a/test/behavior/switch.zig b/test/behavior/switch.zig @@ -656,3 +656,25 @@ test "switch capture copies its payload" { try S.doTheTest(); comptime try S.doTheTest(); } + +test "capture of integer forwards the switch condition directly" { + if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO + if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO + + const S = struct { + fn foo(x: u8) !void { + switch (x) { + 40...45 => |capture| { + try expect(capture == 42); + }, + else => |capture| { + try expect(capture == 100); + }, + } + } + }; + try S.foo(42); + try S.foo(100); + comptime try S.foo(42); + comptime try S.foo(100); +}