fix(lower): closure literals compose with bare function-type slots (issue 0060)

A closure's underlying function carries a hidden env arg that a bare (T)->U slot
doesn't pass, so a closure flowing into a bare function-type slot dropped the
env — the first user arg landed in the env slot and the rest read garbage
(apply(closure((x)->s64 { x*2 })) returned 192 instead of 10; non-failable too).

- createClosureToBareFnAdapter: a capture-free closure into a bare (T)->U slot is
  bridged by a generated adapter carrying the bare ABI (forwards a null env);
  lowerLambda returns its func_ref. Rejected (no silent miscompile): a capturing
  closure into a bare slot (env has nowhere to live) and a failable closure into
  a non-failable slot (the ERR E5.1 FFI-boundary rule).
- Arrow-body failable closures (-> (T,!) => expr) now wrap the bare success value
  into {value, 0} via lowerFailableSuccessReturn (the implicit return previously
  returned a malformed tuple → caught value read as 0).

The isLambda .bang parser fix (failable closure literals parse) already landed in
485b4fa. Regressions: examples/0309-closures-literal-as-bare-fn-param (non-
failable, block + arrow, called in callee) + 1039-errors-failable-closure-literal
(failable, block + arrow, direct + Closure(...) param). Resolves issue 0060
(remaining E5.1 follow-ups noted in the .md). Suite: 328 passed.
This commit is contained in:
agra
2026-06-01 20:35:25 +03:00
parent 485b4fa618
commit 06e2685350
11 changed files with 176 additions and 17 deletions

View File

