|
| 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