authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-04-04 22:46:05-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-04-04 22:46:05-07:00
log95a87e88fac3fc563ac3baaf4eb8027341f4131e
tree4b028355d7f38451d7de1cc2977aa59b9543c8f3
parent51ef31a8331e92103253a37ddfdacbd263cee81d

Sema: forward switch condition to captures


2 files changed, 30 insertions(+), 3 deletions(-)

src/Sema.zig+8-3
...@@ -7273,9 +7273,14 @@ fn zirSwitchCapture(...@@ -7273,9 +7273,14 @@ fn zirSwitchCapture(
7273 }7273 }
7274 },7274 },
7275 else => {7275 else => {
7276 return sema.fail(block, operand_src, "switch on type '{}' provides no capture value", .{7276 // In this case the capture value is just the passed-through value of the
7277 operand_ty.fmt(target),7277 // switch condition.
7278 });7278 if (is_ref) {
7279 assert(operand_is_ref);
7280 return operand_ptr;
7281 } else {
7282 return operand;
7283 }
7279 },7284 },
7280 }7285 }
7281}7286}
test/behavior/switch.zig+22
...@@ -656,3 +656,25 @@ test "switch capture copies its payload" {...@@ -656,3 +656,25 @@ test "switch capture copies its payload" {
656 try S.doTheTest();656 try S.doTheTest();
657 comptime try S.doTheTest();657 comptime try S.doTheTest();
658}658}
659
660test "capture of integer forwards the switch condition directly" {
661 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
662 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
663
664 const S = struct {
665 fn foo(x: u8) !void {
666 switch (x) {
667 40...45 => |capture| {
668 try expect(capture == 42);
669 },
670 else => |capture| {
671 try expect(capture == 100);
672 },
673 }
674 }
675 };
676 try S.foo(42);
677 try S.foo(100);
678 comptime try S.foo(42);
679 comptime try S.foo(100);
680}