@@ -7848,8 +7848,15 @@ pub const Lowering = struct {
if (self.lowerBlockValue(lam.body)) |val| {
if (!self.currentBlockHasTerminator()) {
const val_ty = self.builder.getRefType(val);
const coerced = if (val_ty != .void) self.coerceToType(val, val_ty, ret_ty) else val;
self.builder.ret(coerced, ret_ty);
// A value-carrying failable arrow lambda (`-> (T, !) => expr`)
// yields the bare success value; the compiler appends the
// no-error slot (0) — same as a `return v` in a block body.
if (!ret_ty.isBuiltin() and self.module.types.get(ret_ty) == .tuple and self.errorChannelOf(ret_ty) != null) {
self.lowerFailableSuccessReturn(val, ret_ty, lam.body.span);
} else {
const coerced = if (val_ty != .void) self.coerceToType(val, val_ty, ret_ty) else val;
self.builder.ret(coerced, ret_ty);
}
}
}
} else {
@@ -7874,6 +7881,29 @@ pub const Lowering = struct {
// surrounding `push Context.{ allocator = ... }`.
self.current_ctx_ref = saved_ctx_ref_lam;
// Closure flowing into a BARE function-pointer slot (`(T) -> U`, no env):
// the slot is called without the closure env arg, so the closure fn can't
// be passed directly. For a capture-free closure whose return type matches
// the slot, emit an adapter with the bare ABI. Reject the cases the bare
// ABI can't represent: a capturing closure (env has nowhere to live), and
// a failable closure into a non-failable slot (foreign code can't observe
// the error channel — ERR E5.1 FFI-boundary rule).
if (self.target_type) |tt| {
if (!tt.isBuiltin() and self.module.types.get(tt) == .function) {
const slot_ret = self.module.types.get(tt).function.ret;
if (capture_list.len > 0) {
if (self.diagnostics) |d| d.addFmt(.err, lam.body.span, "a capturing closure cannot be passed as a bare function pointer; declare the parameter type as `Closure(...)` so its environment is carried", .{});
} else if (ret_ty == slot_ret) {
const adapter = self.createClosureToBareFnAdapter(func_id, self.module.types.get(tt).function);
return self.builder.emit(.{ .func_ref = adapter }, tt);
} else if (self.errorChannelOf(ret_ty) != null and self.errorChannelOf(slot_ret) == null) {
if (self.diagnostics) |d| d.addFmt(.err, lam.body.span, "failable closure cannot be assigned to a non-failable function-type slot; foreign code can't observe the error channel — handle the error in a wrapper closure that absorbs it", .{});
} else if (self.diagnostics) |d| {
d.addFmt(.err, lam.body.span, "closure return type does not match the function-type slot", .{});
}
}
}
// Create proper closure type (user-visible params only — skip ctx + env).
const skip_count: usize = if (lambda_wants_ctx) 2 else 1;
var param_types_list = std.ArrayList(TypeId).empty;
@@ -7992,6 +8022,72 @@ pub const Lowering = struct {
return func_id;
}
/// Adapter for coercing a closure into a BARE function-pointer slot
/// (`(T) -> U`, no env). The closure's underlying function has signature
/// `[ctx?] + env + user-params`, but a bare fn-ptr slot is *called* without
/// the env arg — so the closure fn can't be used directly (the env slot
/// would swallow the first user arg). This adapter carries the bare ABI
/// (`[ctx?] + user-params`) and forwards to the closure fn with a null env.
/// Only sound for capture-free closures (a null env is correct iff the body
/// reads no captures); the caller rejects capturing closures.
fn createClosureToBareFnAdapter(self: *Lowering, closure_func_id: FuncId, fn_info: types.TypeInfo.FunctionInfo) FuncId {
var params = std.ArrayList(inst_mod.Function.Param).empty;
defer params.deinit(self.alloc);
const void_ptr_ty = self.module.types.ptrTo(.void);
const wants_ctx = self.implicit_ctx_enabled;
if (wants_ctx) {
params.append(self.alloc, .{ .name = self.module.types.internString("__sx_ctx"), .ty = void_ptr_ty }) catch unreachable;
}
for (fn_info.params, 0..) |pty, i| {
var buf: [32]u8 = undefined;
const pname = std.fmt.bufPrint(&buf, "a{d}", .{i}) catch "arg";
params.append(self.alloc, .{ .name = self.module.types.internString(pname), .ty = pty }) catch unreachable;
}
const closure_func = self.module.functions.items[closure_func_id.index()];
const closure_name = self.module.types.getString(closure_func.name);
var name_buf: [128]u8 = undefined;
const adapter_name = std.fmt.bufPrint(&name_buf, "__cl2fn_{s}", .{closure_name}) catch "__cl2fn";
const adapter_name_id = self.module.types.internString(adapter_name);
const saved_func = self.builder.func;
const saved_block = self.builder.current_block;
const saved_counter = self.builder.inst_counter;
const owned_params = self.alloc.dupe(inst_mod.Function.Param, params.items) catch unreachable;
var func = inst_mod.Function.init(adapter_name_id, owned_params, fn_info.ret);
func.has_implicit_ctx = wants_ctx;
const func_id = self.module.addFunction(func);
self.builder.func = func_id;
self.builder.inst_counter = @intCast(owned_params.len);
const entry_name = self.module.types.internString("entry");
const entry_block = self.builder.appendBlock(entry_name, &.{});
self.builder.switchToBlock(entry_block);
// Forward [ctx?] + null env + user params to the closure fn.
const ctx_slots: usize = if (wants_ctx) 1 else 0;
var call_args = std.ArrayList(Ref).empty;
defer call_args.deinit(self.alloc);
if (wants_ctx) call_args.append(self.alloc, Ref.fromIndex(0)) catch unreachable;
call_args.append(self.alloc, self.builder.constNull(void_ptr_ty)) catch unreachable;
for (fn_info.params, 0..) |_, i| {
call_args.append(self.alloc, Ref.fromIndex(@intCast(ctx_slots + i))) catch unreachable;
}
const owned_args = self.alloc.dupe(Ref, call_args.items) catch unreachable;
const result = self.builder.emit(.{ .call = .{ .callee = closure_func_id, .args = owned_args } }, fn_info.ret);
if (fn_info.ret != .void) {
self.builder.ret(result, fn_info.ret);
} else {
self.builder.retVoid();
}
self.builder.finalize();
self.builder.func = saved_func;
self.builder.current_block = saved_block;
self.builder.inst_counter = saved_counter;
return func_id;
}
/// Walk an AST node and collect free variable references (identifiers that are
/// in the current scope but not in lambda params).
fn collectCaptures(self: *Lowering, node: *const Node, param_names: *std.StringHashMap(void), captures: *std.ArrayList(CaptureInfo)) void {