Commit 10c6e42f

10c6e42f9c0dMerged

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

Description

fix(codegen): route .each_cons[.with_index].map fusion before emitting rc

compile_call_expr emits the receiver via compile_expr_gc_rooted(recv) before consulting compile_enumerable_expr -> compile_map_expr. When recv is the .with_index / .each_cons (no block) shape, that emit produces a pair of placeholder temps (sp_PtrArray * _t = 0;) for the enumerator-returning calls -- harmless on their own, but the inner receiver of .each_cons (e.g., m.times.map { gets.to_i }) gets emitted into rc as a side effect first, then re-emitted by compile_map_expr's fusion path at line ~32220. Two side-effecting inner chains land in the output. With gets as the inner side effect that consumed twice the input lines and produced wrong output (or a segfault past EOF), as cielavenir reported in #621.

#540 covered the one-level case (gets.split.map(&:to_i)) by threading the already-compiled rc into compile_enumerable_expr; the fusion path here doesn't use rc (it needs the inner receiver of each_cons, which is different from the with_index/each_cons placeholder chain), so the threading helps nothing.

Detect the fusion shape (mname == "map" with block + recv is with_index(n) <- each_cons(m) or each_cons(m) directly, both no-block) before line 13635 and route directly to compile_map_expr's fusion. rc never gets emitted.

Fixes #621

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

Details

Commit
10c6e42f9c0d
Parent
b14d5538273d

spinel_codegen.rbmodifiedView file

@@ -13632,6 +13632,22 @@
1363213632 if recv_type != "poly" && expr_emits_poly_rb_val(recv) == 1
1363313633 recv_type = "poly"
1363413634 end
13635+ # Detect the each_cons[.with_index].map fusion shape before emitting
13636+ # `rc`. compile_map_expr's fusion path re-compiles the each_cons
13637+ # inner receiver itself; if we emit `rc` first, the
13638+ # with_index/each_cons placeholders land as `sp_PtrArray * _t = 0;`
13639+ # and (worse) the inner chain's side effects (`gets`) execute
13640+ # twice. Route directly to compile_map_expr instead, which
13641+ # produces the correct single fused loop. Issue #621.
13642+ if mname == "map" && @nd_block[nid] >= 0 && recv >= 0
13643+ ec_check_recv = recv
13644+ if @nd_type[ec_check_recv] == "CallNode" && @nd_name[ec_check_recv] == "with_index" && @nd_block[ec_check_recv] < 0
13645+ ec_check_recv = @nd_receiver[ec_check_recv]
13646+ end
13647+ if ec_check_recv >= 0 && @nd_type[ec_check_recv] == "CallNode" && @nd_name[ec_check_recv] == "each_cons" && @nd_block[ec_check_recv] < 0
13648+ return compile_map_expr(nid, "")
13649+ end
13650+ end
1363513651 rc = compile_expr_gc_rooted(recv)
1363613652 # Type-narrow unbox: when recv is a LocalVariableReadNode whose
1363713653 # narrowed type (post-`raise unless x.is_a?(C)` guard) is a