Commit 5b6a4768
5b6a47688f64Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 7 files · +2 added · ~5 modified
Description
Merge pull request #1510 from ryanseys/rs-enum-for-materialize
Eager-materialize enum_for(:each) / to_enum into an array
Details
- Commit
- 5b6a47688f64
- Parent
- 2b18d64321b2
- Merge parent
- 82fcba60e8de
src/analyze.cmodifiedView file
@@ -256,7 +256,9 @@
256256
}257257
if (mi < 0) return 0;258258
Scope *m = &c->scopes[mi];259-
if (!m->blk_param || !m->blk_param[0] || m->yields || m->is_lowered_yield) return 0;259+
/* A lowered yielding method also receives its block as a real proc, so a260+
block passed to it is lifted and captures enclosing locals like any other. */261+
if (!m->blk_param || !m->blk_param[0] || m->yields) return 0;260262
/* instance_eval/exec trampolines splice their block at the call site rather261263
than lifting it to a proc, so they are not lifted-block captures. */262264
if (m->class_id >= 0 && !m->is_cmethod && m->name &&@@ -1320,6 +1322,130 @@
13201322
return n;13211323
}13221324
1325+
/* Is `id` a `recv.enum_for` / `recv.to_enum` call that materializes the1326+
receiver's `#each` (no args, or a single literal `:each`), with no block?1327+
These are the forms we lower to an eager `#each`-into-array helper. */1328+
static int is_enum_for_each(const Compiler *c, int id) {1329+
const NodeTable *nt = c->nt;1330+
const char *nm = nt_str(nt, id, "name");1331+
if (!nm || (strcmp(nm, "enum_for") && strcmp(nm, "to_enum"))) return 0;1332+
if (nt_ref(nt, id, "receiver") < 0) return 0; /* need a receiver to drive */1333+
if (nt_ref(nt, id, "block") >= 0) return 0; /* a size block is unsupported */1334+
int args = nt_ref(nt, id, "arguments");1335+
int ac = 0; const int *av = args >= 0 ? nt_arr(nt, args, "arguments", &ac) : NULL;1336+
if (ac == 0) return 1; /* enum_for defaults to :each */1337+
if (ac != 1 || !av) return 0;1338+
if (!nt_type(nt, av[0]) || strcmp(nt_type(nt, av[0]), "SymbolNode")) return 0;1339+
const char *s = nt_str(nt, av[0], "value");1340+
return s && !strcmp(s, "each");1341+
}1342+
1343+
/* Rewrite every `recv.enum_for(:each)` / `recv.to_enum` into a call to the1344+
synthesized `recv.__enum_to_a`, which materializes `#each` into an array.1345+
Purely syntactic (no receiver type needed); the per-class helper is1346+
synthesized separately and pruned by reachability when unused. */1347+
static void rewrite_enum_for_each(Compiler *c) {1348+
NodeTable *nt = (NodeTable *)c->nt;1349+
/* snapshot the count: synthesis below appends nodes, which must not be rescanned */1350+
int count = nt->count;1351+
for (int id = 0; id < count; id++) {1352+
if (!nt_type(nt, id) || strcmp(nt_type(nt, id), "CallNode")) continue;1353+
if (!is_enum_for_each(c, id)) continue;1354+
int empty = nt_new_node(nt, "ArgumentsNode");1355+
nt_node_set_arr(nt, empty, "arguments", NULL, 0);1356+
nt_node_set_str(nt, id, "name", "__enum_to_a");1357+
nt_node_set_ref(nt, id, "arguments", empty);1358+
comp_grow_node_arrays(c);1359+
c->nscope[empty] = c->nscope[id];1360+
}1361+
}1362+
1363+
/* Synthesize, on every class that defines an instance `#each` that yields, a1364+
helper method1365+
1366+
def __enum_to_a1367+
__enum_acc = []1368+
each { |__enum_e| __enum_acc << __enum_e }1369+
__enum_acc1370+
end1371+
1372+
so an `enum_for(:each)` rewritten to `__enum_to_a` materializes the receiver1373+
eagerly into an array (then map/select/to_a/... use the array path). The1374+
helper is a normal method whose body is inferred and emitted by the usual1375+
machinery; when `#each` is force-lowered the inlined `each { }` becomes a1376+
real call passing the block as a proc. Unused helpers are pruned by1377+
reachability, so this is inert for programs that never call enum_for/to_enum1378+
(the self-host compiler included). */1379+
static void synth_enum_to_a(Compiler *c) {1380+
NodeTable *nt = (NodeTable *)c->nt;1381+
if (c->nscopes == 0) return;1382+
/* collect target classes first (synthesis below grows c->scopes). At most one1383+
entry per scope, so pre-size both arrays to nscopes and avoid per-item growth. */1384+
int *cls = malloc(sizeof(int) * (size_t)c->nscopes);1385+
int *eachdef = malloc(sizeof(int) * (size_t)c->nscopes);1386+
if (!cls || !eachdef) { fprintf(stderr, "spinel: out of memory\n"); exit(1); }1387+
int ncls = 0;1388+
for (int s = 0; s < c->nscopes; s++) {1389+
Scope *m = &c->scopes[s];1390+
if (!m->name || m->is_cmethod || m->class_id < 0) continue;1391+
if (strcmp(m->name, "each") || !m->yields) continue;1392+
if (comp_method_in_class(c, m->class_id, "__enum_to_a") >= 0) continue;1393+
int dup = 0;1394+
for (int k = 0; k < ncls; k++) if (cls[k] == m->class_id) { dup = 1; break; }1395+
if (dup) continue;1396+
cls[ncls] = m->class_id; eachdef[ncls] = m->def_node; ncls++;1397+
}1398+
for (int k = 0; k < ncls; k++) {1399+
int arr = nt_new_node(nt, "ArrayNode");1400+
nt_node_set_arr(nt, arr, "elements", NULL, 0);1401+
int accw = nt_new_node(nt, "LocalVariableWriteNode");1402+
nt_node_set_str(nt, accw, "name", "__enum_acc");1403+
nt_node_set_ref(nt, accw, "value", arr);1404+
int ep = nt_new_node(nt, "RequiredParameterNode");1405+
nt_node_set_str(nt, ep, "name", "__enum_e");1406+
int params = nt_new_node(nt, "ParametersNode");1407+
nt_node_set_arr(nt, params, "requireds", &ep, 1);1408+
int bparams = nt_new_node(nt, "BlockParametersNode");1409+
nt_node_set_ref(nt, bparams, "parameters", params);1410+
int accr1 = nt_new_node(nt, "LocalVariableReadNode");1411+
nt_node_set_str(nt, accr1, "name", "__enum_acc");1412+
int eread = nt_new_node(nt, "LocalVariableReadNode");1413+
nt_node_set_str(nt, eread, "name", "__enum_e");1414+
int pushargs = nt_new_node(nt, "ArgumentsNode");1415+
nt_node_set_arr(nt, pushargs, "arguments", &eread, 1);1416+
int push = nt_new_node(nt, "CallNode");1417+
nt_node_set_str(nt, push, "name", "<<");1418+
nt_node_set_ref(nt, push, "receiver", accr1);1419+
nt_node_set_ref(nt, push, "arguments", pushargs);1420+
int blkbody = nt_new_node(nt, "StatementsNode");1421+
nt_node_set_arr(nt, blkbody, "body", &push, 1);1422+
int blk = nt_new_node(nt, "BlockNode");1423+
nt_node_set_ref(nt, blk, "parameters", bparams);1424+
nt_node_set_ref(nt, blk, "body", blkbody);1425+
int eachcall = nt_new_node(nt, "CallNode");1426+
nt_node_set_str(nt, eachcall, "name", "each");1427+
nt_node_set_ref(nt, eachcall, "block", blk);1428+
int accr2 = nt_new_node(nt, "LocalVariableReadNode");1429+
nt_node_set_str(nt, accr2, "name", "__enum_acc");1430+
int body = nt_new_node(nt, "StatementsNode");1431+
int stmts[3] = { accw, eachcall, accr2 };1432+
nt_node_set_arr(nt, body, "body", stmts, 3);1433+
1434+
Scope *ms = comp_scope_new(c, "__enum_to_a", eachdef[k]);1435+
ms->class_id = cls[k];1436+
ms->body = body;1437+
int ms_idx = c->nscopes - 1;1438+
/* register_locals already ran (before synthesis), so intern this scope's1439+
locals here; types are filled in by the inference fixpoint that follows. */1440+
scope_local_intern(ms, "__enum_acc");1441+
LocalVar *ev = scope_local_intern(ms, "__enum_e");1442+
if (ev) ev->is_block_param = 1;1443+
comp_grow_node_arrays(c);1444+
walk_scope(c, body, ms_idx, cls[k]);1445+
}1446+
free(cls); free(eachdef);1447+
}1448+
13231449
void analyze_program(Compiler *c) {13241450
/* scope 0 = top level */13251451
Scope *top = comp_scope_new(c, NULL, -1);@@ -1425,6 +1551,13 @@
14251551
}14261552
}14271553
1554+
/* Eager Enumerable-via-#each: rewrite `enum_for(:each)`/`to_enum` to a1555+
synthesized per-class `__enum_to_a` helper that materializes #each into an1556+
array. Done before the inference fixpoint so the helper's body is typed,1557+
and before reachability so the helper is kept only when actually called. */1558+
rewrite_enum_for_each(c);1559+
synth_enum_to_a(c);1560+
14281561
/* `&block` + block.call: a method whose block parameter never escapes14291562
(every read is a `.call` receiver or a `&block` forward) is inlined at14301563
its call sites exactly like a yielding method. The block-param slot is@@ -1838,6 +1971,32 @@
18381971
detect_bigint_loop_vars(c);18391972
propagate_bigint_cascade(c);18401973
1974+
/* Force-lower `#each` for any class whose synthesized `__enum_to_a` helper is1975+
actually called (an `enum_for`/`to_enum` survived the rewrite). The helper1976+
drives `#each` with a collector block; the real (lowered) function form1977+
passes that block as a proc. Done BEFORE mark_proc_captures so the1978+
collector block lifts and its `__enum_acc` accumulator gets a heap cell. */1979+
for (int id = 0; id < c->nt->count; id++) {1980+
const char *ty = nt_type(c->nt, id);1981+
if (!ty || strcmp(ty, "CallNode")) continue;1982+
const char *nm = nt_str(c->nt, id, "name");1983+
if (!nm || strcmp(nm, "__enum_to_a")) continue;1984+
int recv = nt_ref(c->nt, id, "receiver");1985+
if (recv < 0) continue;1986+
TyKind rt = infer_type(c, recv);1987+
if (!ty_is_object(rt)) continue;1988+
int ec = comp_method_in_chain(c, ty_object_class(rt), "each", NULL);1989+
if (ec < 0) continue;1990+
Scope *m = &c->scopes[ec];1991+
if (m->blk_param || !m->yields) continue; /* already lowered, or no yielding each */1992+
m->is_lowered_yield = 1;1993+
m->yields = 0;1994+
m->ret = TY_INT;1995+
m->blk_param = strdup("__yblk__");1996+
LocalVar *yblk = scope_local_intern(m, "__yblk__");1997+
if (yblk) { yblk->type = TY_PROC; yblk->is_param = 1; yblk->is_cell = 1; }1998+
}1999+
18412000
/* mark locals captured by escaping procs (they need heap cells) */18422001
mark_proc_captures(c);18432002
src/codegen_call.cmodifiedView file
Loading diff…
src/codegen_expr.cmodifiedView file
Loading diff…
src/codegen_internal.hmodifiedView file
Loading diff…
src/codegen_stmt.cmodifiedView file
Loading diff…
test/enum_for_each.rbaddedView file
Loading diff…
test/enum_for_each.rb.expectedaddedView file
Loading diff…