Commit 4880c596

4880c5964dedMerged

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

Description

Add &block parameter, proc {}, Proc.new {}, Proc#call

sp_Proc struct wraps function pointer + captured environment:

  • &block parameter: block wrapped in stack-allocated sp_Proc at call site
  • proc { |n| body }: compiles block as static C function, returns sp_Proc*
  • Proc.new { |n| body }: same as proc {}
  • proc.call(x): sp_Proc_call(proc, x) → proc->fn(proc->env, x)
  • Passing procs as method arguments works (sp_Proc* parameter)

Separate from lambda (sp_Val) — sp_Proc is lightweight, no arena needed. GC-allocated when needs_gc is active.

Test: examples/bm_proc.rb — &block, proc {}, Proc.new {}, call, forwarding, with_logging pattern. Output matches Ruby.

All regressions pass (fib, yield, block2).

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

Details

Commit
4880c5964ded
Parent
c3fa26e5c21d

examples/bm_proc.rbaddedView file

1+# Test &block, Proc.new, proc, Proc#call
2+
3+# &block parameter — receive block as Proc
4+def apply(x, &block)
5+ block.call(x)
6+end
7+
8+puts apply(5) { |n| n * 2 } # 10
9+
10+# Store block in variable
11+def make_doubler
12+ proc { |n| n * 2 }
13+end
14+
15+doubler = make_doubler
16+puts doubler.call(7) # 14
17+
18+# Proc.new
19+adder = Proc.new { |n| n + 10 }
20+puts adder.call(5) # 15
21+
22+# Pass proc to method
23+def transform(x, fn)
24+ fn.call(x)
25+end
26+
27+puts transform(3, doubler) # 6
28+
29+# Method with &block forwarding
30+def with_logging(x, &blk)
31+ puts "before"
32+ result = blk.call(x)
33+ puts "after"
34+ result
35+end
36+
37+with_logging(42) do |n|
38+ puts n
39+end
40+# before, 42, after
41+
42+puts "done"