Skip to content

Commit e23f700

Browse files
tannevaledclaude
andauthored
Mirror Kernel#binding onto Kernel, and give String instance_eval/class_eval the caller's locals (#727)
* Mirror Kernel#binding onto the Kernel module, as rb_define_global_function does `Kernel.private_instance_methods(false).include?(:binding)` answered false on ruby 4.0.5's true, while `self.send(:binding)` already returned a Binding: the method exists on Object and registerBinding marks it private, but the name was absent from registerKernelModuleFunctions' hand-kept list, so nothing copied the record onto cKernel. MRI installs it with rb_define_global_function("binding", rb_f_binding, 0) (proc.c ruby_4_0:4726) — the module-function form this list exists to reflect. Measured symmetric difference of Kernel.private_instance_methods(false), ruby 4.0.5 vs rbgo, before this change (MRI has 70, rbgo 60, nothing in rbgo that MRI lacks): binding, block_given?, iterator?, local_variables, set_trace_func, instance_variables_to_inspect, and the rubygems/pp preloads gem, gem_original_require, pp, Pathname. Of those only `binding` is a mirror omission — the method is defined and works. The rest are genuinely undefined here, or (block_given?) a compiler intrinsic with no method record for the mirror to copy; the comment records that census so the next reader does not re-measure it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Give instance_eval/class_eval with a String the caller's locals, as eval_under does MRI's specific_eval sends the String form to eval_under -> eval_string_with_cref (vm_eval.c ruby_4_0:2152-2187, 1882-1911), which builds the eval's base block from rb_vm_get_ruby_level_next_cfp(ec, ec->cfp) — the CALLER'S Ruby frame — so the source compiles as a child of the caller's scope and both reads and WRITES its local variables. Only then does it overwrite self with the receiver and push the cref (singleton class for instance_eval, the module for class_eval). rbgo compiled with no locals at all and ran on a fresh scope, so: x = 41; Object.new.instance_eval("x + 1") MRI 42 rbgo NoMethodError x = 1; Object.new.instance_eval("x = 99"); x MRI 99 rbgo 1 def shadow; :meth; end shadow = :local; Object.new.instance_eval("shadow") MRI :local rbgo :meth The write and shadow directions answered WRONGLY WITHOUT RAISING, which is why the read failure was the only one anyone had noticed. Kernel#eval already did the right thing through callerBinding + bindingEval; these are one mechanism in MRI, so they are one here now — specificEvalString takes the caller Binding and overwrites its self and definee. callerBinding returns a FRESH Binding per call, so the caller's frame keeps its own. 19 of 20 witnesses against ruby 4.0.5 now agree byte-for-byte (read x3 entry points, write-back x3, shadowing, self, immediate receiver, singleton/instance def placement, cref constant lookup, ivars, no-leak of a new local, __method__, explicit file and line). The 20th is a block-scope gap frameBinding already has for Kernel#eval and which instance_eval now shares; it is pinned by TestSpecificEvalStringInheritsTheBlockScopeGap rather than left silent. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Delete compileEval, which the string-eval rerouting left with no callers instanceEvalString and classEvalString were its only two callers and both now go through bindingEval, so every string-eval in the VM reaches the front end through one seam (compiler.CompileEvalWithLocals). A second, no-locals compile path is one no MRI behaviour asks for. Measured, not assumed: `go tool cover -func` put compileEval at 0.0% on the branch against 100.0% on merged main — the 17 statements that took the rounded total from 100.0% to 99.9%. Deleting it rather than leaving it uncalled follows the note evalDefinee already left in this file. It does not cascade: openParseCompileEval stays at 100.0% because openParseCompile (require, prelude) still calls it. The parseCompileEvalFn seam variable in frontend_open.go / frontend_closed.go is left in place; it is a package-level var, so it needs no caller, and both files are outside this change's scope. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Pin eight more string-eval shapes, and the nested eval as the same scope gap A second batch of witnesses measured on ruby 4.0.5, chosen to reach shapes the first twenty could not: the caller local read from inside a BLOCK in the eval string, the local being the caller's block PARAMETER, defined? reporting it, read-modify-write of it, and receivers that are frozen, immediate, or a Module rather than a Class. Seven of the ten were NoMethodError on merged main and now agree with MRI; they are assertions rather than prose because each is a different route into callerBinding. The eighth pins the opposite direction: a `def` inside a class_eval string does NOT close over the caller local, because a method body opens a fresh scope in MRI too. Only the raise is asserted — rbgo answers NoMethodError where ruby 4.0.5 answers NameError for a bare identifier, an engine-wide error-class difference this work does not touch. The remaining two divergences are one cause, not two, and the block-scope test now says so: a NESTED string-eval (`instance_eval("... instance_eval('y')")`) fails for exactly the reason the block case does — the outer eval's frame resolves y up-scope instead of owning a slot, so frameBinding cannot see it from inside. Grouping them under one test means the frameBinding fix will flip all three together. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Delete currentMethodCtxPtr, the second helper the rerouting left with no callers This is the ubuntu coverage gate, not a tidy-up. `test (ubuntu-latest)` failed on the previous commit with `coverage 99.9% < 100%`, and its own below-100 listing named the cause: kernel_introspect.go:387 currentMethodCtxPtr at 0.0%. macOS passed the same commit, so the two dead statements sat exactly on the rounding boundary — which is why the rounded total is the wrong instrument and the below-100 LIST is the right one. instanceEvalString was its only caller (`vm.pendingMethodCtx = vm.currentMethodCtxPtr()`). bindingEval now sets pendingMethodCtx from the Binding's own recorded frame pair instead, and that is the better value: frameBinding skips frames whose scope exec has not published, exactly as rb_vm_get_binding_creatable_next_cfp does, whereas currentMethodCtx takes the top frame unconditionally. Pairing frame N's locals with frame N+1's method name would be incoherent, so there is no honest way to keep it called. Covering it from a test instead was the other option and is the wrong one: a test that exists only to walk unreachable code turns the 100% gate into decoration. currentMethodCtx itself stays — Kernel#__method__ and #__callee__ call it directly. Measured after: below-100 functions are 16 on merged main and 16 here, with an EMPTY symmetric difference; the full function set gains specificEvalString (100.0%) and loses compileEval and currentMethodCtxPtr, both deliberate. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 1a79138 commit e23f700

