Sema: forward switch condition to captures

This commit is contained in:
Andrew Kelley 2022-04-04 22:46:05 -07:00
parent 51ef31a833
commit 95a87e88fa
2 changed files with 30 additions and 3 deletions

View File

@ -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;
}
},
}
}

View File

@ -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);
}