Commit b85092e4

b85092e4c50fMerged

Ryan Seys <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): assign self-recursive Proc bindings through the int cell

A proc that refers to its own binding (f = proc { f.call(...) }) captures that binding in an int cell holding the sp_Proc* as (mrb_int)(uintptr_t). emit_assign emitted the cell's read form -- (sp_Proc *)(uintptr_t)(*_cell_f) -- as the assignment target, which is a cast rvalue and not assignable, so the generated C failed to compile.

Write through the raw cell deref instead (*_cell_f / *((cap *)_cap)->f) and re-encode the right-hand sp_Proc* as (mrb_int)(uintptr_t), mirroring how the cell is initialised and read.

test/proc_recursive.rb covers a self-recursive proc and -> lambda with a single recursive .call per expression. Two poly-returning proc calls in one expression (e.g. naive fib's fib.call(n-1) + fib.call(n-2)) instead exercise the shared _sp_proc_poly_ret slot, whose unsequenced reads are compiler-order dependent -- an orthogonal limitation left for separate work.

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
b85092e4c50f
Parent
34f8cd5461a2

src/codegen_stmt.cmodifiedView file

@@ -401,6 +401,23 @@
401401 int v = nt_ref(c->nt, id, "value");
402402 LocalVar *lv = scope_local(comp_scope_of(c, id), nm);
403403 emit_indent(b, indent);
404+ /* A TY_PROC value lives in an int cell as (mrb_int)(uintptr_t)sp_Proc*. The
405+ write target must be the raw cell deref (an lvalue) with the pointer
406+ re-encoded as int; emit_local_ref's read form casts to sp_Proc* and is not
407+ assignable (self-recursive `f = proc { f.call(...) }`). */
408+ if (lv && lv->type == TY_PROC &&
409+ (lv->is_cell || (g_cap_struct && g_cap_names && nameset_has(g_cap_names, nm)))) {
410+ if (g_cap_struct && g_cap_names && nameset_has(g_cap_names, nm))
411+ buf_printf(b, "*((%s *)_cap)->%s", g_cap_struct, nm);
412+ else
413+ buf_printf(b, "*_cell_%s", nm);
414+ buf_puts(b, " = (mrb_int)(uintptr_t)(");
415+ const char *pvty = nt_type(c->nt, v);
416+ if (pvty && !strcmp(pvty, "NilNode")) buf_puts(b, "NULL");
417+ else emit_expr(c, v, b);
418+ buf_puts(b, ");\n");
419+ return;
420+ }
404421 emit_local_ref(c, id, nm, b);
405422 buf_puts(b, " = ");
406423 /* `x = nil` -> the variable's type-appropriate default */