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 = 0
158158 @in_gc_scope = 0
159+ # Set during the arity-0 instance_eval trampoline inlining so
160+ # receiverless calls in the spliced block body dispatch against
161+ # the rebound self (the .instance_eval receiver) instead of the
162+ # 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 end
754760
761+ # Returns the body node id for class ci's midx'th method, or -1
762+ # if midx is out of range or the body id is invalid. Centralises
763+ # the @cls_meth_bodies[ci].split(";")[midx].to_i parse so detectors
764+ # 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.length
768+ return -1
769+ end
770+ bid = bodies[midx].to_i
771+ if bid < 0
772+ return -1
773+ end
774+ bid
775+ end
776+
777+ # Returns the name of the class method's single proc-typed param
778+ # (its `&block` slot), or "" if the signature isn't exactly one
779+ # proc param. Used by detectors that match the
780+ # `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.length
786+ return ""
787+ end
788+ if midx >= all_ptypes.length
789+ return ""
790+ end
791+ pnames = all_params[midx].split(",")
792+ ptypes = all_ptypes[midx].split(",")
793+ if pnames.length != 1
794+ return ""
795+ end
796+ if ptypes.length != 1
797+ return ""
798+ end
799+ if ptypes[0] != "proc"
800+ return ""
801+ end
802+ pnames[0]
803+ end
804+
805+ # Detects the exact arity-0 instance_eval trampoline shape:
806+ # `def m(&b); instance_eval(&b); end`. Returns 1 when the
807+ # (ci, midx) method body is a single CallNode of `instance_eval`
808+ # forwarded the method's sole proc-typed param via &-arg, 0
809+ # otherwise. Spinel inlines these at the call site (yield-style)
810+ # with self rebound to the receiver — full Ruby instance_eval is
811+ # dynamic, but this AOT compromise covers the common DSL-trampoline
812+ # 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 < 0
817+ return 0
818+ end
819+ stmts = get_stmts(bid)
820+ if stmts.length != 1
821+ return 0
822+ end
823+ s = stmts[0]
824+ if @nd_type[s] != "CallNode"
825+ return 0
826+ end
827+ if @nd_name[s] != "instance_eval"
828+ return 0
829+ end
830+ if @nd_receiver[s] >= 0
831+ return 0
832+ end
833+ inner = find_block_arg(s)
834+ if inner < 0
835+ return 0
836+ end
837+ if @nd_type[inner] != "LocalVariableReadNode"
838+ return 0
839+ end
840+ # Param signature gate (does the string splits) — only methods
841+ # that pass the AST shape get here.
842+ pname = cls_method_sole_proc_param_name(ci, midx)
843+ if pname == ""
844+ return 0
845+ end
846+ if @nd_name[inner] != pname
847+ return 0
848+ end
849+ 1
850+ end
851+
755852 # Flatten a constant reference into an internal name.
756853 # C -> C
757854 # ::C -> C
@@ -14145,6 +14242,31 @@
1414514242 end
1414614243 end
1414714244 end
14245+ # Inside an instance_eval inlined block: receiverless calls in
14246+ # the spliced body dispatch against the rebound self (the
14247+ # receiver that .instance_eval was called on), not the enclosing
14248+ # method's self. Static type inference gives us the class name,
14249+ # so we resolve the method at compile time and emit a typed-self
14250+ # call.
14251+ if @instance_eval_self_var != ""
14252+ target_ci = find_class_idx(@instance_eval_self_type)
14253+ if target_ci >= 0
14254+ cidx = cls_find_method(target_ci, mname)
14255+ if cidx >= 0
14256+ owner = find_method_owner(target_ci, mname)
14257+ cast_recv = "(sp_" + owner + " *)" + @instance_eval_self_var
14258+ tail = build_call_tail(compile_call_args(nid), "")
14259+ return "sp_" + owner + "_" + sanitize_name(mname) + "(" + cast_recv + tail + ")"
14260+ end
14261+ end
14262+ # Fall through deliberately when the rebound class doesn't
14263+ # define `mname`. Ruby's instance_eval rebinds `self` for
14264+ # instance-method dispatch only — Kernel methods (puts, p,
14265+ # raise, etc.) and top-level helpers must still resolve in the
14266+ # enclosing scope, which the gates below handle. Removing this
14267+ # fallthrough would silently break common DSL patterns like
14268+ # `b.configure { puts "hi"; add(10) }`.
14269+ end
1414814270 if @current_class_idx >= 0
1414914271 cidx = cls_find_method(@current_class_idx, mname)
1415014272 if cidx >= 0
@@ -20811,8 +20933,11 @@
2081120933 end
2081220934 end
2081320935
20814- # User-defined yield function called with block
20815- if @nd_block[nid] >= 0
20936+ # User-defined yield function or instance_eval trampoline, called
20937+ # with a literal block. (A `&proc_var` forward at the call site
20938+ # doesn't trigger inlining — those flow through compile_call_expr's
20939+ # regular block-forwarding path.)
20940+ if has_literal_block(nid) == 1
2081620941 if recv < 0
2081720942 mi = find_method_idx(mname)
2081820943 if mi >= 0
@@ -20822,30 +20947,24 @@
2082220947 end
2082320948 end
2082420949 end
20825- # Class method with yield
20950+ # Class method with yield, or an arity-0 instance_eval trampoline.
20951+ # The direct-class and parent-class lookups share the same dispatch
20952+ # shape (find midx, check yield, check trampoline); collapsed into
20953+ # try_yield_or_trampoline_dispatch.
2082620954 if recv >= 0
2082720955 rtype = infer_type(recv)
2082820956 if is_obj_type(rtype) == 1
2082920957 cn = rtype[4, rtype.length - 4]
2083020958 cci = find_class_idx(cn)
2083120959 if cci >= 0
20832- midx = cls_find_method_direct(cci, mname)
20833- if midx >= 0
20834- if cls_method_has_yield(cci, midx) == 1
20835- compile_yield_method_call_stmt(nid, cci, midx, mname)
20836- return 1
20837- end
20960+ if try_yield_or_trampoline_dispatch(nid, recv, cci, mname) == 1
20961+ return 1
2083820962 end
20839- # Check parent
2084020963 if @cls_parents[cci] != ""
2084120964 pci = find_class_idx(@cls_parents[cci])
2084220965 if pci >= 0
20843- pidx = cls_find_method_direct(pci, mname)
20844- if pidx >= 0
20845- if cls_method_has_yield(pci, pidx) == 1
20846- compile_yield_method_call_stmt(nid, pci, pidx, mname)
20847- return 1
20848- end
20966+ if try_yield_or_trampoline_dispatch(nid, recv, pci, mname) == 1
20967+ return 1
2084920968 end
2085020969 end
2085120970 end
@@ -24488,6 +24607,80 @@
2448824607 "0"
2448924608 end
2449024609
24610+ # Tries the yield-method or instance_eval-trampoline dispatch
24611+ # against a single class index. Returns 1 if dispatch fired (caller
24612+ # should return immediately), 0 otherwise (caller falls through to
24613+ # the next gate, e.g. parent class). Shared by the direct-class and
24614+ # 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 < 0
24618+ return 0
24619+ end
24620+ if cls_method_has_yield(cls_idx, midx) == 1
24621+ compile_yield_method_call_stmt(nid, cls_idx, midx, mname)
24622+ return 1
24623+ end
24624+ if is_instance_eval_trampoline(cls_idx, midx) == 1
24625+ compile_instance_eval_inlined_stmt(nid, recv)
24626+ return 1
24627+ end
24628+ 0
24629+ end
24630+
24631+ # Splice the statements of a block body in place with `self`
24632+ # rebound to self_var (typed as cname). Saves and restores the
24633+ # rebound-self ivars (@instance_eval_self_var / _type) so nested
24634+ # splices compose. compile_no_recv_call_expr's instance_eval-self
24635+ # branch reads these to dispatch receiverless calls inside the
24636+ # splice against the rebound class. Reusable by future
24637+ # rebind-and-splice features (e.g. instance_exec, tap-shape
24638+ # trampolines).
24639+ def splice_block_with_self_rebound(body, self_var, cname)
24640+ prev_self_var = @instance_eval_self_var
24641+ prev_self_type = @instance_eval_self_type
24642+ @instance_eval_self_var = self_var
24643+ @instance_eval_self_type = cname
24644+ if body >= 0
24645+ stmts = get_stmts(body)
24646+ k = 0
24647+ while k < stmts.length
24648+ compile_stmt(stmts[k])
24649+ k = k + 1
24650+ end
24651+ end
24652+ @instance_eval_self_var = prev_self_var
24653+ @instance_eval_self_type = prev_self_type
24654+ end
24655+
24656+ # Inlines a `recv.m { body }` call when `m` is an arity-0
24657+ # instance_eval trampoline. The entire method body is the call
24658+ # `instance_eval(&block)`, so we splice the block body in place
24659+ # with self rebound to the receiver. Modeled on
24660+ # compile_yield_method_call_stmt but simpler — the trampoline body
24661+ # has no locals/params to remap.
24662+ def compile_instance_eval_inlined_stmt(nid, recv)
24663+ blk = @nd_block[nid]
24664+ if blk < 0
24665+ return
24666+ end
24667+ rtype = infer_type(recv)
24668+ cname = ""
24669+ if is_obj_type(rtype) == 1
24670+ cname = rtype[4, rtype.length - 4]
24671+ end
24672+ if cname == ""
24673+ return
24674+ end
24675+ rc = compile_expr_gc_rooted(recv)
24676+ self_var = new_temp
24677+ emit(" sp_" + cname + " *" + self_var + " = (sp_" + cname + " *)" + rc + ";")
24678+ if @in_gc_scope == 1
24679+ emit(" SP_GC_ROOT(" + self_var + ");")
24680+ end
24681+ splice_block_with_self_rebound(@nd_body[blk], self_var, cname)
24682+ end
24683+
2449124684 def compile_yield_method_call_stmt(nid, cci, midx, mname)
2449224685 # Call a yield-using class method with a block - inline the method body
2449324686 blk = @nd_block[nid]