Commit 2ca741a2

2ca741a22239Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 5 files · +2 added · ~3 modified

Description

codegen: Proc#curry over the lambda-arena representation

Add a "curried" type plus runtime support so f.curry[a][b]... works. sp_lam_curry wraps a lambda with its arity; each []/call supplies one argument and returns either a fresh curried proc or, once the arity is reached, the materialised result, the runtime tag distinguishing the two. The lambda's arity is recorded at definition (required-param count) and threaded into sp_lam_curry. A curried value stays typed "curried" (an sp_Val *, never auto-unboxed) through assignment and chaining; consuming it (e.g. puts) reads the final value via sp_lam_to_int. infer_type resolves curry chains from the receiver so a stale cache entry cannot mistype the bracket call.

Fixes #919

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
2ca741a22239
Parent
b8f582b3d120

lib/sp_runtime.hmodifiedView file

@@ -3726,6 +3726,30 @@
37263726 The codegen swaps operands for `>>`. */
37273727 static sp_Val *sp_lam_compose_fn(sp_Val *self, sp_Val *arg) { return sp_lam_call(self->captures[0], sp_lam_call(self->captures[1], arg)); }
37283728 static sp_Val *sp_lam_compose(sp_Val *outer, sp_Val *inner) { sp_Val *v = sp_lam_proc(sp_lam_compose_fn, 2); v->captures[0] = outer; v->captures[1] = inner; return v; }
3729+/* Proc#curry over the sp_Val * representation. The curried value is a
3730+ proc whose captures are [target, arity, arg0, arg1, ...]; applying
3731+ one more arg either returns a fresh curried proc (still short of
3732+ arity) or invokes the target with the full argument list. Each `[]`
3733+ application supplies a single argument. */
3734+static sp_Val *sp_lam_curry_fn(sp_Val *self, sp_Val *arg) {
3735+ sp_Val *target = self->captures[0];
3736+ mrb_int arity = self->captures[1]->u.ival;
3737+ int have = self->u.proc.ncaptures - 2;
3738+ if (have + 1 < arity) {
3739+ sp_Val *v = sp_lam_proc(sp_lam_curry_fn, self->u.proc.ncaptures + 1);
3740+ v->captures[0] = target;
3741+ v->captures[1] = self->captures[1];
3742+ for (int i = 0; i < have; i++) v->captures[2 + i] = self->captures[2 + i];
3743+ v->captures[2 + have] = arg;
3744+ return v;
3745+ }
3746+ if (arity == 1) return sp_lam_call(target, arg);
3747+ if (arity == 2) return sp_lam_call2(target, self->captures[2], arg);
3748+ if (arity == 3) return sp_lam_call3(target, self->captures[2], self->captures[3], arg);
3749+ if (arity == 4) return sp_lam_call4(target, self->captures[2], self->captures[3], self->captures[4], arg);
3750+ return &sp_lam_nil_val;
3751+}
3752+static sp_Val *sp_lam_curry(sp_Val *f, mrb_int arity) { sp_Val *v = sp_lam_proc(sp_lam_curry_fn, 2); v->captures[0] = f; v->captures[1] = sp_lam_int(arity); return v; }
37293753 static mrb_int sp_lam_to_int(sp_Val *v) { return v->u.ival; }
37303754
37313755 /* ---- Fiber runtime (ucontext) ---- */