4 files changed

Lines changed: 238 additions & 43 deletions

File tree

‎internal/vm/builtins.go‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6562,11 +6562,23 @@ func (vm *VM) registerKernelPublicMethods() {
65626562
// Kernel.private_instance_methods(false) from ruby 4.0.6 intersected with what
65636563
// rbgo defines; a name absent on this build (e.g. fork/exec/system under wasm) is
65646564
// simply skipped. Runs after every listed method is registered.
6565+
//
6566+
// "binding" is on the list for the same reason every other name is, and it was
6567+
// MISSING: rb_define_global_function("binding", rb_f_binding, 0) (proc.c
6568+
// ruby_4_0:4726) is the module-function form, registerBinding already marks the
6569+
// Object-side record private, but nothing mirrored it onto Kernel — so
6570+
// Kernel.private_instance_methods(false).include?(:binding) answered false while
6571+
// self.send(:binding) worked. A hand-kept list drifts one name at a time; the
6572+
// symmetric difference against ruby 4.0.5 is now four genuinely-undefined names
6573+
// (iterator?, local_variables, set_trace_func, instance_variables_to_inspect),
6574+
// one that is an intrinsic and not yet a method (block_given?), and the rubygems
6575+
// /pp additions MRI preloads (gem, gem_original_require, pp, Pathname) — none of
6576+
// which this mirror can reach, since it only reflects records that exist.
65656577
func (vm *VM) registerKernelModuleFunctions() {
65666578
names := []string{
65676579
"Array", "Complex", "Float", "Hash", "Integer", "Rational", "String",
6568-
"__dir__", "`", "abort", "at_exit", "autoload", "autoload?", "caller",
6569-
"caller_locations",
6580+
"__dir__", "`", "abort", "at_exit", "autoload", "autoload?", "binding",
6581+
"caller", "caller_locations",
65706582
"catch", "eval", "exec", "exit", "exit!", "fail", "fork", "format", "gets",
65716583
"global_variables", "lambda",
65726584
"load", "loop", "open", "p", "print", "printf", "proc", "putc", "puts",

‎internal/vm/eval.go‎

Lines changed: 54 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"strconv"
66
"strings"
77

8-
"github.com/go-embedded-ruby/ruby/internal/bytecode"
98
"github.com/go-embedded-ruby/ruby/internal/object"
109
)
1110

@@ -23,7 +22,7 @@ import (
2322
// method, proc or binding the source creates. When no file is given MRI does not
2423
// borrow the caller's path either: get_eval_default_path (vm_eval.c
2524
// ruby_4_0:1666) builds the synthetic "(eval at FILE:LINE)" naming where the
26-
// eval was WRITTEN. evalLocation is that pair, and compileEval stamps it on.
25+
// eval was WRITTEN. evalLocation is that pair, and bindingEval stamps it on.
2726
type evalLocation struct {
2827
file string
2928
line int
@@ -100,25 +99,15 @@ func (vm *VM) evalLineno(v object.Value) int {
10099
return 0
101100
}
102101

103-
// compileEval compiles src at loc and stamps the path onto the ISeq and every one
104-
// of its children (setISeqFile, so a proc or method the source defines reports
105-
// the eval's path too, as MRI's whole eval ISeq tree carries one path).
106-
//
107-
// The first LINE has to go into the compilation rather than be applied to the
108-
// finished ISeq: MRI hands it to the parser (pm_options_line_set,
109-
// rb_parser_compile_string_path), so it reaches not only every insns_info entry
110-
// and nested first_lineno but also the Integer literal `__LINE__` becomes — and
111-
// that literal is indistinguishable in the constant pool from any other Integer
112-
// once compilation is over. compiler.CompileEval takes it for that reason.
113-
func (vm *VM) compileEval(src string, loc evalLocation) *bytecode.ISeq {
114-
iseq, cerr := parseCompileEvalFn(src, loc.line)
115-
if cerr != nil {
116-
raiseEvalSyntaxError(loc, cerr)
117-
}
118-
iseq.Name = "(eval)"
119-
setISeqFile(iseq, loc.file)
120-
return iseq
121-
}
102+
// compileEval is GONE. It compiled a string-eval with NO locals and stamped the
103+
// path on, and its only two callers were instanceEvalString and classEvalString
104+
// — which now go through bindingEval, because MRI compiles the String form of
105+
// specific_eval against the caller's scope (see specificEvalString). Every
106+
// string-eval in the VM therefore reaches the front end through one seam,
107+
// bindingEval's compiler.CompileEvalWithLocals, and a second no-locals seam
108+
// would be a path no MRI behaviour asks for. Deleting it rather than leaving it
109+
// uncalled is the point, exactly as for evalDefinee below: an unreachable
110+
// compile path is the shape a later wave would trust.
122111

123112
// raiseEvalSyntaxError raises the SyntaxError for a string that would not parse,
124113
// with the LOCATION in front of the message as MRI reports it: MRI's parser
@@ -158,29 +147,61 @@ func parseErrorLine(msg string) (int, string, bool) {
158147
return n, rest[i+2:], true
159148
}
160149

161-
// instanceEvalString backs the String form of BasicObject#instance_eval: it
162-
// compiles src and runs it with self as the receiver and the receiver's
163-
// singleton class as the definee, so a `def` in the source becomes a singleton
164-
// method and `self`/instance variables resolve to the receiver. An immediate
150+
// specificEvalString is MRI's specific_eval -> eval_under for the STRING form of
151+
// instance_eval / module_eval / class_eval (vm_eval.c ruby_4_0:2152-2187). Three
152+
// things come from three different places, and rbgo used to get only two of them:
153+
//
154+
// - the LOCALS are the CALLER'S. eval_under hands the source to
155+
// eval_string_with_cref, which builds its base block from
156+
// rb_vm_get_ruby_level_next_cfp(ec, ec->cfp) — the Ruby frame below the CFUNC
157+
// — so the eval'd source is compiled as a child scope of the calling frame
158+
// and sees, and can ASSIGN to, its local variables (vm_eval.c
159+
// ruby_4_0:1882-1911). `x = 41; Object.new.instance_eval("x + 1")` is 42 on
160+
// ruby 4.0.5; rbgo ran with a FRESH, EMPTY scope and raised NoMethodError for
161+
// `x`. The write direction failed silently, which is worse: `x = 1;
162+
// Object.new.instance_eval("x = 99"); x` stayed 1 instead of becoming 99, and
163+
// a caller local shadowing a method of the same name lost to the method.
164+
// - the SELF is the RECEIVER, not the calling frame's — eval_string_with_cref
165+
// overwrites block.as.captured.self with it.
166+
// - the CREF is PUSHED, not inherited: vm_cref_push(ec, self, NULL, FALSE,
167+
// singleton). singleton is TRUE for instance_eval (the definee is the
168+
// receiver's singleton class, so a `def` becomes a singleton method) and
169+
// FALSE for module_eval/class_eval (the definee is the module itself, so a
170+
// `def` becomes an instance method). That half rbgo already had right, and it
171+
// is why this takes a caller Binding and OVERWRITES both fields rather than
172+
// using the binding's own: callerBinding returns a fresh Binding each call,
173+
// so the caller's frame keeps its self and definee.
174+
//
175+
// The three used to be split across two code paths — Kernel#eval already went
176+
// through callerBinding + bindingEval for exactly this, while the specific_eval
177+
// family compiled with no locals at all. They are one mechanism in MRI and one
178+
// here now.
179+
func (vm *VM) specificEvalString(self object.Value, definee *RClass, src string, loc evalLocation) object.Value {
180+
cb := vm.callerBinding()
181+
cb.self = self
182+
cb.definee = definee
183+
return vm.bindingEval(cb, src, loc)
184+
}
185+
186+
// instanceEvalString backs the String form of BasicObject#instance_eval: the
187+
// source runs with self as the receiver and the receiver's singleton class as
188+
// the definee, over the CALLER'S locals (see specificEvalString). An immediate
165189
// receiver has no singleton class, so its own class stands in as the definee
166190
// (source that only reads still works).
167191
func (vm *VM) instanceEvalString(self object.Value, src string, loc evalLocation) object.Value {
168-
iseq := vm.compileEval(src, loc)
169192
definee, ok := vm.ensureSingleton(self)
170193
if !ok {
171194
definee = vm.classOf(self)
172195
}
173-
vm.pendingMethodCtx = vm.currentMethodCtxPtr()
174-
return vm.exec(iseq, self, nil, definee, "", nil, nil, nil, nil, nil)
196+
return vm.specificEvalString(self, definee, src, loc)
175197
}
176198

177199
// classEvalString backs the String form of Module#module_eval / #class_eval: the
178-
// class is both self and the method-definition target, with a fresh local scope,
179-
// so a top-level `def` in the source becomes an instance method of cls — the
180-
// mechanism racc's runtime uses to graft do_parse/yyparse.
200+
// class is both self and the method-definition target — so a top-level `def` in
201+
// the source becomes an instance method of cls, the mechanism racc's runtime uses
202+
// to graft do_parse/yyparse — over the CALLER'S locals (see specificEvalString).
181203
func (vm *VM) classEvalString(cls *RClass, src string, loc evalLocation) object.Value {
182-
iseq := vm.compileEval(src, loc)
183-
return vm.exec(iseq, cls, nil, cls, "", nil, nil, nil, nil, nil)
204+
return vm.specificEvalString(cls, cls, src, loc)
184205
}
185206

186207
// registerEval installs Kernel#eval — the embedded front-end's reason for being.

‎internal/vm/kernel_introspect.go‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -381,14 +381,6 @@ func (vm *VM) currentMethodCtx() frameMethod {
381381
return vm.frameMethods[len(vm.frameMethods)-1]
382382
}
383383

384-
// currentMethodCtxPtr returns a heap copy of currentMethodCtx for handing to the
385-
// next exec frame via pendingMethodCtx (Kernel#eval, so eval'd code inherits the
386-
// caller's method context).
387-
func (vm *VM) currentMethodCtxPtr() *frameMethod {
388-
ctx := vm.currentMethodCtx()
389-
return &ctx
390-
}
391-
392384
// callerSlice selects the levels Kernel#caller / #caller_locations return from the
393385
// argument list, applying MRI's semantics over caller(0) — backtraceFrames(0),
394386
// the current frame stack nearest-first. A Range slices that list exactly like

‎internal/vm/wave_b_binding_test.go‎

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
// Copyright (c) the go-embedded-ruby/ruby authors
2+
//
3+
// SPDX-License-Identifier: BSD-3-Clause
4+
5+
package vm
6+
7+
import "testing"
8+
9+
// TestKernelBindingIsMirroredOntoKernel pins the module_function split for
10+
// Kernel#binding. MRI installs it with rb_define_global_function("binding",
11+
// rb_f_binding, 0) (proc.c ruby_4_0:4726), so it is a PRIVATE instance method of
12+
// Kernel and a PUBLIC method on the Kernel module. The method already worked here
13+
// — self.send(:binding) returned a Binding — but the name was missing from
14+
// registerKernelModuleFunctions' list, so none of the reflection below saw it.
15+
// Every expectation was measured on ruby 4.0.5.
16+
func TestKernelBindingIsMirroredOntoKernel(t *testing.T) {
17+
cases := []struct{ src, want string }{
18+
// The omission itself, in the shape core/kernel/binding_spec.rb reads it.
19+
{`p Kernel.private_instance_methods(false).include?(:binding)`, "true"},
20+
{`p Kernel.private_method_defined?(:binding)`, "true"},
21+
{`p Kernel.instance_method(:binding).owner`, "Kernel"},
22+
{`p Kernel.instance_method(:binding).name`, ":binding"},
23+
// -1, not MRI's 0: EVERY native method reports -1 here (Object
24+
// #frozen?/#object_id do too, both 0 on ruby 4.0.5), so this is the
25+
// engine-wide native-arity gap and not something the mirror introduced.
26+
// It is asserted rather than omitted so the mirrored record is seen to
27+
// carry the ORIGINAL's arity instead of inventing one.
28+
{`p Kernel.instance_method(:binding).arity`, "-1"},
29+
// Public on the Kernel module, like every other module_function.
30+
{`p Kernel.public_methods.include?(:binding)`, "true"},
31+
{`p Kernel.binding.class`, "Binding"},
32+
// And still private on the instance side, still reachable through send —
33+
// the half that already worked, kept under test so a later mirror change
34+
// cannot trade one for the other.
35+
{`p respond_to?(:binding)`, "false"},
36+
{`p respond_to?(:binding, true)`, "true"},
37+
{`p self.send(:binding).class`, "Binding"},
38+
{`p binding.class`, "Binding"},
39+
}
40+
for _, c := range cases {
41+
if got := eval(t, c.src); got != c.want+"\n" {
42+
t.Errorf("src=%q got=%q want=%q", c.src, got, c.want+"\n")
43+
}
44+
}
45+
46+
// An explicit receiver is refused, as rb_define_global_function's private
47+
// Object-side copy demands. Measured on ruby 4.0.5.
48+
class, msg := evalErr(t, `Object.new.binding`)
49+
if want := "private method 'binding' called for an instance of Object"; class != "NoMethodError" || msg != want {
50+
t.Errorf("Object.new.binding: got %s:%q want NoMethodError:%q", class, msg, want)
51+
}
52+
}
53+
54+
// TestSpecificEvalStringSeesCallerLocals covers the STRING form of
55+
// instance_eval / module_eval / class_eval. MRI's specific_eval routes it to
56+
// eval_under -> eval_string_with_cref (vm_eval.c ruby_4_0:2152-2187,
57+
// 1882-1911), which compiles the source as a child scope of
58+
// rb_vm_get_ruby_level_next_cfp — the CALLER'S frame — while overwriting self
59+
// with the receiver and PUSHING a cref (the singleton class for instance_eval,
60+
// the module itself for class_eval).
61+
//
62+
// rbgo ran the source in a fresh, EMPTY scope, so a caller local raised
63+
// NoMethodError on read and was silently ignored on write. Both directions are
64+
// asserted: the write one is where a half-fix shows, because it fails without
65+
// raising anything.
66+
func TestSpecificEvalStringSeesCallerLocals(t *testing.T) {
67+
cases := []struct{ name, src, want string }{
68+
// Read, all three entry points.
69+
{"instance_eval read", `x = 41; p Object.new.instance_eval("x + 1")`, "42"},
70+
{"class_eval read", `x = 41; p String.class_eval("x + 1")`, "42"},
71+
{"module_eval read", `x = 41; p Comparable.module_eval("x + 1")`, "42"},
72+
// Write back into the caller's local — the direction a half-fix misses.
73+
{"instance_eval write", `x = 1; Object.new.instance_eval("x = 99"); p x`, "99"},
74+
{"class_eval write", `x = 1; String.class_eval("x = 99"); p x`, "99"},
75+
{"write inside a method", `def w; z = 1; Object.new.instance_eval("z = 42"); z; end; p w`, "42"},
76+
// A caller local SHADOWS a method of the same name, as it does in ordinary
77+
// Ruby: this answered :meth before, silently.
78+
{"local shadows method", `def shadow; :meth; end; shadow = :local; p Object.new.instance_eval("shadow")`, ":local"},
79+
// The receiver is self even while the locals come from the caller — the two
80+
// halves come from different places (eval_string_with_cref overwrites
81+
// block.as.captured.self).
82+
{"self is the receiver", `o = Object.new; p o.instance_eval("self").equal?(o)`, "true"},
83+
{"self over an immediate", `n = 3; p 5.instance_eval("self + n")`, "8"},
84+
{"class_eval self is the module", `p String.class_eval("self")`, "String"},
85+
// The cref is PUSHED, not the caller's: singleton for instance_eval so a
86+
// `def` becomes a singleton method, the module for class_eval so it becomes
87+
// an instance method. This half already worked; it must survive the change.
88+
{"instance_eval def is a singleton method",
89+
`o = Object.new; o.instance_eval("def zzz; :sing; end"); p [o.zzz, o.singleton_methods]`, "[:sing, [:zzz]]"},
90+
{"class_eval def is an instance method",
91+
`c = Class.new; c.class_eval("def yyy; :inst; end"); p [c.new.yyy, c.instance_methods(false)]`, "[:inst, [:yyy]]"},
92+
{"class_eval def self. is a class method",
93+
`c = Class.new; c.class_eval("def self.cm; :cm; end"); p c.cm`, ":cm"},
94+
{"constant resolves through the pushed cref",
95+
`class O13; K13 = :found; end; p O13.class_eval("K13")`, ":found"},
96+
{"ivars resolve against the receiver",
97+
`o = Object.new; o.instance_variable_set(:@a, 7); p o.instance_eval("@a")`, "7"},
98+
// A local the eval string CREATES does not leak back to the caller: the
99+
// caller's ISeq has no slot for it, so `defined?` there is nil (MRI agrees).
100+
{"a new local does not leak", `Object.new.instance_eval("qq = 5"); p defined?(qq)`, "nil"},
101+
// eval is transparent to __method__ through this path too.
102+
{"__method__ is the caller's", `def w12; Object.new.instance_eval("__method__"); end; p w12`, ":w12"},
103+
// The (file, line) pair is still specific_eval's argv[1]/argv[2], not the
104+
// caller's: routing through the caller's scope must not borrow its path.
105+
{"explicit filename wins", `p Object.new.instance_eval("__FILE__", "given.rb")`, `"given.rb"`},
106+
{"explicit first line wins", `p Object.new.instance_eval("__LINE__", "given.rb", 40)`, "40"},
107+
// A second batch of shapes the first cannot reach: the caller local is read
108+
// from inside a BLOCK in the eval string, is a block PARAMETER of the
109+
// caller, is reported by defined?, is reassigned from its own value, or
110+
// belongs to a frame whose receiver is an immediate or a frozen object.
111+
// All measured on ruby 4.0.5.
112+
{"a block in the eval string closes over it",
113+
`m = 3; p Object.new.instance_eval("[1,2].map { |z| z * m }")`, "[3, 6]"},
114+
{"the caller local is a block parameter",
115+
`p([7].map { |bp| Object.new.instance_eval("bp * 3") })`, "[21]"},
116+
{"defined? sees it",
117+
`dd = 1; p Object.new.instance_eval("defined?(dd)")`, `"local-variable"`},
118+
{"read-modify-write of a caller local",
119+
`k = 0; Object.new.instance_eval("k = k + 7"); p k`, "7"},
120+
{"a frozen receiver still reads caller locals",
121+
`s = "str".freeze; n = 2; p s.instance_eval("size + n")`, "5"},
122+
{"module_eval over a Module, not a Class",
123+
`w = 9; m = Module.new; p m.module_eval("w")`, "9"},
124+
{"value assigned before the eval, not at declaration",
125+
`q = nil; q = 4; p Object.new.instance_eval("q")`, "4"},
126+
// A `def` inside the eval string does NOT close over the caller local: a
127+
// method body opens a fresh scope in MRI too. rbgo reports NoMethodError
128+
// where ruby 4.0.5 reports NameError for a bare identifier — an
129+
// engine-wide error-class difference, unchanged by this work — so only the
130+
// fact that it RAISES is asserted here.
131+
{"a def in the eval string does not close over it",
132+
`v = 5; c = Class.new; c.class_eval("def g; v; end"); p((c.new.g rescue :raised))`, ":raised"},
133+
}
134+
for _, c := range cases {
135+
if got := eval(t, c.src); got != c.want+"\n" {
136+
t.Errorf("%s: src=%q got=%q want=%q", c.name, c.src, got, c.want+"\n")
137+
}
138+
}
139+
}
140+
141+
// TestSpecificEvalStringInheritsTheBlockScopeGap records a divergence this change
142+
// does NOT close, so that nobody reads the tests above as a claim that it did.
143+
//
144+
// rbgo's frameBinding (internal/vm/vm.go) builds a Binding from the frame's own
145+
// iseq.Locals and does not walk the enclosing Env chain, so a binding captured
146+
// inside a BLOCK cannot see the locals of the method or top level around it. MRI
147+
// does: `y = 5; [1].map { eval("y * 2") }` is [10] on ruby 4.0.5.
148+
//
149+
// That gap is Kernel#eval's already — it predates this change and behaves
150+
// identically there — and instance_eval now shares it precisely BECAUSE the two
151+
// were joined onto one mechanism. Pinning it keeps the two in step: when
152+
// frameBinding learns to walk the parent env, this test fails and both want
153+
// is [10].
154+
func TestSpecificEvalStringInheritsTheBlockScopeGap(t *testing.T) {
155+
const evalSrc = `y = 5; p([1].map { eval("y * 2") })`
156+
const ievalSrc = `y = 5; p([1].map { Object.new.instance_eval("y * 2") })`
157+
// A NESTED string-eval is the same gap wearing a different hat: the outer
158+
// eval's own frame resolves `y` up-scope rather than owning a slot for it, so
159+
// the inner callerBinding cannot see it either. ruby 4.0.5 answers 2.
160+
const nestedSrc = `y = 5; p Object.new.instance_eval("Object.new.instance_eval('y * 2')")`
161+
const want = "undefined method 'y' for "
162+
for _, src := range []string{evalSrc, ievalSrc, nestedSrc} {
163+
class, msg := evalErr(t, src)
164+
if class != "NoMethodError" || len(msg) < len(want) || msg[:len(want)] != want {
165+
t.Errorf("src=%q: got %s:%q; expected the shared block-scope gap (%s%s…). "+
166+
"If frameBinding now walks the enclosing env, both of these answer [10] on "+
167+
"ruby 4.0.5 and this test should become that assertion.", src, class, msg, "NoMethodError:", want)
168+
}
169+
}
170+
}

0 commit comments

Comments
 (0)