Commit 51d369bb

51d369bb0e1cMerged

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

Description

fix(codegen,bench): Array.new with block as method-body return; rewrite life.rb

Two coupled changes surfaced when removing the silent-no-op fallthrough.

(1) compile_body_return's CallNode-with-block branch had explicit cases for map/select/sum/count/proc but not for new. A method body ending in Array.new(n) { 0 } (or Hash.new { ... }) fell through to the catch-all that calls compile_stmt + emits return <default>. compile_stmt evaluated the construction, populated a temp, and discarded it — the function returned NULL. Subsequent calls receiving the NULL segfaulted.

Symptom in benchmark/life.rb: `def next_gen(cells); Array.new(SIZE)
{ |i| ... }; end` returned NULL, the simulation loop dereferenced
it, exit 139.

Fix: route the `new` case through compile_expr (which already
builds the temp into a named local) and return its name.

(2) life.rb was using three idioms that codegen doesn't implement: (-1..1).sum { ... }, (-1..1).count { ... } (Range with block), and SIZE.times.map { ... } (Integer#times.map chain via the Enumerator). All three triggered the silent-zero fallthrough, so the simulation was running with neighbors() always returning 0; the bench passed only because CRuby happened to also produce 0 after 200 generations of the glider+blinker pattern.

Rewrite to Array equivalents: `OFFSETS = [-1, 0, 1]; OFFSETS.sum
{ ... }`, `OFFSETS.count { ... }`, `Array.new(SIZE) { ... }`.
Without (1) the `next_gen` rewrite would still segfault, so both
pieces ship together.

After both: bench output matches CRuby exactly, the simulation actually runs (no silent dispatches), and zero unresolved-call warnings are emitted at codegen.

Bootstrap (gen2 == gen3) clean; 198 tests + 56 benches pass.

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

Details

Commit
51d369bb0e1c
Parent
b113d2985e34

benchmark/life.rbmodifiedView file

@@ -16,14 +16,20 @@
1616 cells[(y % H) * W + (x % W)]
1717 end
1818
19+# Range-with-block idioms (`(-1..1).count { ... }`, `(-1..1).sum { ... }`,
20+# `SIZE.times.map { ... }`) aren't implemented in spinel's codegen yet —
21+# they emit a deduped warning and a literal 0 at codegen time. Use the
22+# Array equivalents so the generation actually runs.
23+OFFSETS = [-1, 0, 1]
24+
1925 def neighbors(cells, x, y)
20- (-1..1).sum { |iy|
21- (-1..1).count { |ix| cell_get(cells, x + ix, y + iy) == 1 }
26+ OFFSETS.sum { |iy|
27+ OFFSETS.count { |ix| cell_get(cells, x + ix, y + iy) == 1 }
2228 }
2329 end
2430
2531 def next_gen(cells)
26- SIZE.times.map { |i|
32+ Array.new(SIZE) { |i|
2733 y = i / W
2834 x = i % W
2935 n = neighbors(cells, x, y)
@@ -38,7 +44,7 @@
3844 end
3945
4046 # Initialize with a deterministic pattern (glider + blinker)
41-cells = SIZE.times.map { 0 }
47+cells = Array.new(SIZE) { 0 }
4248
4349 # Glider at (1,1)
4450 cells[1 * W + 2] = 1