Commit d6f31986

d6f319863881Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · ~4 modified

Description

First-class Proc: closures via heap cells (capture + mutation)

A proc that captures an enclosing local now compiles instead of aborting. Captured locals live in heap cells (mrb_int *) shared by pointer between the enclosing scope and the proc, so mutation propagates both ways and the cell outlives the enclosing frame (the proc's cap keeps it alive).

Mechanism (modeled on legacy's spinel -c output for closures):

  • analyze marks an enclosing local is_cell when a proc uses it AND it belongs to the enclosing scope (a param, or assigned outside any proc body). A name assigned only inside the proc stays proc-local -- Ruby's block-local rule.
  • codegen declares a cell local as mrb_int *_cell_x (params copy their incoming value in); all reads/writes route through emit_local_ref to (*_cell_x), or to (*((cap *)_cap)->x) inside the proc body.
  • each capturing proc emits a cap struct + scan; the proc-creation site allocs the cap and shares the enclosing cell pointers.

Two deliberate choices vs legacy: (1) uniform celling for a captured var's whole scope, rather than legacy's promote-at-capture-point + redirect-after -- the rewrite's emitter has no statement-position state, and is_cell is a clean static property. (2) cap_scan marks the cap struct itself (sp_gc_mark(p)) before the cells; sp_Proc_scan does not mark cap, so marking only the cells (as legacy's emitted cap_scan does) would let the cap be swept out from under a live proc -- a latent UAF its tiny test never triggers. Verified under GC pressure (50k allocations between proc creation and call; captured value persists).

Also: an assignment expression now infers as its assigned value's type (x = v -> typeof v), so a proc/method body ending in an assignment types correctly.

Scope: int captures only (cell is mrb_int *); non-int capture defers loudly.

make test: 165 pass / 5 fail / 674 error (was 164 / 5 / 675); proc_closure green, no regressions.

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

Details

Commit
d6f319863881
Parent
d126222f3d75

src/analyze.cmodifiedView file

@@ -584,6 +584,8 @@
584584 if (!strcmp(ty, "NilNode")) return TY_NIL;
585585 if (!strcmp(ty, "RangeNode")) return TY_RANGE;
586586 if (!strcmp(ty, "LambdaNode")) return TY_PROC;
587+ /* an assignment expression evaluates to the assigned value */
588+ if (!strcmp(ty, "LocalVariableWriteNode")) return infer_type(c, nt_ref(nt, id, "value"));
587589
588590 if (!strcmp(ty, "LocalVariableReadNode")) {
589591 const char *nm = nt_str(nt, id, "name");
@@ -1743,6 +1745,110 @@
17431745 #undef ADD_NAME
17441746 }
17451747
1748+/* ---- proc capture detection (closures) ----
1749+ A local read inside a proc body that isn't bound by the proc (param or a
1750+ local the body itself writes) is a captured/free variable; its enclosing
1751+ local must live in a heap cell so the closure and the enclosing scope share
1752+ mutable storage. Mark those enclosing locals is_cell. */
1753+typedef struct { const char **v; int n, cap; } ANameSet;
1754+static int aname_has(ANameSet *s, const char *nm) {
1755+ if (!nm) return 1;
1756+ for (int i = 0; i < s->n; i++) if (!strcmp(s->v[i], nm)) return 1;
1757+ return 0;
1758+}
1759+static void aname_add(ANameSet *s, const char *nm) {
1760+ if (aname_has(s, nm)) return;
1761+ if (s->n >= s->cap) { s->cap = s->cap ? s->cap * 2 : 8; s->v = realloc(s->v, sizeof(char *) * (size_t)s->cap); }
1762+ s->v[s->n++] = nm;
1763+}
1764+static int a_nested_block(const char *ty) { return ty && (!strcmp(ty, "BlockNode") || !strcmp(ty, "LambdaNode")); }
1765+static int a_is_local_node(const char *ty) {
1766+ return ty && (!strcmp(ty, "LocalVariableReadNode") || !strcmp(ty, "LocalVariableWriteNode") ||
1767+ !strcmp(ty, "LocalVariableTargetNode") || !strcmp(ty, "LocalVariableOperatorWriteNode") ||
1768+ !strcmp(ty, "LocalVariableOrWriteNode") || !strcmp(ty, "LocalVariableAndWriteNode"));
1769+}
1770+static int a_is_write_node(const char *ty) {
1771+ return ty && (!strcmp(ty, "LocalVariableWriteNode") || !strcmp(ty, "LocalVariableTargetNode") ||
1772+ !strcmp(ty, "LocalVariableOperatorWriteNode") || !strcmp(ty, "LocalVariableOrWriteNode") ||
1773+ !strcmp(ty, "LocalVariableAndWriteNode"));
1774+}
1775+/* Mark every node id in the subtree (crossing nested blocks: a node inside an
1776+ inner block is still "inside a proc"). */
1777+static void a_mark_subtree(Compiler *c, int id, char *inproc) {
1778+ if (id < 0) return;
1779+ inproc[id] = 1;
1780+ int nr = nt_num_refs(c->nt, id);
1781+ for (int i = 0; i < nr; i++) { int ch = nt_ref_at(c->nt, id, i); if (ch >= 0) a_mark_subtree(c, ch, inproc); }
1782+ int na = nt_num_arrs(c->nt, id);
1783+ for (int i = 0; i < na; i++) { int n = 0; const int *ids = nt_arr_at(c->nt, id, i, &n); for (int k = 0; k < n; k++) if (ids[k] >= 0) a_mark_subtree(c, ids[k], inproc); }
1784+}
1785+/* Names used (read or written) directly in the proc body, not crossing nested
1786+ blocks. */
1787+static void a_collect_used(Compiler *c, int id, ANameSet *out) {
1788+ if (id < 0) return;
1789+ const char *ty = nt_type(c->nt, id);
1790+ if (!ty) return;
1791+ if (a_is_local_node(ty)) aname_add(out, nt_str(c->nt, id, "name"));
1792+ int nr = nt_num_refs(c->nt, id);
1793+ for (int i = 0; i < nr; i++) { int ch = nt_ref_at(c->nt, id, i); if (ch >= 0 && !a_nested_block(nt_type(c->nt, ch))) a_collect_used(c, ch, out); }
1794+ int na = nt_num_arrs(c->nt, id);
1795+ for (int i = 0; i < na; i++) { int n = 0; const int *ids = nt_arr_at(c->nt, id, i, &n); for (int k = 0; k < n; k++) if (ids[k] >= 0 && !a_nested_block(nt_type(c->nt, ids[k]))) a_collect_used(c, ids[k], out); }
1796+}
1797+static int a_proc_params_node(Compiler *c, int create) {
1798+ const char *ty = nt_type(c->nt, create);
1799+ if (ty && !strcmp(ty, "LambdaNode")) return nt_ref(c->nt, create, "parameters");
1800+ int block = nt_ref(c->nt, create, "block");
1801+ if (block < 0) return -1;
1802+ int bp = nt_ref(c->nt, block, "parameters");
1803+ return bp < 0 ? -1 : nt_ref(c->nt, bp, "parameters");
1804+}
1805+static int a_proc_body(Compiler *c, int create) {
1806+ const char *ty = nt_type(c->nt, create);
1807+ if (ty && !strcmp(ty, "LambdaNode")) return nt_ref(c->nt, create, "body");
1808+ int block = nt_ref(c->nt, create, "block");
1809+ return block >= 0 ? nt_ref(c->nt, block, "body") : -1;
1810+}
1811+/* A name used inside a proc is captured iff it belongs to the enclosing scope:
1812+ it is an enclosing parameter, or it is assigned somewhere in the enclosing
1813+ scope OUTSIDE any proc body. (A name assigned only inside the proc is a
1814+ proc-local, not a capture -- Ruby's block-local rule.) Captured enclosing
1815+ locals get a heap cell. */
1816+static void mark_proc_captures(Compiler *c) {
1817+ const NodeTable *nt = c->nt;
1818+ char *inproc = (char *)calloc((size_t)nt->count, 1);
1819+ if (!inproc) return;
1820+ for (int id = 0; id < nt->count; id++)
1821+ if (is_proc_create(c, id)) { int body = a_proc_body(c, id); if (body >= 0) a_mark_subtree(c, body, inproc); }
1822+
1823+ for (int id = 0; id < nt->count; id++) {
1824+ if (!is_proc_create(c, id)) continue;
1825+ int body = a_proc_body(c, id);
1826+ if (body < 0) continue;
1827+ int encl = c->nscope[id];
1828+ ANameSet params = {0}, used = {0};
1829+ int pn = a_proc_params_node(c, id);
1830+ if (pn >= 0) { int rn = 0; const int *reqs = nt_arr(nt, pn, "requireds", &rn); for (int k = 0; k < rn; k++) aname_add(&params, nt_str(nt, reqs[k], "name")); }
1831+ a_collect_used(c, body, &used);
1832+ Scope *es = &c->scopes[encl];
1833+ for (int u = 0; u < used.n; u++) {
1834+ const char *nm = used.v[u];
1835+ if (aname_has(&params, nm)) continue; /* the proc's own param */
1836+ LocalVar *lv = scope_local(es, nm);
1837+ if (!lv) continue; /* not an enclosing local */
1838+ int owned = lv->is_param;
1839+ for (int w = 0; w < nt->count && !owned; w++) {
1840+ if (c->nscope[w] != encl || inproc[w]) continue;
1841+ if (!a_is_write_node(nt_type(nt, w))) continue;
1842+ const char *wn = nt_str(nt, w, "name");
1843+ if (wn && !strcmp(wn, nm)) owned = 1;
1844+ }
1845+ if (owned) lv->is_cell = 1;
1846+ }
1847+ free(params.v); free(used.v);
1848+ }
1849+ free(inproc);
1850+}
1851+
17461852 void analyze_program(Compiler *c) {
17471853 /* scope 0 = top level */
17481854 Scope *top = comp_scope_new(c, NULL, -1);
@@ -1855,6 +1961,9 @@
18551961 /* recompute returns: a method returning such a param is now poly */
18561962 for (int iter = 0; iter < 8; iter++) if (!infer_return_types(c)) break;
18571963
1964+ /* mark locals captured by escaping procs (they need heap cells) */
1965+ mark_proc_captures(c);
1966+
18581967 /* Reachability: an instance/free method is live only if its name is
18591968 referenced somewhere -- as a call name, an alias target, or a symbol
18601969 literal (covering send/method/define_method). Names never mentioned