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:
-
User-defined yield methods → callback function pointer:
- Methods with
yieldget 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)
- Methods with
-
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 support2+
3+
# User-defined iterator with yield4+
def my_times(n)5+
i = 06+
while i < n7+
yield i8+
i += 19+
end10+
end11+
12+
# Array#each13+
def sum_array(arr)14+
total = 015+
arr.each do |x|16+
total += x17+
end18+
total19+
end20+
21+
# Array#map22+
def double_array(arr)23+
arr.map do |x|24+
x * 225+
end26+
end27+
28+
# Array#select29+
def evens(arr)30+
arr.select do |x|31+
x % 2 == 032+
end33+
end34+
35+
# Nested yield36+
def repeat(n)37+
i = 038+
while i < n39+
yield i40+
i += 141+
end42+
end43+
44+
# Main45+
total = 046+
my_times(10) do |i|47+
total += i48+
end49+
puts total # 4550+
51+
arr = (1..10).to_a52+
puts sum_array(arr) # 5553+
54+
doubled = double_array(arr)55+
puts doubled.length # 1056+
57+
even_nums = evens(arr)58+
puts even_nums.length # 559+
60+
# Nested: repeat yields, inner block accumulates61+
result = 062+
repeat(5) do |i|63+
my_times(i) do |j|64+
result += j65+
end66+
end67+
puts result # 0+0+1+0+1+2+0+1+2+3 = 10src/codegen.cmodifiedView file
Loading diff…
src/codegen.hmodifiedView file
Loading diff…