From 0bbff9d7fb3388d064288eb0bb8395aadcc5f4f1 Mon Sep 17 00:00:00 2001 From: agra Date: Sun, 31 May 2026 21:10:56 +0300 Subject: [PATCH] ERR/E1.5: catch sema (pure-failable slice) + error-set match subjects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `expr catch [e] BODY` consumes a failable's error inline. Pure-failable slice (value-carrying `-> (T, !)` catch deferred to E2's tuple ABI). - lowerExpr `.catch_expr` -> lowerCatch; inferExprType `.catch_expr` -> operand's success type (void for pure-failable). - lowerCatch: operand must be failable (else "catch requires a failable expression"); pure-failable LHS only (value-carrying bails to E2). Eval operand -> err tag; condBr to handle (error) / merge (success). In handle: child scope binds `e` to the tag (typed as the error set), lower body (block or expr); if the body didn't diverge, br merge. Result is void. `catch` needs no failable enclosing function — it handles the error locally. - All four body forms work: block, no-binding `catch { }`, bare-expr, and the match-body `catch e == { case ... }`. Re-raise (`raise e`) and diverging bodies (`return`) rely on E1.3 / E1.4c. Also: lowerMatch now supports error-set subjects — `case .X` resolves to the global tag id (was the arm index, dispatching wrong), and the switch operand is the error-set value (its u32 tag) directly rather than via enumTag. This is what the catch match-body form (and a plain `if e == { case .X }`) needs. Tests: examples/226-catch.sx (block / no-binding / match-body / re-raise / diverging body / success-skip; exit 18), examples/227-catch-rejections.sx (operand-not-failable; exit 1). Gates: zig build, zig build test, 265/265 examples. --- examples/226-catch.sx | 64 ++++++++++++++++++ examples/227-catch-rejections.sx | 13 ++++ src/ir/lower.zig | 84 +++++++++++++++++++++++- tests/expected/226-catch.exit | 1 + tests/expected/226-catch.txt | 1 + tests/expected/227-catch-rejections.exit | 1 + tests/expected/227-catch-rejections.txt | 5 ++ 7 files changed, 168 insertions(+), 1 deletion(-) create mode 100644 examples/226-catch.sx create mode 100644 examples/227-catch-rejections.sx create mode 100644 tests/expected/226-catch.exit create mode 100644 tests/expected/226-catch.txt create mode 100644 tests/expected/227-catch-rejections.exit create mode 100644 tests/expected/227-catch-rejections.txt diff --git a/examples/226-catch.sx b/examples/226-catch.sx new file mode 100644 index 0000000..a97e26a --- /dev/null +++ b/examples/226-catch.sx @@ -0,0 +1,64 @@ +// `catch` on a pure-failable LHS (ERR step E1.5). `expr catch [e] BODY` +// consumes the error inline: on failure it binds the tag to `e` (optional) +// and runs BODY; on success the result is void (a `-> !` LHS has no success +// value). BODY may diverge (`return` / `raise` — typed `noreturn`, E1.4c) or +// fall through. `catch` needs no failable *enclosing* function — it handles +// the error locally. All four body forms appear below: block, no-binding +// block, match-body (`== { case ... }`), and the selective handle + re-raise +// pattern. Value-carrying `-> (T, !)` catch (binding the success value) lands +// with the tuple ABI in E2. + +#import "modules/std.sx"; + +E :: error { Bad, Empty } + +must :: (n: s32) -> !E { + if n < 0 { raise error.Bad; } + if n == 0 { raise error.Empty; } + return; +} + +// Diverging body — returns from `classify` on error. +classify :: (n: s32) -> s32 { + must(n) catch e { + if e == error.Bad { return 1; } + if e == error.Empty { return 2; } + return 9; + }; + return 0; // must(n) succeeded +} + +// Match-body form — sugar for `catch e { if e == { case ... } }`. +mclassify :: (n: s32) -> s32 { + must(n) catch e == { + case .Bad: return 11; + case .Empty: return 22; + else: return 99; + }; + return 0; +} + +// Selective handle + re-raise (failable enclosing fn; `raise e` is the +// variable form). Swallows Bad → success; re-raises everything else. +handle_some :: (n: s32) -> !E { + must(n) catch e { + if e == error.Bad { return; } // swallow → success + raise e; // re-raise the rest + }; + return; +} + +main :: () -> s32 { + r : s32 = 0; + must(-1) catch e { if e == error.Bad { r = r + 1; } }; // Bad → +1 + must(5) catch { r = r + 100; }; // success → body skipped + r = r + classify(0); // Empty → 2 + r = r + classify(8); // success → 0 + he := handle_some(0); // Empty re-raised + if he == error.Empty { r = r + 4; } // +4 + hb := handle_some(-1); // Bad swallowed → success + if hb == error.Bad { r = r + 50; } // not taken + r = r + mclassify(-1); // Bad → 11 + print("catch result: {}\n", r); // 1+2+4+11 = 18 + return r; +} diff --git a/examples/227-catch-rejections.sx b/examples/227-catch-rejections.sx new file mode 100644 index 0000000..7e91a1c --- /dev/null +++ b/examples/227-catch-rejections.sx @@ -0,0 +1,13 @@ +// `catch` rejection (ERR step E1.5): the operand must be failable. Unlike +// `try` / `raise`, `catch` needs no failable enclosing function — it consumes +// the error locally — so the only stable rejection is a non-failable operand. +// The positive cases live in `examples/226-catch.sx`. + +#import "modules/std.sx"; + +plain :: () -> s32 { return 0; } + +main :: () -> s32 { + plain() catch e { return 1; }; // error: operand has type s32 (not failable) + return 0; +} diff --git a/src/ir/lower.zig b/src/ir/lower.zig index a862c5a..4916658 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -2571,6 +2571,7 @@ pub const Lowering = struct { }, .try_expr => |te| self.lowerTry(te.operand, node.span), + .catch_expr => |ce| self.lowerCatch(&ce, node.span), else => self.emitError("unknown_expr", node.span), }; } @@ -3707,6 +3708,15 @@ pub const Lowering = struct { } break :blk false; }; + // An error-set subject (`catch e == { case .X: ... }` / `if e == { ... }`): + // the value IS its u32 tag id, and `case .X` matches the global tag id + // of `X`. Used by ERR E1.5's catch match-body form. + const is_error_set_match = blk: { + if (!subject_ty.isBuiltin()) { + break :blk self.module.types.get(subject_ty) == .error_set; + } + break :blk false; + }; // Determine if the match produces a value (has non-void arms) // For type-category matches (inside any_to_string), only produce value when force_block_value @@ -3823,6 +3833,9 @@ pub const Lowering = struct { const ty_name = self.formatTypeName(subject_ty); diags.addFmt(.err, pat.span, "no variant '{s}' on type '{s}'", .{ pat_name, ty_name }); } + } else if (ty_info == .error_set) { + // `case .X` matches the global tag id of `X`. + break :blk @intCast(self.module.types.internTag(pat_name)); } } break :blk @intCast(i); @@ -3848,7 +3861,7 @@ pub const Lowering = struct { break :tag_blk self.builder.emit(.{ .unbox_any = .{ .operand = subject } }, .s64); } break :tag_blk subject; - } else if (is_optional_match) self.builder.emit(.{ .optional_has_value = .{ .operand = subject } }, .bool) else blk: { + } else if (is_optional_match) self.builder.emit(.{ .optional_has_value = .{ .operand = subject } }, .bool) else if (is_error_set_match) subject else blk: { // Determine actual tag type from union info (e.g. u32 for SDL_Event) const tag_ty: TypeId = tt: { if (!subject_ty.isBuiltin()) { @@ -13584,6 +13597,16 @@ pub const Lowering = struct { if (info == .tuple and info.tuple.fields.len == 2) break :blk info.tuple.fields[0]; break :blk op_ty; }, + // `expr catch ...` strips the error channel → the success type + // (void for a pure-failable LHS; the value part for value-carrying). + .catch_expr => |ce| blk: { + const op_ty = self.inferExprType(ce.operand); + const channel = self.errorChannelOf(op_ty) orelse break :blk .unresolved; + if (op_ty == channel) break :blk .void; + const info = self.module.types.get(op_ty); + if (info == .tuple and info.tuple.fields.len == 2) break :blk info.tuple.fields[0]; + break :blk op_ty; + }, .if_expr => |ie| { // If-else types as its branches' unified type. A `noreturn` // branch (one that diverges — `return` / `raise` / `break` / @@ -15241,6 +15264,65 @@ pub const Lowering = struct { } } + /// `expr catch [e] BODY` — inline failure handler (ERR step E1.5, + /// pure-failable slice). Evaluates `expr`; on failure, binds the tag to + /// `e` (if present) and runs BODY; on success, the value is `void` (a + /// pure-failable LHS has no success value). BODY either diverges (via + /// `noreturn` — E1.4c) or falls through. `catch` consumes the error + /// locally, so — unlike `try` / `raise` — it needs no failable *enclosing* + /// function. Value-carrying LHS (binding the success value / a + /// value-producing body unifying with the success tuple) needs the + /// error-channel tuple ABI and lands in E2 — bail loudly here. + fn lowerCatch(self: *Lowering, ce: *const ast.CatchExpr, span: ast.Span) Ref { + const op_ty = self.inferExprType(ce.operand); + const err_set = self.errorChannelOf(op_ty) orelse { + if (self.diagnostics) |diags| { + diags.addFmt(.err, span, "`catch` requires a failable expression; operand has type '{s}'", .{self.formatTypeName(op_ty)}); + } + return self.builder.constInt(0, .void); + }; + if (op_ty != err_set) { + if (self.diagnostics) |diags| { + diags.addFmt(.err, span, "`catch` on a value-carrying failable (`-> (T..., !)`) is not yet lowered — pending the error-channel tuple ABI (ERR E2)", .{}); + } + return self.builder.constInt(0, .void); + } + + // Evaluate the operand → the error tag (0 = success), then branch. + const err_val = self.lowerExpr(ce.operand); + const err_ty = self.builder.getRefType(err_val); + const zero = self.builder.constInt(0, err_ty); + const is_err = self.builder.emit(.{ .cmp_ne = .{ .lhs = err_val, .rhs = zero } }, .bool); + + const handle_bb = self.freshBlock("catch.handle"); + const merge_bb = self.freshBlock("catch.merge"); + // On success (err == 0) jump straight to the merge; on error, handle. + self.builder.condBr(is_err, handle_bb, &.{}, merge_bb, &.{}); + + // Handle: bind the tag (typed as the error set) and run the body in a + // child scope. The body diverges (terminates the block) or falls + // through to the merge. + self.builder.switchToBlock(handle_bb); + var handle_scope = Scope.init(self.alloc, self.scope); + const saved_scope = self.scope; + self.scope = &handle_scope; + if (ce.binding) |name| { + handle_scope.put(name, .{ .ref = err_val, .ty = err_set, .is_alloca = false }); + } + if (ce.body.data == .block) { + self.lowerBlock(ce.body); + } else { + _ = self.lowerExpr(ce.body); + } + self.scope = saved_scope; + handle_scope.deinit(); + if (!self.currentBlockHasTerminator()) self.builder.br(merge_bb, &.{}); + + // Merge (success path + non-diverging handle). Pure-failable → void. + self.builder.switchToBlock(merge_bb); + return self.builder.constInt(0, .void); + } + fn bailTry(self: *Lowering, span: ast.Span, comptime what: []const u8) Ref { if (self.diagnostics) |diags| { diags.addFmt(.err, span, "`try` with " ++ what ++ " is not yet lowered — pending the error-channel tuple ABI (ERR E2)", .{}); diff --git a/tests/expected/226-catch.exit b/tests/expected/226-catch.exit new file mode 100644 index 0000000..3c03207 --- /dev/null +++ b/tests/expected/226-catch.exit @@ -0,0 +1 @@ +18 diff --git a/tests/expected/226-catch.txt b/tests/expected/226-catch.txt new file mode 100644 index 0000000..2dfce24 --- /dev/null +++ b/tests/expected/226-catch.txt @@ -0,0 +1 @@ +catch result: 18 diff --git a/tests/expected/227-catch-rejections.exit b/tests/expected/227-catch-rejections.exit new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/tests/expected/227-catch-rejections.exit @@ -0,0 +1 @@ +1 diff --git a/tests/expected/227-catch-rejections.txt b/tests/expected/227-catch-rejections.txt new file mode 100644 index 0000000..6372888 --- /dev/null +++ b/tests/expected/227-catch-rejections.txt @@ -0,0 +1,5 @@ +error: `catch` requires a failable expression; operand has type 's32' + --> /Users/agra/projects/sx/examples/227-catch-rejections.sx:11:5 + | +11 | plain() catch e { return 1; }; // error: operand has type s32 (not failable) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^