Commit 0aea90f3
0aea90f3dcccMerged
Ryan Seys <[email protected]> · 5 months ago · 18 files · +16 added · ~2 modified
Description
analyze,codegen: inline-splice lowering for direct instance_exec/eval
Lowers a literal-block recv.instance_exec(args) { ... } / recv.instance_eval { ... }
by splicing the block body at the call site with self rebound to the
receiver, instead of calling a lifted static function. Splicing lets the
block read and write the caller's locals (closure capture) and return the
block's last expression as the call value -- neither of which the lifted
function could do.
- Override-aware gate:
iexec_rewrite_call/ieval_rewrite_callskip the lift when the receiver's class defines its owninstance_exec/instance_eval(cls_find_method), so ordinary dispatch wins, matching CRuby. - Reject helpers (
iexec_reject,iexec_reject_kind,body_iexec_unsupported_kind,iexec_args_have_block_arg) turn shapes the static lift cannot model into clear compile-timeSpinel:diagnostics instead of a silent miscompile:def/define_methodin the block,yield/block_given?, a no-blockrecv.instance_exec(args)(LocalJumpErrorin CRuby), and an unresolved receiver class. - Inline-splice lowering (
compile_iexec_inline): heap receivers splice withselfrebound; value-type receivers bindselfby value and emit.rather than->for ivar access.emit_iexec_funcsskips generating a static function for an inlined lift (it would be unused). - Expression position:
x = recv.instance_exec { ... }declaresxwith the block's last-expression type (iexec_call_value_type) and yields that value, not the receiver. - Block params declared under both the per-call-site suffixed name and the
original name, bracketed by
push_scope/pop_scopeso they shadow outer locals only within the splice.
Tests: instance_exec_override, instance_exec_return (expression-position
value), instance_exec_capture (outer-local read / write-back /
accumulation), instance_exec_valuetype (value-type receiver), a combined
instance_exec_parity anchor cross-checked against ruby 4.0.5, and
analyze_fail/ cases for def, define_method, and a no-block call.
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 0aea90f3dccc
- Parent
- 4f3009ebeb75
spinel_analyze.rbmodifiedView file
return "obj_" + @cls_names[@ieval_class_idxs[n]] end end # iexec direct-path lift: the synthetic `__sp_iexec_<N>` function is # void-returning in the baseline, so its call resolves to "void". # The expression-position follow-up surfaces the real last-expression # type here via infer_iexec_body_return_types. # iexec direct-path lift: a heap receiver is inlined at the call site # and the call's value is the block's last expression, so type the call # by that expression (simple ctypes only -- array / hash / poly bodies # stay "void" and take the receiver-yielding comma-expr fallback, like # the ieval arm above). Computed on the fly to avoid a per-lift ivar. if is_iexec_call_name(mname) == 1 suffix = mname[11, mname.length - 11] rt = iexec_call_value_type(suffix.to_i) if ieval_return_type_is_simple(rt) == 1 return rt end return "void" end if ci < 0 return end # Override-aware intrinsic: if the receiver's class (or its parent # chain) defines its own `instance_eval`, the user has shadowed the # intrinsic. Skip the lift so ordinary dispatch resolves to the # user's method, matching CRuby. A gate on the method-name string # alone would silently bypass the override. if cls_find_method(ci, "instance_eval") >= 0 return end body_id = @nd_body[blk] # v1: bail if the block uses yield/block_given?. Lifting it as a # plain function would lose the enclosing method's block plumbing. if body_id >= 0 && body_has_yield(body_id) == 1 return end # Reject non-local control flow and runtime method definition inside # the block -- return / break / next / def / define_method have no # statically-translatable semantics once the body is lifted. if body_id >= 0 kind = body_iexec_unsupported_kind(body_id) if kind != "" iexec_reject_kind("instance_eval", kind) end end n = @ieval_counter @ieval_counter = @ieval_counter + 1 @ieval_class_idxs.push(ci) @nd_block[nid] = -1 end # Emit a hard `Spinel: <intrinsic>: <reason>; <suggestion>` diagnostic # and exit. `intrinsic` is the user-facing method name so the message # points at the right call. def iexec_reject(intrinsic, reason, suggestion) msg = "Spinel: " + intrinsic + ": " + reason if suggestion != "" msg = msg + "; " + suggestion end $stderr.puts msg exit(1) end # Rejection helper for the body_iexec_unsupported_kind enum. Maps the # construct name to a reason + suggestion, then rejects. def iexec_reject_kind(intrinsic, kind) reason = "" suggestion = "" if kind == "return" reason = "block uses 'return', which would return from the enclosing method" suggestion = "remove the 'return' (the block's last expression is its value), or move the non-local exit outside the " + intrinsic + " block" elsif kind == "break" reason = "block uses 'break', which has no enclosing-iterator semantics under " + intrinsic suggestion = "restructure to avoid non-local control flow" elsif kind == "next" reason = "block uses 'next', which has no enclosing-iterator semantics under " + intrinsic suggestion = "restructure to avoid non-local control flow" elsif kind == "def" reason = "block contains a 'def', defining a method at runtime" suggestion = "Spinel does not support runtime method definition; define the method statically on the receiver's class" elsif kind == "define_method" reason = "block calls 'define_method', defining a method at runtime" suggestion = "Spinel does not support runtime method definition; define the method statically on the receiver's class" else reason = "block uses unsupported construct '" + kind + "'" suggestion = "remove the construct or restructure the block body" end iexec_reject(intrinsic, reason, suggestion) end # Walks an instance_eval / instance_exec block body and returns the # name of the first unsupported construct found (return / break / # next / def / define_method), or "" when the body uses only # constructs the lift can model. Nested DefNodes return "def" at the # boundary rather than descending -- their bodies belong to a # different scope and are checked when those methods compile. def body_iexec_unsupported_kind(nid) if nid < 0 return "" end t = @nd_type[nid] if t == "ReturnNode" return "return" end if t == "BreakNode" return "break" end if t == "NextNode" return "next" end if t == "DefNode" return "def" end if t == "CallNode" && @nd_name[nid] == "define_method" return "define_method" end cs = [] push_child_ids(nid, cs) k = 0 while k < cs.length r = body_iexec_unsupported_kind(cs[k]) if r != "" return r end k = k + 1 end "" end # A `recv.<intrinsic>(args)` with no literal block and no `&proc` # argument is a no-block call. CRuby raises LocalJumpError at # runtime; Spinel surfaces the same as a compile-time error. Returns # 1 when the args carry a BlockArgumentNode (`&proc` form), so the # caller can leave that case for the proc-arg path instead. def iexec_args_have_block_arg(nid) args_id = @nd_arguments[nid] if args_id < 0 return 0 end aids = get_args(args_id) k = 0 while k < aids.length if @nd_type[aids[k]] == "BlockArgumentNode" return 1 end k = k + 1 end 0 end # Direct-path lift for `recv.instance_exec(args) { |params| body }`. # Sibling of ieval_rewrite_call -- detects an explicit-receiver # instance_exec call with a block literal, validates the end recv = @nd_receiver[nid] blk = @nd_block[nid] # Receiverless `instance_exec(...)` is the trampoline-body shape # (`def m(x, &b); instance_exec(x, &b); end`), handled by codegen's # call-site inlining. Leave it for that path. if recv < 0 return end if blk < 0 # An explicit-receiver call with no literal block: either a no-block # call (CRuby raises LocalJumpError -- surface it at compile time) # or a `&proc` form (left for the proc-arg path). if iexec_args_have_block_arg(nid) == 0 iexec_reject( "instance_exec", "no block given", "pass a literal block (`recv.instance_exec { ... }`)" ) end return end ci = recv_class_idx_for_rebind(recv, local_class) if ci < 0 # AOT codegen needs the receiver's class to emit a typed # `sp_iexec_<N>(sp_<C> *self, ...)` signature; a polymorphic / # un-narrowed receiver can't be lifted without runtime dispatch. iexec_reject( "instance_exec", "receiver type cannot be statically resolved", "assign the receiver to a typed local first (e.g. `r = Foo.new`), or narrow via a class predicate (`raise unless r.is_a?(Foo)`) before the call" ) end # Override-aware intrinsic: bypass the lift when the receiver's # class defines its own `instance_exec`; ordinary dispatch then # resolves to the user's method, preserving CRuby semantics. Same # shape as the override check in ieval_rewrite_call. if cls_find_method(ci, "instance_exec") >= 0 return end body_id = @nd_body[blk] # plumbing once we lift the body to a static function. Same # gate as ieval_rewrite_call. if body_id >= 0 && body_has_yield(body_id) == 1 return iexec_reject( "instance_exec", "block uses 'yield' or 'block_given?', which require an enclosing block-receiving method", "restructure the inner logic to take a Proc parameter instead of yielding" ) end # Reject non-local control flow and runtime method definition -- # return / break / next have no enclosing-method semantics once the # body is lifted to a static function, and def / define_method are # runtime definitions Spinel does not model. if body_id >= 0 kind = body_iexec_unsupported_kind(body_id) if kind != "" iexec_reject_kind("instance_exec", kind) end end # Block param extraction (mirrors compile_yield_method_call_stmt end end # On-the-fly last-expression type of a lifted iexec block, used to # type a local assigned from `recv.instance_exec(...) { ... }`. Computed # here rather than cached in a per-lift ivar so no new serialized # compiler state is added. Mirrors infer_ieval_body_return_types' setup: # rebind the class and declare the block params, then infer the body's # last-expression type. def iexec_call_value_type(n) if n < 0 || n >= @iexec_body_ids.length return "void" end bid = @iexec_body_ids[n] if bid < 0 return "void" end ci = @iexec_class_idxs[n] saved_ci = @current_class_idx @current_class_idx = ci push_scope pnames_s = @iexec_block_pnames[n] ptypes_s = @iexec_block_ptypes[n] if pnames_s != "" pnames = pnames_s.split("|") ptypes = ptypes_s.split("|") k = 0 while k < pnames.length pt = "int" if k < ptypes.length pt = ptypes[k] end declare_var(pnames[k], pt) k = k + 1 end end rt = infer_body_return(bid) pop_scope @current_class_idx = saved_ci rt end def is_iexec_call_name(mname) if mname.length <= 11 return 0spinel_codegen.rbmodifiedView file
Loading diff…
test/analyze_fail/instance_exec_def_in_block.rbaddedView file
Loading diff…
test/analyze_fail/instance_exec_def_in_block.stderr.expectedaddedView file
Loading diff…
test/analyze_fail/instance_exec_define_method.rbaddedView file
Loading diff…
test/analyze_fail/instance_exec_define_method.stderr.expectedaddedView file
Loading diff…
test/analyze_fail/instance_exec_no_block.rbaddedView file
Loading diff…
test/analyze_fail/instance_exec_no_block.stderr.expectedaddedView file
Loading diff…
test/instance_exec_capture.rbaddedView file
Loading diff…
test/instance_exec_capture.rb.expectedaddedView file
Loading diff…
test/instance_exec_override.rbaddedView file
Loading diff…
test/instance_exec_override.rb.expectedaddedView file
Loading diff…
test/instance_exec_parity.rbaddedView file
Loading diff…
test/instance_exec_parity.rb.expectedaddedView file
Loading diff…
test/instance_exec_return.rbaddedView file
Loading diff…
test/instance_exec_return.rb.expectedaddedView file
Loading diff…
test/instance_exec_valuetype.rbaddedView file
Loading diff…
test/instance_exec_valuetype.rb.expectedaddedView file
Loading diff…