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_call skip the lift when the receiver's class defines its own instance_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-time Spinel: diagnostics instead of a silent miscompile: def / define_method in the block, yield / block_given?, a no-block recv.instance_exec(args) (LocalJumpError in CRuby), and an unresolved receiver class.
  • Inline-splice lowering (compile_iexec_inline): heap receivers splice with self rebound; value-type receivers bind self by value and emit . rather than -> for ivar access. emit_iexec_funcs skips generating a static function for an inlined lift (it would be unused).
  • Expression position: x = recv.instance_exec { ... } declares x with 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_scope so 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

@@ -3461,11 +3461,17 @@
34613461 return "obj_" + @cls_names[@ieval_class_idxs[n]]
34623462 end
34633463 end
3464- # iexec direct-path lift: the synthetic `__sp_iexec_<N>` function is
3465- # void-returning in the baseline, so its call resolves to "void".
3466- # The expression-position follow-up surfaces the real last-expression
3467- # type here via infer_iexec_body_return_types.
3464+ # iexec direct-path lift: a heap receiver is inlined at the call site
3465+ # and the call's value is the block's last expression, so type the call
3466+ # by that expression (simple ctypes only -- array / hash / poly bodies
3467+ # stay "void" and take the receiver-yielding comma-expr fallback, like
3468+ # the ieval arm above). Computed on the fly to avoid a per-lift ivar.
34683469 if is_iexec_call_name(mname) == 1
3470+ suffix = mname[11, mname.length - 11]
3471+ rt = iexec_call_value_type(suffix.to_i)
3472+ if ieval_return_type_is_simple(rt) == 1
3473+ return rt
3474+ end
34693475 return "void"
34703476 end
34713477
@@ -9307,6 +9313,14 @@
93079313 if ci < 0
93089314 return
93099315 end
9316+ # Override-aware intrinsic: if the receiver's class (or its parent
9317+ # chain) defines its own `instance_eval`, the user has shadowed the
9318+ # intrinsic. Skip the lift so ordinary dispatch resolves to the
9319+ # user's method, matching CRuby. A gate on the method-name string
9320+ # alone would silently bypass the override.
9321+ if cls_find_method(ci, "instance_eval") >= 0
9322+ return
9323+ end
93109324 body_id = @nd_body[blk]
93119325 # v1: bail if the block uses yield/block_given?. Lifting it as a
93129326 # plain function would lose the enclosing method's block plumbing.
@@ -9315,6 +9329,15 @@
93159329 if body_id >= 0 && body_has_yield(body_id) == 1
93169330 return
93179331 end
9332+ # Reject non-local control flow and runtime method definition inside
9333+ # the block -- return / break / next / def / define_method have no
9334+ # statically-translatable semantics once the body is lifted.
9335+ if body_id >= 0
9336+ kind = body_iexec_unsupported_kind(body_id)
9337+ if kind != ""
9338+ iexec_reject_kind("instance_eval", kind)
9339+ end
9340+ end
93189341 n = @ieval_counter
93199342 @ieval_counter = @ieval_counter + 1
93209343 @ieval_class_idxs.push(ci)
@@ -9335,6 +9358,105 @@
93359358 @nd_block[nid] = -1
93369359 end
93379360
9361+ # Emit a hard `Spinel: <intrinsic>: <reason>; <suggestion>` diagnostic
9362+ # and exit. `intrinsic` is the user-facing method name so the message
9363+ # points at the right call.
9364+ def iexec_reject(intrinsic, reason, suggestion)
9365+ msg = "Spinel: " + intrinsic + ": " + reason
9366+ if suggestion != ""
9367+ msg = msg + "; " + suggestion
9368+ end
9369+ $stderr.puts msg
9370+ exit(1)
9371+ end
9372+
9373+ # Rejection helper for the body_iexec_unsupported_kind enum. Maps the
9374+ # construct name to a reason + suggestion, then rejects.
9375+ def iexec_reject_kind(intrinsic, kind)
9376+ reason = ""
9377+ suggestion = ""
9378+ if kind == "return"
9379+ reason = "block uses 'return', which would return from the enclosing method"
9380+ suggestion = "remove the 'return' (the block's last expression is its value), or move the non-local exit outside the " + intrinsic + " block"
9381+ elsif kind == "break"
9382+ reason = "block uses 'break', which has no enclosing-iterator semantics under " + intrinsic
9383+ suggestion = "restructure to avoid non-local control flow"
9384+ elsif kind == "next"
9385+ reason = "block uses 'next', which has no enclosing-iterator semantics under " + intrinsic
9386+ suggestion = "restructure to avoid non-local control flow"
9387+ elsif kind == "def"
9388+ reason = "block contains a 'def', defining a method at runtime"
9389+ suggestion = "Spinel does not support runtime method definition; define the method statically on the receiver's class"
9390+ elsif kind == "define_method"
9391+ reason = "block calls 'define_method', defining a method at runtime"
9392+ suggestion = "Spinel does not support runtime method definition; define the method statically on the receiver's class"
9393+ else
9394+ reason = "block uses unsupported construct '" + kind + "'"
9395+ suggestion = "remove the construct or restructure the block body"
9396+ end
9397+ iexec_reject(intrinsic, reason, suggestion)
9398+ end
9399+
9400+ # Walks an instance_eval / instance_exec block body and returns the
9401+ # name of the first unsupported construct found (return / break /
9402+ # next / def / define_method), or "" when the body uses only
9403+ # constructs the lift can model. Nested DefNodes return "def" at the
9404+ # boundary rather than descending -- their bodies belong to a
9405+ # different scope and are checked when those methods compile.
9406+ def body_iexec_unsupported_kind(nid)
9407+ if nid < 0
9408+ return ""
9409+ end
9410+ t = @nd_type[nid]
9411+ if t == "ReturnNode"
9412+ return "return"
9413+ end
9414+ if t == "BreakNode"
9415+ return "break"
9416+ end
9417+ if t == "NextNode"
9418+ return "next"
9419+ end
9420+ if t == "DefNode"
9421+ return "def"
9422+ end
9423+ if t == "CallNode" && @nd_name[nid] == "define_method"
9424+ return "define_method"
9425+ end
9426+ cs = []
9427+ push_child_ids(nid, cs)
9428+ k = 0
9429+ while k < cs.length
9430+ r = body_iexec_unsupported_kind(cs[k])
9431+ if r != ""
9432+ return r
9433+ end
9434+ k = k + 1
9435+ end
9436+ ""
9437+ end
9438+
9439+ # A `recv.<intrinsic>(args)` with no literal block and no `&proc`
9440+ # argument is a no-block call. CRuby raises LocalJumpError at
9441+ # runtime; Spinel surfaces the same as a compile-time error. Returns
9442+ # 1 when the args carry a BlockArgumentNode (`&proc` form), so the
9443+ # caller can leave that case for the proc-arg path instead.
9444+ def iexec_args_have_block_arg(nid)
9445+ args_id = @nd_arguments[nid]
9446+ if args_id < 0
9447+ return 0
9448+ end
9449+ aids = get_args(args_id)
9450+ k = 0
9451+ while k < aids.length
9452+ if @nd_type[aids[k]] == "BlockArgumentNode"
9453+ return 1
9454+ end
9455+ k = k + 1
9456+ end
9457+ 0
9458+ end
9459+
93389460 # Direct-path lift for `recv.instance_exec(args) { |params| body }`.
93399461 # Sibling of ieval_rewrite_call -- detects an explicit-receiver
93409462 # instance_exec call with a block literal, validates the
@@ -9365,14 +9487,41 @@
93659487 end
93669488 recv = @nd_receiver[nid]
93679489 blk = @nd_block[nid]
9490+ # Receiverless `instance_exec(...)` is the trampoline-body shape
9491+ # (`def m(x, &b); instance_exec(x, &b); end`), handled by codegen's
9492+ # call-site inlining. Leave it for that path.
93689493 if recv < 0
93699494 return
93709495 end
93719496 if blk < 0
9497+ # An explicit-receiver call with no literal block: either a no-block
9498+ # call (CRuby raises LocalJumpError -- surface it at compile time)
9499+ # or a `&proc` form (left for the proc-arg path).
9500+ if iexec_args_have_block_arg(nid) == 0
9501+ iexec_reject(
9502+ "instance_exec",
9503+ "no block given",
9504+ "pass a literal block (`recv.instance_exec { ... }`)"
9505+ )
9506+ end
93729507 return
93739508 end
93749509 ci = recv_class_idx_for_rebind(recv, local_class)
93759510 if ci < 0
9511+ # AOT codegen needs the receiver's class to emit a typed
9512+ # `sp_iexec_<N>(sp_<C> *self, ...)` signature; a polymorphic /
9513+ # un-narrowed receiver can't be lifted without runtime dispatch.
9514+ iexec_reject(
9515+ "instance_exec",
9516+ "receiver type cannot be statically resolved",
9517+ "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"
9518+ )
9519+ end
9520+ # Override-aware intrinsic: bypass the lift when the receiver's
9521+ # class defines its own `instance_exec`; ordinary dispatch then
9522+ # resolves to the user's method, preserving CRuby semantics. Same
9523+ # shape as the override check in ieval_rewrite_call.
9524+ if cls_find_method(ci, "instance_exec") >= 0
93769525 return
93779526 end
93789527 body_id = @nd_body[blk]
@@ -9380,7 +9529,21 @@
93809529 # plumbing once we lift the body to a static function. Same
93819530 # gate as ieval_rewrite_call.
93829531 if body_id >= 0 && body_has_yield(body_id) == 1
9383- return
9532+ iexec_reject(
9533+ "instance_exec",
9534+ "block uses 'yield' or 'block_given?', which require an enclosing block-receiving method",
9535+ "restructure the inner logic to take a Proc parameter instead of yielding"
9536+ )
9537+ end
9538+ # Reject non-local control flow and runtime method definition --
9539+ # return / break / next have no enclosing-method semantics once the
9540+ # body is lifted to a static function, and def / define_method are
9541+ # runtime definitions Spinel does not model.
9542+ if body_id >= 0
9543+ kind = body_iexec_unsupported_kind(body_id)
9544+ if kind != ""
9545+ iexec_reject_kind("instance_exec", kind)
9546+ end
93849547 end
93859548
93869549 # Block param extraction (mirrors compile_yield_method_call_stmt
@@ -9608,6 +9771,45 @@
96089771 end
96099772 end
96109773
9774+ # On-the-fly last-expression type of a lifted iexec block, used to
9775+ # type a local assigned from `recv.instance_exec(...) { ... }`. Computed
9776+ # here rather than cached in a per-lift ivar so no new serialized
9777+ # compiler state is added. Mirrors infer_ieval_body_return_types' setup:
9778+ # rebind the class and declare the block params, then infer the body's
9779+ # last-expression type.
9780+ def iexec_call_value_type(n)
9781+ if n < 0 || n >= @iexec_body_ids.length
9782+ return "void"
9783+ end
9784+ bid = @iexec_body_ids[n]
9785+ if bid < 0
9786+ return "void"
9787+ end
9788+ ci = @iexec_class_idxs[n]
9789+ saved_ci = @current_class_idx
9790+ @current_class_idx = ci
9791+ push_scope
9792+ pnames_s = @iexec_block_pnames[n]
9793+ ptypes_s = @iexec_block_ptypes[n]
9794+ if pnames_s != ""
9795+ pnames = pnames_s.split("|")
9796+ ptypes = ptypes_s.split("|")
9797+ k = 0
9798+ while k < pnames.length
9799+ pt = "int"
9800+ if k < ptypes.length
9801+ pt = ptypes[k]
9802+ end
9803+ declare_var(pnames[k], pt)
9804+ k = k + 1
9805+ end
9806+ end
9807+ rt = infer_body_return(bid)
9808+ pop_scope
9809+ @current_class_idx = saved_ci
9810+ rt
9811+ end
9812+
96119813 def is_iexec_call_name(mname)
96129814 if mname.length <= 11
96139815 return 0