Commit 2772baa0

2772baa049d2Merged

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

Description

codegen: bind a value-type receiver by value in instance_exec trampolines

An instance_exec trampoline (def m(&b); instance_exec(args, &b); end) inlines at the call site by rebinding self to a temp holding the receiver. The splice always declared that temp as a pointer (sp_X *_t = <recv>), which is a type error when the receiver class is value-type-promoted: such a receiver is a by-value struct (sp_X), not sp_X *.

Bind the rebound self by value and dereference its ivars with . (via g_self_deref) when the receiver class is a value type; keep the pointer form otherwise. Value types are immutable, so the by-value copy is transparent. This matches the direct-instance_exec value-type path (a value-type class that stays heap-allocated is unaffected -- it keeps the pointer form).

Refs #1374

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

Details

Commit
2772baa049d2
Parent
e16d3e7fd82f

src/codegen_call.cmodifiedView file

@@ -1854,11 +1854,17 @@
18541854 TyKind body_ty = ie_bn > 0 ? comp_ntype(c, ie_bb[ie_bn - 1]) : TY_NIL;
18551855 int scalar_res = is_scalar_ret(body_ty) && body_ty != TY_VOID && body_ty != TY_NIL && body_ty != TY_UNKNOWN;
18561856 int tr = ++g_tmp, tres = ++g_tmp;
1857+ int self_is_val = c->classes[cls_id].is_value_type;
18571858 Buf rb; memset(&rb, 0, sizeof rb);
18581859 if (ie_self_cls >= 0) buf_puts(&rb, g_self); /* implicit self */
18591860 else emit_expr(c, recv, &rb);
18601861 emit_indent(g_pre, g_indent);
1861- buf_printf(g_pre, "sp_%s *_t%d = %s;\n", c->classes[cls_id].name, tr, rb.p ? rb.p : "NULL");
1862+ /* A value-type receiver is a stack struct, not a pointer: bind the
1863+ rebound self by value and dereference its ivars with `.` in the
1864+ splice. Value types are immutable, so the copy is transparent. */
1865+ buf_printf(g_pre, "sp_%s %s_t%d = %s;\n", c->classes[cls_id].name,
1866+ self_is_val ? "" : "*", tr,
1867+ rb.p ? rb.p : (self_is_val ? "{0}" : "NULL"));
18621868 free(rb.p);
18631869 if (scalar_res) {
18641870 emit_indent(g_pre, g_indent); emit_ctype(c, body_ty, g_pre);
@@ -1866,6 +1872,7 @@
18661872 }
18671873 char selfbuf[64]; snprintf(selfbuf, sizeof selfbuf, "_t%d", tr);
18681874 const char *saved_self2 = g_self; g_self = selfbuf;
1875+ const char *saved_deref2 = g_self_deref; g_self_deref = self_is_val ? "." : "->";
18691876 int saved_ie = g_ie_class_id; g_ie_class_id = cls_id;
18701877 /* Bind the block params (interned in the enclosing scope, declared
18711878 there): instance_exec assigns the call-site args; instance_eval
@@ -1991,6 +1998,7 @@
19911998 }
19921999 g_ie_class_id = saved_ie;
19932000 g_self = saved_self2;
2001+ g_self_deref = saved_deref2;
19942002 if (scalar_res) buf_printf(b, "_t%d", tres);
19952003 else buf_printf(b, "_t%d", tr); /* statement use: value is the receiver */
19962004 return;