Commit 95a87e88fa

Andrew Kelley <andrew@ziglang.org>
2022-04-05 07:46:05
Sema: forward switch condition to captures
1 parent 51ef31a
Changed files (2)
src
test
behavior
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;
+            }
         },
     }
 }
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);
+}