Commit f3d1da49
f3d1da49a6baMerged
Ryan Seys <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified
Description
feat(codegen): inline single-stmt instance_eval(&b) trampoline
Detects the exact def m(&b); instance_eval(&b); end DSL trampoline
shape at compile time and inlines the block body at each call site
with self rebound to the receiver. Full Ruby instance_eval is
dynamic — self rebinding is runtime-known — so AOT compilation can't
generally support it. The trampoline shape is the common DSL form
(Rails-style configure blocks, RSpec describe blocks), and inlining
it covers the case without giving up static dispatch.
Behavior
class Builder
def initialize; @sum = 0; end
def add(n); @sum = @sum + n; end
def total; @sum; end
def configure(&block); instance_eval(&block); end
end
b = Builder.new
b.configure do
add(10) # resolves as Builder#add via rebound self
add(32)
end
puts b.total # 42
Implementation
- is_instance_eval_trampoline(ci, midx) — exact-shape detector: arity-0, single CallNode statement, instance_eval receiverless, block-arg LocalVariableReadNode whose name matches the method's sole proc-typed param. Reuses find_block_arg.
- compile_instance_eval_inlined_stmt(nid, recv) — splicer modeled on compile_yield_method_call_stmt. Saves and restores @instance_eval_self_var / @instance_eval_self_type so nested trampolines compose.
- compile_no_recv_call_expr gains an instance_eval-self branch before the @current_class_idx >= 0 check: receiverless calls in the spliced body resolve methods against the rebound class via Spinel's static type inference and emit a typed-self call.
- The yield-method dispatch gate generalizes from @nd_block[nid] >= 0 to has_literal_block(nid) == 1, so a &proc_var forward at the call site doesn't trigger inlining. The direct-class and parent-class branches share a small try_yield_or_trampoline_dispatch helper to avoid duplication.
Out of scope
- instance_exec(*args, &block) — variadic, harder to type.
- Multi-statement method bodies that wrap instance_eval(&b) in more code — the detector requires single-statement.
- Direct obj.instance_eval { } at the call site (separate PR by another contributor; different mechanism).
- Dynamic self rebinding at runtime.
Test plan
- make bootstrap (gen2.c == gen3.c)
- make test passes (182 tests)
- test/instance_eval_trampoline.rb covers basic trampoline (Builder#add via configure), multi-statement spliced block body (Counter#bump x3 via with), and nested trampoline composition (outer.configure { inner.with { ... } } verifying save/restore of @instance_eval_self_var).
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- f3d1da49a6ba
- Parent
- 04000f21a009
spinel_codegen.rbmodifiedView file
@@ -156,6 +156,12 @@
156156
@hoisted_strlen_recv = ""157157
@in_yield_method = 0158158
@in_gc_scope = 0159+
# Set during the arity-0 instance_eval trampoline inlining so160+
# receiverless calls in the spliced block body dispatch against161+
# the rebound self (the .instance_eval receiver) instead of the162+
# enclosing method's self.163+
@instance_eval_self_var = ""164+
@instance_eval_self_type = ""159165
160166
# Yield/block tracking (parallel with meth_names / cls_meth_names)161167
@meth_has_yield = []@@ -752,6 +758,97 @@
752758
""753759
end754760
761+
# Returns the body node id for class ci's midx'th method, or -1762+
# if midx is out of range or the body id is invalid. Centralises763+
# the @cls_meth_bodies[ci].split(";")[midx].to_i parse so detectors764+
# don't have to inline it.765+
def cls_method_body_id(ci, midx)766+
bodies = @cls_meth_bodies[ci].split(";")767+
if midx >= bodies.length768+
return -1769+
end770+
bid = bodies[midx].to_i771+
if bid < 0772+
return -1773+
end774+
bid775+
end776+
777+
# Returns the name of the class method's single proc-typed param778+
# (its `&block` slot), or "" if the signature isn't exactly one779+
# proc param. Used by detectors that match the780+
# `def m(&b); ...; end` shape (instance_eval trampoline today;781+
# extensible to instance_exec, tap, etc.).782+
def cls_method_sole_proc_param_name(ci, midx)783+
all_params = @cls_meth_params[ci].split("|")784+
all_ptypes = @cls_meth_ptypes[ci].split("|")785+
if midx >= all_params.length786+
return ""787+
end788+
if midx >= all_ptypes.length789+
return ""790+
end791+
pnames = all_params[midx].split(",")792+
ptypes = all_ptypes[midx].split(",")793+
if pnames.length != 1794+
return ""795+
end796+
if ptypes.length != 1797+
return ""798+
end799+
if ptypes[0] != "proc"800+
return ""801+
end802+
pnames[0]803+
end804+
805+
# Detects the exact arity-0 instance_eval trampoline shape:806+
# `def m(&b); instance_eval(&b); end`. Returns 1 when the807+
# (ci, midx) method body is a single CallNode of `instance_eval`808+
# forwarded the method's sole proc-typed param via &-arg, 0809+
# otherwise. Spinel inlines these at the call site (yield-style)810+
# with self rebound to the receiver — full Ruby instance_eval is811+
# dynamic, but this AOT compromise covers the common DSL-trampoline812+
# shape. Anything wider falls through to today's silent no-op.813+
def is_instance_eval_trampoline(ci, midx)814+
# AST shape gates first (no string splits — cheap reject path).815+
bid = cls_method_body_id(ci, midx)816+
if bid < 0817+
return 0818+
end819+
stmts = get_stmts(bid)820+
if stmts.length != 1821+
return 0822+
end823+
s = stmts[0]824+
if @nd_type[s] != "CallNode"825+
return 0826+
end827+
if @nd_name[s] != "instance_eval"828+
return 0829+
end830+
if @nd_receiver[s] >= 0831+
return 0832+
end833+
inner = find_block_arg(s)834+
if inner < 0835+
return 0836+
end837+
if @nd_type[inner] != "LocalVariableReadNode"838+
return 0839+
end840+
# Param signature gate (does the string splits) — only methods841+
# that pass the AST shape get here.842+
pname = cls_method_sole_proc_param_name(ci, midx)843+
if pname == ""844+
return 0845+
end846+
if @nd_name[inner] != pname847+
return 0848+
end849+
1850+
end851+
755852
# Flatten a constant reference into an internal name.756853
# C -> C757854
# ::C -> C@@ -14145,6 +14242,31 @@
1414514242
end1414614243
end1414714244
end14245+
# Inside an instance_eval inlined block: receiverless calls in14246+
# the spliced body dispatch against the rebound self (the14247+
# receiver that .instance_eval was called on), not the enclosing14248+
# method's self. Static type inference gives us the class name,14249+
# so we resolve the method at compile time and emit a typed-self14250+
# call.14251+
if @instance_eval_self_var != ""14252+
target_ci = find_class_idx(@instance_eval_self_type)14253+
if target_ci >= 014254+
cidx = cls_find_method(target_ci, mname)14255+
if cidx >= 014256+
owner = find_method_owner(target_ci, mname)14257+
cast_recv = "(sp_" + owner + " *)" + @instance_eval_self_var14258+
tail = build_call_tail(compile_call_args(nid), "")14259+
return "sp_" + owner + "_" + sanitize_name(mname) + "(" + cast_recv + tail + ")"14260+
end14261+
end14262+
# Fall through deliberately when the rebound class doesn't14263+
# define `mname`. Ruby's instance_eval rebinds `self` for14264+
# instance-method dispatch only — Kernel methods (puts, p,14265+
# raise, etc.) and top-level helpers must still resolve in the14266+
# enclosing scope, which the gates below handle. Removing this14267+
# fallthrough would silently break common DSL patterns like14268+
# `b.configure { puts "hi"; add(10) }`.14269+
end1414814270
if @current_class_idx >= 01414914271
cidx = cls_find_method(@current_class_idx, mname)1415014272
if cidx >= 0@@ -20811,8 +20933,11 @@
2081120933
end2081220934
end2081320935
20814-
# User-defined yield function called with block20815-
if @nd_block[nid] >= 020936+
# User-defined yield function or instance_eval trampoline, called20937+
# with a literal block. (A `&proc_var` forward at the call site20938+
# doesn't trigger inlining — those flow through compile_call_expr's20939+
# regular block-forwarding path.)20940+
if has_literal_block(nid) == 12081620941
if recv < 02081720942
mi = find_method_idx(mname)2081820943
if mi >= 0@@ -20822,30 +20947,24 @@
2082220947
end2082320948
end2082420949
end20825-
# Class method with yield20950+
# Class method with yield, or an arity-0 instance_eval trampoline.20951+
# The direct-class and parent-class lookups share the same dispatch20952+
# shape (find midx, check yield, check trampoline); collapsed into20953+
# try_yield_or_trampoline_dispatch.2082620954
if recv >= 02082720955
rtype = infer_type(recv)2082820956
if is_obj_type(rtype) == 12082920957
cn = rtype[4, rtype.length - 4]2083020958
cci = find_class_idx(cn)2083120959
if cci >= 020832-
midx = cls_find_method_direct(cci, mname)20833-
if midx >= 020834-
if cls_method_has_yield(cci, midx) == 120835-
compile_yield_method_call_stmt(nid, cci, midx, mname)20836-
return 120837-
end20960+
if try_yield_or_trampoline_dispatch(nid, recv, cci, mname) == 120961+
return 12083820962
end20839-
# Check parent2084020963
if @cls_parents[cci] != ""2084120964
pci = find_class_idx(@cls_parents[cci])2084220965
if pci >= 020843-
pidx = cls_find_method_direct(pci, mname)20844-
if pidx >= 020845-
if cls_method_has_yield(pci, pidx) == 120846-
compile_yield_method_call_stmt(nid, pci, pidx, mname)20847-
return 120848-
end20966+
if try_yield_or_trampoline_dispatch(nid, recv, pci, mname) == 120967+
return 12084920968
end2085020969
end2085120970
end@@ -24488,6 +24607,80 @@
2448824607
"0"2448924608
end2449024609
24610+
# Tries the yield-method or instance_eval-trampoline dispatch24611+
# against a single class index. Returns 1 if dispatch fired (caller24612+
# should return immediately), 0 otherwise (caller falls through to24613+
# the next gate, e.g. parent class). Shared by the direct-class and24614+
# parent-class branches in compile_no_recv_call_expr.24615+
def try_yield_or_trampoline_dispatch(nid, recv, cls_idx, mname)24616+
midx = cls_find_method_direct(cls_idx, mname)24617+
if midx < 024618+
return 024619+
end24620+
if cls_method_has_yield(cls_idx, midx) == 124621+
compile_yield_method_call_stmt(nid, cls_idx, midx, mname)24622+
return 124623+
end24624+
if is_instance_eval_trampoline(cls_idx, midx) == 124625+
compile_instance_eval_inlined_stmt(nid, recv)24626+
return 124627+
end24628+
024629+
end24630+
24631+
# Splice the statements of a block body in place with `self`24632+
# rebound to self_var (typed as cname). Saves and restores the24633+
# rebound-self ivars (@instance_eval_self_var / _type) so nested24634+
# splices compose. compile_no_recv_call_expr's instance_eval-self24635+
# branch reads these to dispatch receiverless calls inside the24636+
# splice against the rebound class. Reusable by future24637+
# rebind-and-splice features (e.g. instance_exec, tap-shape24638+
# trampolines).24639+
def splice_block_with_self_rebound(body, self_var, cname)24640+
prev_self_var = @instance_eval_self_var24641+
prev_self_type = @instance_eval_self_type24642+
@instance_eval_self_var = self_var24643+
@instance_eval_self_type = cname24644+
if body >= 024645+
stmts = get_stmts(body)24646+
k = 024647+
while k < stmts.length24648+
compile_stmt(stmts[k])24649+
k = k + 124650+
end24651+
end24652+
@instance_eval_self_var = prev_self_var24653+
@instance_eval_self_type = prev_self_type24654+
end24655+
24656+
# Inlines a `recv.m { body }` call when `m` is an arity-024657+
# instance_eval trampoline. The entire method body is the call24658+
# `instance_eval(&block)`, so we splice the block body in place24659+
# with self rebound to the receiver. Modeled on24660+
# compile_yield_method_call_stmt but simpler — the trampoline body24661+
# has no locals/params to remap.24662+
def compile_instance_eval_inlined_stmt(nid, recv)24663+
blk = @nd_block[nid]24664+
if blk < 024665+
return24666+
end24667+
rtype = infer_type(recv)24668+
cname = ""24669+
if is_obj_type(rtype) == 124670+
cname = rtype[4, rtype.length - 4]24671+
end24672+
if cname == ""24673+
return24674+
end24675+
rc = compile_expr_gc_rooted(recv)24676+
self_var = new_temp24677+
emit(" sp_" + cname + " *" + self_var + " = (sp_" + cname + " *)" + rc + ";")24678+
if @in_gc_scope == 124679+
emit(" SP_GC_ROOT(" + self_var + ");")24680+
end24681+
splice_block_with_self_rebound(@nd_body[blk], self_var, cname)24682+
end24683+
2449124684
def compile_yield_method_call_stmt(nid, cci, midx, mname)2449224685
# Call a yield-using class method with a block - inline the method body2449324686
blk = @nd_block[nid]test/instance_eval_trampoline.rbaddedView file
Loading diff…