Commit 3897a383

3897a383f61aMerged

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

Description

Add yield/block support — user-defined iterators, Array#each/map/select

Two approaches depending on context:

  1. User-defined yield methods → callback function pointer:

    • Methods with yield get extra (sp_block_fn, void*) parameters
    • yield expr → _block(_block_env, expr)
    • Call sites generate env struct with pointers to captured variables
    • Block body becomes a static callback function
    • Captured variables modified by reference (*e->var)
  2. Array#each/map/select → inline loop codegen:

    • arr.each { |x| body } → for loop over IntArray
    • arr.map { |x| expr } → new IntArray with pushed results
    • arr.select { |x| cond } → filtered IntArray

Also adds:

  • has_yield detection in function analysis
  • Capture analysis for block bodies (reuses lambda capture scanner)
  • Nested block support (inner block params excluded from captures)
  • Block output buffering for correct C declaration ordering

Test: examples/bm_yield.rb exercises all patterns: my_times(n) with yield, Array#each/map/select, nested yields Output: 45, 55, 10, 5, 10 — matches Ruby exactly

All regressions pass.

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

Details

Commit
3897a383f61a
Parent
6f5e83383880

examples/bm_yield.rbaddedView file

1+# Test program for yield/block support
2+
3+# User-defined iterator with yield
4+def my_times(n)
5+ i = 0
6+ while i < n
7+ yield i
8+ i += 1
9+ end
10+end
11+
12+# Array#each
13+def sum_array(arr)
14+ total = 0
15+ arr.each do |x|
16+ total += x
17+ end
18+ total
19+end
20+
21+# Array#map
22+def double_array(arr)
23+ arr.map do |x|
24+ x * 2
25+ end
26+end
27+
28+# Array#select
29+def evens(arr)
30+ arr.select do |x|
31+ x % 2 == 0
32+ end
33+end
34+
35+# Nested yield
36+def repeat(n)
37+ i = 0
38+ while i < n
39+ yield i
40+ i += 1
41+ end
42+end
43+
44+# Main
45+total = 0
46+my_times(10) do |i|
47+ total += i
48+end
49+puts total # 45
50+
51+arr = (1..10).to_a
52+puts sum_array(arr) # 55
53+
54+doubled = double_array(arr)
55+puts doubled.length # 10
56+
57+even_nums = evens(arr)
58+puts even_nums.length # 5
59+
60+# Nested: repeat yields, inner block accumulates
61+result = 0
62+repeat(5) do |i|
63+ my_times(i) do |j|
64+ result += j
65+ end
66+end
67+puts result # 0+0+1+0+1+2+0+1+2+3 = 10