ERR/E1.5: catch sema (pure-failable slice) + error-set match subjects

`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.
This commit is contained in:
agra
2026-05-31 21:10:56 +03:00
parent 28b18f812a
commit 0bbff9d7fb
7 changed files with 168 additions and 1 deletions

View File

@@ -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)", .{});