Commit 0e6c3e67

0e6c3e6700dbMerged

Ryan Seys <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

codegen: instance_exec trampoline with fixed-arity forwarding

Adds instance_exec support via the codegen-time trampoline pattern that already powers instance_eval. The detected shape is

def m(p1, ..., pN, &b); instance_exec(p1, ..., pN, &b); end

with N >= 0 and strict 1:1 forwarding of positional params into positional instance_exec args. The user-visible call shape

recv.m(arg1, ..., argN) { |q1, ..., qN| body }

inlines body at the call site with self rebound to recv (via the existing splice_block_with_self_rebound and the ivar-routing gate on @instance_eval_self_var) and each qK bound to a fresh suffixed C local holding the call-site argK value (via @inline_rename_map_from / _to, the same machinery compile_yield_method_call_stmt uses).

New helpers in spinel_codegen.rb:

  • cls_method_trailing_proc_param_name: sibling of the existing sole-proc-param helper, but allows leading required params.
  • is_instance_exec_trampoline: AST shape detector mirroring is_instance_eval_trampoline (single CallNode body named instance_exec, no explicit receiver, &-arg matching the method's trailing proc param, positional args are LocalVariableRead nodes matching method params 1:1).
  • compile_instance_exec_inlined_stmt: hybrid of compile_instance_eval_inlined_stmt (self rebind) and compile_yield_method_call_stmt (block-param rename). It save/restores @self_override, @inline_rename_map_*, and the rebound-self ivars around the splice so nested rebinds compose. A mismatch between block-param count and forwarded-arg count is a hard error -- Spinel uses strict arity (CRuby's auto-splat / auto-pack is not modeled).

Dispatch is wired into try_yield_or_trampoline_dispatch alongside the instance_eval-trampoline clause; the trampoline-body dead-code suppression is extended to recognise both detectors so the forwarded instance_exec(args, &b) call does not warn-and-emit-0.

test/instance_exec_trampoline.rb covers fixed-arity forwarding (1 and 2 args), @ivar read/write inside the spliced block, multiple call sites against different instances, inheritance through a parent method, and outer-local capture via the splice.

Boundaries (deferred to later PRs in the stack):

  • Splat / mixed-arg trampolines reject for now.
  • Direct recv.instance_exec(args) { ... } outside a trampoline is the next PR's lift.
  • Value-typed receivers and expression-position return values land in follow-ups.

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

Details

Commit
0e6c3e6700db
Parent
1f054fd8169c

spinel_codegen.rbmodifiedView file

@@ -863,6 +863,46 @@
863863 pnames[0]
864864 end
865865
866+ # Returns the &block param's name on (ci, midx), or "" if the
867+ # method's last param isn't proc-typed. Sibling of
868+ # cls_method_sole_proc_param_name, but allows the method to have
869+ # other (required) params before the &block. Used by the
870+ # instance_exec trampoline detector, where the trampoline forwards
871+ # N required params and the block:
872+ # def m(a, b, ..., &blk); instance_exec(a, b, ..., &blk); end
873+ # cls_method_sole_proc_param_name requires the method to have
874+ # exactly one param; this lifts that restriction by checking only
875+ # the last position.
876+ def cls_method_trailing_proc_param_name(ci, midx)
877+ pnames = cls_meth_pnames_get(ci, midx)
878+ ptypes = cls_meth_ptypes_get(ci, midx)
879+ if pnames.length == 0 || pnames.length != ptypes.length
880+ return ""
881+ end
882+ last = pnames.length - 1
883+ if ptypes[last] != "proc"
884+ return ""
885+ end
886+ # Earlier params must be ordinary (no rest, no keyword). The
887+ # baseline supports fixed-arity forwarding only; splat / mixed-args
888+ # extensions land in follow-ups.
889+ k = 0
890+ while k < last
891+ pt = ptypes[k]
892+ # The required-arg ptypes include type names (int, str_array,
893+ # obj_<C>, etc.), never "rest" / "kwrest" / "block" markers. If
894+ # a non-required-arg slot appears here, abort the detection so
895+ # we don't conflate splat trampolines with the fixed-arity
896+ # shape. A follow-up relaxes this to accept a "rest"-typed
897+ # final-required-param when the splat trampoline path lands.
898+ if pt == "" || pt == "proc"
899+ return ""
900+ end
901+ k = k + 1
902+ end
903+ pnames[last]
904+ end
905+
866906 # Detects the exact arity-0 instance_eval trampoline shape:
867907 # `def m(&b); instance_eval(&b); end`. Returns 1 when the
868908 # (ci, midx) method body is a single CallNode of `instance_eval`
@@ -910,6 +950,104 @@
910950 1
911951 end
912952
953+ # Detects the fixed-arity instance_exec trampoline shape:
954+ # def m(a1, ..., aN, &b); instance_exec(a1, ..., aN, &b); end
955+ # for N >= 0 with strict 1:1 forwarding -- positional method
956+ # params become positional instance_exec args, in order, and
957+ # the &b proc param is forwarded as the &-block. Returns 1 on
958+ # match, 0 otherwise.
959+ #
960+ # Unlike instance_eval (arity-0 only, no block params), this
961+ # detector accepts methods that take required positional params
962+ # alongside the &block, because instance_exec's args become the
963+ # block's params at the call site. The user-visible call shape is
964+ # `recv.m(arg1, ..., argN) { |p1, ..., pN| body }`; codegen
965+ # inlines body with self rebound to recv and block params bound
966+ # to the call-site args.
967+ #
968+ # Boundaries (rejected by returning 0 -> falls through to
969+ # ordinary dispatch which will error at codegen with the usual
970+ # warn-and-emit-0):
971+ # - No mixed-args (literals, ivars in trampoline body)
972+ # - No splat (def m(*args, &b))
973+ # - No keyword args
974+ # Follow-ups relax these once the baseline path is solid.
975+ def is_instance_exec_trampoline(ci, midx)
976+ bid = cls_method_body_id(ci, midx)
977+ if bid < 0
978+ return 0
979+ end
980+ stmts = get_stmts(bid)
981+ if stmts.length != 1
982+ return 0
983+ end
984+ s = stmts[0]
985+ if @nd_type[s] != "CallNode"
986+ return 0
987+ end
988+ if @nd_name[s] != "instance_exec"
989+ return 0
990+ end
991+ if @nd_receiver[s] >= 0
992+ return 0
993+ end
994+ # The block-arg must be a bare local-var ref matching the method's
995+ # trailing &block param. Same gate as is_instance_eval_trampoline.
996+ inner = find_block_arg(s)
997+ if inner < 0
998+ return 0
999+ end
1000+ if @nd_type[inner] != "LocalVariableReadNode"
1001+ return 0
1002+ end
1003+ bp_name = cls_method_trailing_proc_param_name(ci, midx)
1004+ if bp_name == ""
1005+ return 0
1006+ end
1007+ if @nd_name[inner] != bp_name
1008+ return 0
1009+ end
1010+ # Walk the trampoline body's positional args. The baseline requires
1011+ # each arg to be a LocalVariableReadNode matching the method's
1012+ # required param at the same index, in order. Mixed-args (literals,
1013+ # ivars, splat) reject for now; the strict-enumerable extension
1014+ # lands in a follow-up.
1015+ pnames = cls_meth_pnames_get(ci, midx)
1016+ req_n = pnames.length - 1 # last is the &block, already checked
1017+ args_id = @nd_arguments[s]
1018+ arg_ids = []
1019+ if args_id >= 0
1020+ arg_ids = get_args(args_id)
1021+ end
1022+ # The block-arg shows up in get_args too (as BlockArgumentNode).
1023+ # Filter to positional args only; CallNode args = positional +
1024+ # block-arg, in that order.
1025+ positional = []
1026+ k = 0
1027+ while k < arg_ids.length
1028+ aid = arg_ids[k]
1029+ if @nd_type[aid] != "BlockArgumentNode"
1030+ positional.push(aid)
1031+ end
1032+ k = k + 1
1033+ end
1034+ if positional.length != req_n
1035+ return 0
1036+ end
1037+ k = 0
1038+ while k < req_n
1039+ aid = positional[k]
1040+ if @nd_type[aid] != "LocalVariableReadNode"
1041+ return 0
1042+ end
1043+ if @nd_name[aid] != pnames[k]
1044+ return 0
1045+ end
1046+ k = k + 1
1047+ end
1048+ 1
1049+ end
1050+
9131051 # Flatten a constant reference into an internal name.
9141052 # C -> C
9151053 # ::C -> C
@@ -12373,6 +12511,13 @@
1237312511 if is_instance_eval_trampoline(ci, midx) == 1
1237412512 is_tramp = 1
1237512513 end
12514+ # instance_exec trampoline: same dead-body rationale -- every
12515+ # call site is splice-rewritten by try_yield_or_trampoline_dispatch,
12516+ # so the body's `instance_exec(a, ..., &b)` call would otherwise
12517+ # warn-and-emit-0 once per trampoline definition.
12518+ if is_instance_exec_trampoline(ci, midx) == 1
12519+ is_tramp = 1
12520+ end
1237612521 end
1237712522 # stub uncalled methods so an inferred-int param
1237812523 # doesn't fail C-compile against a narrower ivar slot.
@@ -49809,6 +49954,10 @@
4980949954 compile_instance_eval_inlined_stmt(nid, recv)
4981049955 return 1
4981149956 end
49957+ if is_instance_exec_trampoline(cls_idx, midx) == 1
49958+ compile_instance_exec_inlined_stmt(nid, recv, cls_idx, midx)
49959+ return 1
49960+ end
4981249961 0
4981349962 end
4981449963
@@ -49878,6 +50027,136 @@
4987850027 @self_override = saved_self_override
4987950028 end
4988050029
50030+ # Inlines a `recv.m(args) { |params| body }` call when `m` is a
50031+ # Fixed-arity instance_exec trampoline:
50032+ # def m(a1, ..., aN, &b); instance_exec(a1, ..., aN, &b); end
50033+ #
50034+ # Hybrid of compile_instance_eval_inlined_stmt (self rebind via
50035+ # splice_block_with_self_rebound) and compile_yield_method_call_stmt
50036+ # (block-param rename machinery via @inline_rename_map_from / _to).
50037+ # The block params become fresh suffixed C locals containing the
50038+ # call-site args; the block body is then spliced at the call site
50039+ # with @self_override / @instance_eval_self_var / _type set so
50040+ # bare method calls and @ivar reads dispatch through the receiver.
50041+ #
50042+ # TODO: value-typed receivers crash on the pointer cast emitted for
50043+ # self_var, same shape as the corresponding TODO in
50044+ # compile_instance_eval_inlined_stmt. Expression-position support
50045+ # (return value of the call usable in `total = recv.compute(...) { ... }`)
50046+ # is a follow-up; this path ships statement-form only.
50047+ def compile_instance_exec_inlined_stmt(nid, recv, cci, midx)
50048+ blk = @nd_block[nid]
50049+ if blk < 0
50050+ return
50051+ end
50052+ rtype = infer_type(recv)
50053+ cname = ""
50054+ if is_obj_type(rtype) == 1
50055+ cname = rtype[4, rtype.length - 4]
50056+ end
50057+ if cname == ""
50058+ return
50059+ end
50060+
50061+ # Block-param names from the user's `{ |p1, p2, ...| body }` at
50062+ # the call site. Same shape as compile_yield_method_call_stmt's
50063+ # block-param extraction; the AST traversal is identical.
50064+ bp_names = "".split(",")
50065+ bp = @nd_parameters[blk]
50066+ if bp >= 0
50067+ inner = @nd_parameters[bp]
50068+ if inner >= 0
50069+ reqs = parse_id_list(@nd_requireds[inner])
50070+ k = 0
50071+ while k < reqs.length
50072+ bp_names.push(@nd_name[reqs[k]])
50073+ k = k + 1
50074+ end
50075+ end
50076+ end
50077+
50078+ # Trampoline-method param types: forward through @cls_meth_ptypes
50079+ # so each call-site arg gets a typed local. The trampoline's
50080+ # ptypes[k] for k < N (the required params) are the types the
50081+ # block body should see for its block params.
50082+ ptypes_full = cls_meth_ptypes_get(cci, midx)
50083+ req_n = ptypes_full.length - 1 # last is &block
50084+
50085+ # Arity check: the user's block at the call site must declare the
50086+ # same number of required params as the trampoline forwards. A
50087+ # mismatch is a hard error rather than a silent miscompile --
50088+ # Spinel uses strict arity here (CRuby's auto-splat / auto-pack is
50089+ # not modeled), so the counts must match exactly.
50090+ if bp_names.length != req_n
50091+ $stderr.puts "Spinel: instance_exec trampoline: " + bp_names.length.to_s + " block param(s) do not match " + req_n.to_s + " trampoline arg(s); Spinel uses strict arity (CRuby's auto-splat / auto-pack is not modeled). Match the counts exactly."
50092+ exit(1)
50093+ end
50094+
50095+ # Evaluate call-site args BEFORE rebinding self -- the args are
50096+ # in the outer scope, not the splice context. Mirrors the order
50097+ # in compile_yield_method_call_stmt.
50098+ args_id = @nd_arguments[nid]
50099+ arg_ids = []
50100+ if args_id >= 0
50101+ arg_ids = get_args(args_id)
50102+ end
50103+
50104+ rc = compile_expr_gc_rooted(recv)
50105+ self_var = new_temp
50106+ emit(" sp_" + cname + " *" + self_var + " = (sp_" + cname + " *)" + rc + ";")
50107+ if @in_gc_scope == 1
50108+ emit(" SP_GC_ROOT(" + self_var + ");")
50109+ end
50110+
50111+ # Per-call-site suffix for block-param locals so nested splices
50112+ # / same-trampoline-different-call-sites don't shadow. Reuses
50113+ # @block_counter (also used by compile_yield_method_call_stmt's
50114+ # `_y<N>` suffix); the prefix is `_ix<N>` to distinguish.
50115+ @block_counter = @block_counter + 1
50116+ suffix = "_ix" + @block_counter.to_s
50117+
50118+ map_from = "".split(",")
50119+ map_to = "".split(",")
50120+
50121+ k = 0
50122+ while k < req_n
50123+ pt = "int"
50124+ if k < ptypes_full.length
50125+ pt = ptypes_full[k]
50126+ end
50127+ tname = bp_names[k] + suffix
50128+ val = "0"
50129+ if k < arg_ids.length
50130+ val = compile_expr(arg_ids[k])
50131+ end
50132+ emit(" " + c_type(pt) + " lv_" + tname + " = " + val + ";")
50133+ if type_is_pointer(pt) == 1 && @in_gc_scope == 1
50134+ emit(" SP_GC_ROOT(lv_" + tname + ");")
50135+ end
50136+ map_from.push(bp_names[k])
50137+ map_to.push(tname)
50138+ declare_var(tname, pt)
50139+ k = k + 1
50140+ end
50141+
50142+ # Route bare @ivar reads/writes inside the spliced block to the
50143+ # rebound receiver (same retrofit as
50144+ # compile_instance_eval_inlined_stmt). Save/restore for nested
50145+ # rebinds.
50146+ saved_self_override = @self_override
50147+ @self_override = self_var
50148+ saved_in_rmf = @inline_rename_map_from
50149+ saved_in_rmt = @inline_rename_map_to
50150+ @inline_rename_map_from = map_from
50151+ @inline_rename_map_to = map_to
50152+
50153+ splice_block_with_self_rebound(@nd_body[blk], self_var, cname)
50154+
50155+ @inline_rename_map_from = saved_in_rmf
50156+ @inline_rename_map_to = saved_in_rmt
50157+ @self_override = saved_self_override
50158+ end
50159+
4988150160 def compile_yield_method_call_stmt(nid, cci, midx, mname)
4988250161 # Call a yield-using class method with a block - inline the method body
4988350162 blk = @nd_block[nid]