Commit 102e2bb5

102e2bb52557Merged

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

Description

codegen: run upto/downto block body when the block declares no parameter

The integer upto/downto block loop used the block's first parameter name directly as the C loop counter, so it only matched when the block declared a parameter. A no-parameter block (1.upto(5) { h += 1 }) fell through and its body was dropped entirely (the counter printed 0 instead of 5).

Drive the loop with a fresh temp, like n.times does, and rebind the block parameter from it each iteration only when one is declared. The rebind also makes mutating the parameter inside the block not perturb the loop, matching CRuby (1.upto(3) { |n| n += 100; ... }).

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

Details

Commit
102e2bb52557
Parent
38918e9605c0

src/codegen_call.cmodifiedView file

@@ -10742,8 +10742,10 @@
1074210742 return 1;
1074310743 }
1074410744
10745- /* n.upto(m) / n.downto(m) { |i| ... } */
10746- if ((!strcmp(name, "upto") || !strcmp(name, "downto")) && rt == TY_INT && p0) {
10745+ /* n.upto(m) / n.downto(m) { [|i|] ... } -- a fresh temp drives the loop and
10746+ the block param (if any) is rebound from it each iteration, like n.times.
10747+ A blockless-param form (`1.upto(5) { body }`) must still run the body. */
10748+ if ((!strcmp(name, "upto") || !strcmp(name, "downto")) && rt == TY_INT) {
1074710749 int up = !strcmp(name, "upto");
1074810750 int args = nt_ref(nt, id, "arguments");
1074910751 int argc = 0;
@@ -10752,10 +10754,12 @@
1075210754 if (argc != 1) return 0;
1075310755 Buf lo; memset(&lo, 0, sizeof lo); emit_expr(c, recv, &lo);
1075410756 Buf hi; memset(&hi, 0, sizeof hi); emit_expr(c, argv[0], &hi);
10757+ int ti = ++g_tmp;
1075510758 emit_indent(b, indent);
10756- buf_printf(b, "for (lv_%s = ", p0); buf_puts(b, lo.p);
10757- buf_printf(b, "; lv_%s %s ", p0, up ? "<=" : ">="); buf_puts(b, hi.p);
10758- buf_printf(b, "; lv_%s%s) {\n", p0, up ? "++" : "--");
10759+ buf_printf(b, "for (mrb_int _t%d = ", ti); buf_puts(b, lo.p);
10760+ buf_printf(b, "; _t%d %s ", ti, up ? "<=" : ">="); buf_puts(b, hi.p);
10761+ buf_printf(b, "; _t%d%s) {\n", ti, up ? "++" : "--");
10762+ if (p0) { char ts[32]; snprintf(ts, sizeof ts, "_t%d", ti); emit_iter_param_assign(c, block, p0_orig, p0, TY_INT, ts, b, indent + 1); }
1075910763 emit_loop_body(c, body, b, indent + 1);
1076010764 emit_indent(b, indent); buf_puts(b, "}\n");
1076110765 free(lo.p); free(hi.p);