ERR/E5.1: reject closure-value into bare function-pointer slot

A closure VALUE (a pre-bound variable) flowing into a bare (T)->U slot
was passed unsoundly: the bare ABI calls fn_ptr(ctx, args) with no env
channel, so the closure's underlying fn (which takes an env slot) had its
env dropped and args shifted — UB for a matching ABI, a wrong-tuple read
for the non-failable->failable widening (returned -1), and a segfault when
the closure captured.

coerceToType now rejects a .closure -> .function coercion with a
diagnostic pointing at the idiom (pass the literal directly, which gets
the static adapter, or type the parameter Closure(...) so the env is
carried). Closure LITERALS are unaffected — lowerLambda pre-adapts them to
a .function-typed value before coercion.

Regression: 1045-errors-closure-var-bare-slot-reject.sx.
This commit is contained in:
agra
2026-06-01 22:44:20 +03:00
parent 1c14383495
commit 2e6e031233
5 changed files with 64 additions and 0 deletions

View File

@@ -15364,6 +15364,24 @@ pub const Lowering = struct {
return self.builder.boxAny(val, src_ty);
}
// Closure VALUE → bare function-pointer slot: not soundly representable.
// A bare `(T) -> U` slot is called as `fn_ptr(ctx, args)` with NO env
// arg, but a closure's underlying fn takes an env slot — so passing a
// closure value's fn_ptr drops the env and shifts the args (UB for a
// matching ABI, a wrong-tuple read for ∅-widening, a segfault when the
// closure captures). Only a closure LITERAL can cross this boundary,
// via the static adapter `lowerLambda` emits (so a literal arrives here
// already typed `.function`). Reject the variable case loudly.
if (!src_ty.isBuiltin() and !dst_ty.isBuiltin()) {
if (self.module.types.get(src_ty) == .closure and self.module.types.get(dst_ty) == .function) {
if (self.diagnostics) |d| {
const cs = self.builder.current_span;
d.addFmt(.err, ast.Span{ .start = cs.start, .end = cs.end }, "a closure value cannot be passed as a bare function-pointer `(...) -> ...` — its environment can't be carried across the bare ABI; pass the closure literal directly at the call site, or declare the parameter type as `Closure(...)`", .{});
}
return val;
}
}
// Tuple → Tuple element-wise coercion (e.g. a `(s64, s64)` literal
// flowing into a `(s32, s32)` slot — the multi-value failable success
// tuple). Same arity, at least one differing field (src_ty == dst_ty