Commit 672bdd12

672bdd12abb9Merged

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

Description

Run sum-block setup statements inside the fold loop

emit_sum_block_expr emitted the block's value expression with emit_expr, so when that expression was itself a compound emitter that spills setup to g_pre (e.g. the nested OFFSETS.count { } loop in bm_life's neighbor counting), the setup landed at the enclosing statement boundary — the inner loop ran once, outside the sum loop, and every iteration re-added the same stale count.

Redirect g_pre into a local buffer while emitting the value expression and splice it into the loop body ahead of the accumulation, so nested setup executes per iteration.

bm_life now passes. make test stays green (845 pass).

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

Details

Commit
672bdd12abb9
Parent
604165c6025d

src/codegen_fold.cmodifiedView file

@@ -639,9 +639,21 @@
639639 }
640640 buf_printf(b, "; for (mrb_int _t%d = 0; _t%d < _t%d; _t%d++) { ", ti, ti, tn, ti);
641641 if (p0) buf_printf(b, "lv_%s = sp_%sArray_get(_t%d, _t%d); ", p0, k, ta, ti);
642- buf_printf(b, "_t%d = ", tacc);
643- if (acct == TY_INT) { buf_printf(b, "sp_int_add(_t%d, ", tacc); emit_expr(c, bb[bn - 1], b); buf_puts(b, ")"); }
644- else { buf_printf(b, "_t%d + ", tacc); emit_expr(c, bb[bn - 1], b); }
642+ /* The block's value expression may spill setup statements to g_pre (e.g.
643+ a nested count loop). Those must run per iteration: redirect g_pre into
644+ a local buffer while emitting the value, then splice it into the loop
645+ body ahead of the accumulation. */
646+ {
647+ Buf inner; memset(&inner, 0, sizeof inner);
648+ Buf valb; memset(&valb, 0, sizeof valb);
649+ Buf *saved_pre = g_pre; g_pre = &inner;
650+ if (acct == TY_INT) { buf_printf(&valb, "sp_int_add(_t%d, ", tacc); emit_expr(c, bb[bn - 1], &valb); buf_puts(&valb, ")"); }
651+ else { buf_printf(&valb, "_t%d + ", tacc); emit_expr(c, bb[bn - 1], &valb); }
652+ g_pre = saved_pre;
653+ if (inner.p) buf_puts(b, inner.p);
654+ buf_printf(b, "_t%d = %s", tacc, valb.p ? valb.p : "0");
655+ free(inner.p); free(valb.p);
656+ }
645657 buf_printf(b, "; } _t%d; })", tacc);
646658 return 1;
647659 }