From 7d682b4a2f9f3d640d088a0d1b75cab725c2e0ef Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 12:21:21 +0200 Subject: [PATCH 1/4] BasicObject: fire singleton_method_added/removed/undefined hooks (MRI 4.0.6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Define the three singleton-method definition hooks as private no-op instance methods on BasicObject and fire them, matching MRI, on the object that owns a singleton method whenever one is added, removed, or undefined — via def obj.x / def self.x, class << self, define_method, define_singleton_method, alias / alias_method, remove_method, and undef / undef_method. A per-object singleton class now records its attached object so the hook has a receiver; a class metaclass uses its metaOf back-pointer. Firing routes through a resolver that skips the BasicObject default no-op (so ordinary defs stay cheap) and, when the hook has been undef'd, dispatches to the object's method_missing (NoMethodError by default) exactly as MRI does. undef of a hook whose default lives on BasicObject but is reachable only through the attached object (a metaclass's super chain does not bridge to BasicObject's instance methods) is now permitted. core/basicobject singleton_method_{added,removed,undefined} specs go from 1/0/0 passing to 11/2/2 (all green). Updates the stale core-methods test to MRI's private_instance_methods set. Co-Authored-By: Claude Opus 4.8 --- internal/vm/basicobject_core_internal_test.go | 6 +- internal/vm/basicobject_residuals_test.go | 132 ++++++++++++++++++ internal/vm/builtins.go | 19 ++- internal/vm/modulefunc.go | 76 +++++++++- internal/vm/object_model.go | 35 ++++- internal/vm/singleton.go | 2 + internal/vm/vm.go | 9 +- 7 files changed, 266 insertions(+), 13 deletions(-) create mode 100644 internal/vm/basicobject_residuals_test.go diff --git a/internal/vm/basicobject_core_internal_test.go b/internal/vm/basicobject_core_internal_test.go index a29f9569..0751315a 100644 --- a/internal/vm/basicobject_core_internal_test.go +++ b/internal/vm/basicobject_core_internal_test.go @@ -15,10 +15,12 @@ import "testing" func TestBasicObjectCoreMethods(t *testing.T) { cases := []struct{ src, want string }{ // The public instance-method set matches MRI exactly (no initialize / - // method_missing, which are private). + // method_missing / singleton_method_* hooks, which are private). {`p BasicObject.instance_methods(false).sort`, "[:!, :!=, :==, :__id__, :__send__, :equal?, :instance_eval, :instance_exec]"}, - {`p BasicObject.private_instance_methods(false).sort`, "[:initialize, :method_missing]"}, + // The private set includes the singleton-method definition hooks (MRI 4.0.6). + {`p BasicObject.private_instance_methods(false).sort`, + "[:initialize, :method_missing, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined]"}, // A bare BasicObject has the core methods (no Kernel). {`b = BasicObject.new; p b.__send__(:equal?, b)`, "true"}, {`b = BasicObject.new; p b.__send__(:==, b)`, "true"}, diff --git a/internal/vm/basicobject_residuals_test.go b/internal/vm/basicobject_residuals_test.go new file mode 100644 index 00000000..8d537b5d --- /dev/null +++ b/internal/vm/basicobject_residuals_test.go @@ -0,0 +1,132 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "strings" + "testing" +) + +// TestSingletonMethodHooks covers the singleton_method_added / _removed / +// _undefined definition hooks: MRI calls them on the object that owns a singleton +// method whenever one is added to, removed from, or undefined on it. Each case +// drives a distinct definition path (def obj.x, def self.x, class << self, +// define_method, define_singleton_method, alias, remove_method, undef). +func TestSingletonMethodHooks(t *testing.T) { + cases := []struct{ src, want string }{ + // singleton_method_added, per-object singleton (def obj.x). Defining the hook + // itself fires it once (MRI), then the following def fires it again. + {`o = Object.new +def o.singleton_method_added(n); puts "A #{n}"; end +def o.foo; end`, "A singleton_method_added\nA foo\n"}, + // A class receiver (def self.x lands on the class's singleton methods) and the + // class << self / define_singleton_method singleton-class paths all fire on the + // class. + {`c = Class.new +def c.singleton_method_added(n); puts "C #{n}"; end +class << c; def bar; end; end +c.define_singleton_method(:baz){}`, "C singleton_method_added\nC bar\nC baz\n"}, + // A method defined into a plain object's singleton class (class << obj) fires on + // the attached object. + {`o = Object.new +def o.singleton_method_added(n); puts "S #{n}"; end +class << o; def m; end; end`, "S singleton_method_added\nS m\n"}, + // alias_method, syntax alias, and define_method inside a singleton class each + // count as adding a singleton method. + {`c = Class.new +def c.singleton_method_added(n); puts "C #{n}"; end +def c.orig; end +class << c; alias_method :al, :orig; end +class << c; alias sy orig; end +class << c; define_method(:dm){}; end`, + "C singleton_method_added\nC orig\nC al\nC sy\nC dm\n"}, + // singleton_method_removed fires when a singleton method is removed. + {`o = Object.new +def o.singleton_method_removed(n); puts "R #{n}"; end +def o.gone; end +class << o; remove_method :gone; end`, "R gone\n"}, + // singleton_method_undefined fires when a singleton method is undefined. + {`o = Object.new +def o.singleton_method_undefined(n); puts "U #{n}"; end +def o.und; end +class << o; undef_method :und; end`, "U und\n"}, + // When the hook is undef'd, defining a singleton method routes to the object's + // #method_missing (here recording the hook name and method). + {`o = Object.new +class << o + def method_missing(*a); puts "MM #{a.inspect}"; end + undef_method :singleton_method_added + def foo; end +end`, "MM [:singleton_method_added, :foo]\n"}, + // The default hooks are private no-op methods on BasicObject — a direct call + // returns nil and is otherwise silent. + {`p BasicObject.new.__send__(:singleton_method_added, :x)`, "nil\n"}, + {`p BasicObject.new.__send__(:singleton_method_removed, :x)`, "nil\n"}, + {`p BasicObject.new.__send__(:singleton_method_undefined, :x)`, "nil\n"}, + // A def into a normal class still fires method_added, not the singleton hook. + {`class MAOnly + def self.method_added(n); puts "MA #{n}"; end + def inst; end +end`, "MA inst\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + +// TestSingletonHookUndefRaises covers the undef'd-hook path with no user +// method_missing: the definition routes to the default method_missing, which +// raises NoMethodError naming the hook. +func TestSingletonHookUndefRaises(t *testing.T) { + err := runErr(t, `o = Object.new +class << o; undef_method :singleton_method_added; end +def o.bar; end`) + if err == nil || !strings.Contains(err.Error(), "NoMethodError") || + !strings.Contains(err.Error(), "singleton_method_added") { + t.Fatalf("want NoMethodError for singleton_method_added, got %v", err) + } +} + +// TestUndefHookOnMetaclass covers undef of a hook whose default lives on +// BasicObject and is reachable only through the attached object (a class's +// metaclass superclass chain does not bridge to BasicObject's instance methods): +// the undef must succeed, and a subsequent class-method def must then raise +// NoMethodError rather than the undef itself raising NameError. +func TestUndefHookOnMetaclass(t *testing.T) { + err := runErr(t, `class MetaUndef + class << self; undef_method :singleton_method_added; end +end +def MetaUndef.foo; end`) + if err == nil || !strings.Contains(err.Error(), "NoMethodError") { + t.Fatalf("want NoMethodError after undef on metaclass, got %v", err) + } +} + +// TestUndefMissingMethodStillRaises guards the non-singleton branch of the undef +// resolution: undef'ing a name defined nowhere is still a NameError. +func TestUndefMissingMethodStillRaises(t *testing.T) { + err := runErr(t, `class UndefMissing; undef_method :never_defined; end`) + if err == nil || !strings.Contains(err.Error(), "NameError") { + t.Fatalf("want NameError for undef of undefined method, got %v", err) + } +} + +// TestClonePreservesSingletonHooks checks that a cloned object's copied singleton +// class still fires the hook for methods added to the clone (its attached object +// is the clone, not the source). +func TestClonePreservesSingletonHooks(t *testing.T) { + got := eval(t, `o = Object.new +def o.singleton_method_added(n); puts n; end +c = o.clone +def c.after_clone; end`) + // The clone copies singleton_method_added, so defining after_clone on the clone + // fires it. (The def on the source before cloning also fired, printing the hook + // name; the clone re-runs none of that.) + if !strings.Contains(got, "after_clone") { + t.Fatalf("want hook fired on clone, got %q", got) + } +} diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 7c9046b0..f59d62ad 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -945,6 +945,18 @@ func (vm *VM) bootstrap() { map[string]object.Value{"@name": nameSym, "@receiver": self, "@args": callArgs}) return object.NilV }) + // The singleton-method definition hooks: private no-op instance methods on + // BasicObject that MRI calls on an object whenever a singleton method is added + // to, removed from, or undefined on it. The VM fires them (see + // fireSingletonMethodHook) only when overridden, so the defaults here mainly + // satisfy private_instance_methods and a direct call. + singletonHookNoop := func(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { + return object.NilV + } + for _, hook := range []string{"singleton_method_added", "singleton_method_removed", "singleton_method_undefined"} { + vm.cBasicObject.define(hook, singletonHookNoop) + vm.setInstanceVisibility(vm.cBasicObject, hook, visPrivate) + } // initialize and method_missing are PRIVATE instance methods of BasicObject // (as in MRI): callable via new/super and the dispatch fallback, never listed // in instance_methods, only in private_instance_methods. @@ -1562,7 +1574,7 @@ func (vm *VM) bootstrap() { cm.name, cm.owner, cm.vis = name, cls, vis cls.methods[name] = &cm bumpMethodSerial() - vm.fireMethodAdded(cls, name) + vm.fireMethodDefined(cls, name) return object.Symbol(name) case *UnboundMethod: vm.checkTransplantBindable(cls, src.owner) @@ -1571,7 +1583,7 @@ func (vm *VM) bootstrap() { cm.name, cm.owner, cm.vis = name, cls, vis cls.methods[name] = &cm bumpMethodSerial() - vm.fireMethodAdded(cls, name) + vm.fireMethodDefined(cls, name) return object.Symbol(name) } } @@ -1591,7 +1603,7 @@ func (vm *VM) bootstrap() { } cls.methods[name] = &Method{name: name, proc: body, owner: cls, vis: vis} bumpMethodSerial() - vm.fireMethodAdded(cls, name) + vm.fireMethodDefined(cls, name) return object.Symbol(name) }) @@ -8832,6 +8844,7 @@ func (vm *VM) cloneSingleton(src, dst object.Value) { } ns := newClass("", vm.classOf(dst)) ns.isSingleton = true + ns.attached = dst // the clone owns this singleton class; hooks fire on it for name, m := range sc.methods { cp := *m cp.owner = ns diff --git a/internal/vm/modulefunc.go b/internal/vm/modulefunc.go index 3e8c9c7f..d2eb2fb0 100644 --- a/internal/vm/modulefunc.go +++ b/internal/vm/modulefunc.go @@ -157,7 +157,7 @@ func (vm *VM) registerModuleExtras() { // NameError whose wording distinguishes a module from a class and names // the receiver by its #to_s (MRI). The default undefMethod message says // "class" for every receiver, so screen the miss here first. - if m := lookupMethod(mod, name); m == nil || m.undefined { + if !vm.resolvableForUndef(mod, name) { kind := "class" if mod.isModule { kind = "module" @@ -185,8 +185,13 @@ func (vm *VM) registerModuleExtras() { raise("NameError", "method '%s' not defined in %s", name, mod.ToS()) } delete(mod.methods, name) + bumpMethodSerial() + if mod.isSingleton { + // Removing a method from a singleton class (class << obj; remove_method :m) + // fires singleton_method_removed on the attached object. + vm.fireSingletonMethodHook(vm.attachedObject(mod), "singleton_method_removed", name) + } } - bumpMethodSerial() return mod }) @@ -331,3 +336,70 @@ func (vm *VM) fireMethodAdded(cls *RClass, name string) { vm.invoke(hook, cls, []object.Value{object.SymVal(name)}, nil) } } + +// attachedObject returns the object a singleton class belongs to — the class +// itself for a metaclass (def self.foo lands on its owner's class methods), and +// the recorded object for a per-object singleton class. It is the receiver of the +// singleton_method_added/removed/undefined hooks for defs made in that class. +func (vm *VM) attachedObject(sc *RClass) object.Value { + if sc.metaOf != nil { + return sc.metaOf + } + return sc.attached +} + +// fireMethodDefined runs the definition hook for a method just installed on cls: +// singleton_method_added on the attached object when cls is a singleton class +// (per-object singleton or a class metaclass), and method_added otherwise — the +// same split MRI makes. +func (vm *VM) fireMethodDefined(cls *RClass, name string) { + if cls.isSingleton { + vm.fireSingletonMethodHook(vm.attachedObject(cls), "singleton_method_added", name) + return + } + vm.fireMethodAdded(cls, name) +} + +// fireSingletonMethodHook invokes recv.(:name) — one of +// singleton_method_added / singleton_method_removed / singleton_method_undefined +// — when defining, removing, or undefining a singleton method of recv. MRI fires +// these on the object that owns the singleton method. The BasicObject default is +// a private no-op, so the hook is dispatched only when recv provides an override +// (owner is not BasicObject) or has had the hook undefined — in which case the +// send routes to method_missing, raising NoMethodError by default, exactly as MRI +// does for an undef'd hook. +func (vm *VM) fireSingletonMethodHook(recv object.Value, hook, name string) { + m := vm.resolveSingletonHook(recv, hook) + if m == nil || (!m.undefined && m.owner == vm.cBasicObject) { + // No hook resolves, or it is the BasicObject default no-op: nothing observable. + return + } + if m.undefined { + // The hook was undef'd on recv, so the call routes to method_missing — which + // raises NoMethodError by default. Invoke it directly (rather than through + // send) because an undef'd class method is found as a tombstone by + // lookupSMethod, which send would invoke instead of routing to method_missing. + mm := vm.resolveSingletonHook(recv, "method_missing") + vm.invoke(mm, recv, []object.Value{object.SymVal(hook), object.SymVal(name)}, nil) + return + } + vm.invoke(m, recv, []object.Value{object.SymVal(name)}, nil) +} + +// resolveSingletonHook finds the method recv would dispatch for a hook name, +// mirroring send's resolution order (a class receiver's singleton/class methods +// first, then a per-object singleton class, then the instance-method chain) but +// returning an undef'd tombstone rather than nil so callers can tell a removed +// hook apart from the BasicObject default. +func (vm *VM) resolveSingletonHook(recv object.Value, name string) *Method { + if cls, ok := recv.(*RClass); ok { + if m := lookupSMethod(cls, name); m != nil { + return m + } + } + c := vm.classOf(recv) + if sc := vm.objSingleton(recv); sc != nil { + c = sc + } + return lookupMethod(c, name) +} diff --git a/internal/vm/object_model.go b/internal/vm/object_model.go index ee7afa98..9165009a 100644 --- a/internal/vm/object_model.go +++ b/internal/vm/object_model.go @@ -214,6 +214,7 @@ type RClass struct { meta *RClass // lazily-created metaclass for `class << SomeClass`; its methods map IS this class's smethods metaOf *RClass // when this RClass is a metaclass, the class it is the metaclass of (else nil); routes `class << c` visibility directives to c's class methods isSingleton bool // true for a singleton class — a class metaclass or a per-object singleton (reported by Module#singleton_class?) + attached object.Value // for a per-object singleton class, the object it belongs to; drives the singleton_method_added/removed/undefined hooks. nil for a metaclass (use metaOf) and every non-singleton class. deprecatedConsts map[string]bool // constants marked by Module#deprecate_constant; access warns funcMode bool // module_function (no-arg) mode: subsequent instance defs are also copied as module/singleton methods // defaultVis is the access level applied to subsequent `def`s in this body, @@ -338,6 +339,7 @@ func (vm *VM) singletonClass(o *RObject) *RClass { if o.singleton == nil { o.singleton = newClass("", o.class) o.singleton.isSingleton = true + o.singleton.attached = o } return o.singleton } @@ -352,6 +354,7 @@ func (vm *VM) defineSingletonMethod(recv object.Value, name string, iseq *byteco if t, ok := recv.(*RClass); ok { t.smethods[name] = &Method{name: name, iseq: iseq, owner: t} bumpMethodSerial() + vm.fireSingletonMethodHook(recv, "singleton_method_added", name) return } // Any other object — an *RObject, the top-level main object, or a @@ -365,6 +368,7 @@ func (vm *VM) defineSingletonMethod(recv object.Value, name string, iseq *byteco } sc.methods[name] = &Method{name: name, iseq: iseq, owner: sc} bumpMethodSerial() // adding a singleton method can change what a cached send resolves to + vm.fireSingletonMethodHook(recv, "singleton_method_added", name) } // objSingleton returns the existing per-object singleton class for any value, or @@ -402,6 +406,7 @@ func (vm *VM) ensureSingleton(v object.Value) (*RClass, bool) { } sc := newClass("", vm.classOf(v)) sc.isSingleton = true + sc.attached = v vm.extSingletons[v] = sc return sc, true } @@ -673,22 +678,50 @@ func (vm *VM) aliasMethod(definee *RClass, newName, oldName string) { clone.undefined = false definee.methods[newName] = &clone bumpMethodSerial() + if definee.isSingleton { + // An alias made in a singleton class (class << obj; alias new old) adds a + // singleton method, so it fires singleton_method_added on the attached object. + vm.fireSingletonMethodHook(vm.attachedObject(definee), "singleton_method_added", newName) + } } // undefMethod implements `undef name` on definee: it installs a tombstone so the // name resolves to "undefined" — hiding any inherited definition and making a // call route to method_missing (NoMethodError). Undefining a name that resolves // nowhere raises NameError, as in MRI. +// resolvableForUndef reports whether name may be undefined on mod: either it is +// defined somewhere in mod's own+ancestor chain, or — for a singleton class whose +// superclass chain does not bridge to its attached object's full method +// resolution (a metaclass reaches Class's instance methods, and ultimately +// BasicObject's, only through the object, not through its super chain) — the name +// resolves on that attached object. This makes `class << self; undef_method +// :singleton_method_added` on a metaclass legal, as in MRI. +func (vm *VM) resolvableForUndef(mod *RClass, name string) bool { + if m := lookupMethod(mod, name); m != nil && !m.undefined { + return true + } + if !mod.isSingleton { + return false + } + att := vm.attachedObject(mod) + return att != nil && vm.findMethod(att, name) != nil +} + func (vm *VM) undefMethod(definee *RClass, name string) { // undef_method resolves only through the receiver's own+ancestor chain (no // Kernel→Object bridge): MRI raises for a method defined on Object when undef'd // via the Kernel module, and a subclass undef'ing an inherited Kernel method // (e.g. respond_to_missing?) resolves through normal ancestor lookup anyway. - if m := lookupMethod(definee, name); m == nil || m.undefined { + if !vm.resolvableForUndef(definee, name) { raise("NameError", "undefined method '%s' for class '%s'", name, definee.name) } definee.methods[name] = &Method{name: name, owner: definee, undefined: true} bumpMethodSerial() + if definee.isSingleton { + // Undefining a method in a singleton class (class << obj; undef_method :m) + // fires singleton_method_undefined on the attached object. + vm.fireSingletonMethodHook(vm.attachedObject(definee), "singleton_method_undefined", name) + } } func lookupOwnOrIncluded(c *RClass, name string) *Method { diff --git a/internal/vm/singleton.go b/internal/vm/singleton.go index a58d11d6..5078ed53 100644 --- a/internal/vm/singleton.go +++ b/internal/vm/singleton.go @@ -24,6 +24,7 @@ func (vm *VM) registerSingleton() { if t, ok := self.(*RClass); ok { t.smethods[name] = &Method{name: name, proc: body, owner: t} bumpMethodSerial() + vm.fireSingletonMethodHook(self, "singleton_method_added", name) return object.Symbol(name) } sc, ok := vm.ensureSingleton(self) @@ -32,6 +33,7 @@ func (vm *VM) registerSingleton() { } sc.methods[name] = &Method{name: name, proc: body, owner: sc} bumpMethodSerial() + vm.fireSingletonMethodHook(self, "singleton_method_added", name) return object.Symbol(name) }) diff --git a/internal/vm/vm.go b/internal/vm/vm.go index af2cc62a..db84fcf1 100644 --- a/internal/vm/vm.go +++ b/internal/vm/vm.go @@ -1742,11 +1742,10 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, definee.smethods[name] = &sm } bumpMethodSerial() // a (re)definition can change what a cached send resolves to - // Hook: definee.method_added(:name) for instance-method defs, if - // the class/module defines the hook (singleton method). - if hook := lookupSMethod(definee, "method_added"); hook != nil { - vm.invoke(hook, definee, []object.Value{object.SymVal(name)}, nil) - } + // Hook: definee.method_added(:name) for a def into a normal class, or + // (attached object).singleton_method_added(:name) for a def into a + // singleton class (class << obj; def m — and class << self; def m). + vm.fireMethodDefined(definee, name) // `def foo; end` evaluates to :foo (MRI), which is what makes // `private def foo; end` mark the just-defined method. push(object.SymVal(name)) From fe78aaf037d1db7cbb7330c4ae491908fade65cd Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 12:51:03 +0200 Subject: [PATCH 2/4] BasicObject: instance_eval/instance_exec block form binds def to the receiver MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The block form of instance_eval/instance_exec now runs with the receiver's singleton class as the method-definition target (a class/module's metaclass, else a per-object singleton class), so a `def` inside the block becomes a singleton method of the receiver instead of leaking onto the block's home namespace — and instance_eval yields the receiver to the block. A def inside the block fires singleton_method_added on the receiver, as MRI. The method-def redirect is threaded separately (pendingEvalMethodDefinee → methodDefinee) so it applies ONLY to def/alias/undef; the frame's definee stays the block's lexical scope, keeping constant lookup, `class`/`module` reopenings, and class-variable resolution lexical — matching MRI and, critically, the way the conformance harness itself runs example bodies via instance_eval. core/basicobject instance_eval 21→24, instance_exec 14→15. No regressions across core/{basicobject,kernel,proc,method,class,module} and language (base-vs-new sweep clean); full internal/vm suite green. Co-Authored-By: Claude Opus 4.8 --- internal/vm/basicobject_residuals_test.go | 46 ++++++++++++++++ internal/vm/builtins.go | 8 ++- internal/vm/object_model.go | 37 +++++++++++++ internal/vm/vm.go | 64 ++++++++++++++++------- 4 files changed, 134 insertions(+), 21 deletions(-) diff --git a/internal/vm/basicobject_residuals_test.go b/internal/vm/basicobject_residuals_test.go index 8d537b5d..5791c959 100644 --- a/internal/vm/basicobject_residuals_test.go +++ b/internal/vm/basicobject_residuals_test.go @@ -78,6 +78,52 @@ end`, "MA inst\n"}, } } +// TestInstanceEvalDefinee covers instance_eval / instance_exec running a block +// with self's singleton class as the method-def target while keeping the block's +// lexical scope for constants, class variables and class reopenings (MRI). +func TestInstanceEvalDefinee(t *testing.T) { + cases := []struct{ src, want string }{ + // The block is yielded self. + {`p "hola".instance_eval {|o| o }`, "\"hola\"\n"}, + // A def binds to the receiver only, not to every instance of its class. + {`o = Object.new +o.instance_eval { def foo; 1; end } +p o.foo +p Object.new.respond_to?(:foo)`, "1\nfalse\n"}, + // instance_eval on a class defines a class (singleton) method. + {`c = Class.new +c.instance_eval { def cm; 9; end } +p c.cm`, "9\n"}, + // A `class` reopening inside the block resolves lexically (top-level Bar), + // not under the receiver's singleton class. + {`class IEBar; end +ob = Object.new +ob.instance_eval { class IEBar; def z; 3; end; end } +p IEBar.new.z`, "3\n"}, + // A class variable inside the block resolves in the block's lexical class. + {`class IECVar + @@n = 41 + def blk; ->(*){ @@n } end +end +p Object.new.instance_eval(&IECVar.new.blk)`, "41\n"}, + // A read-only block runs on an immediate (which has no singleton class). + {`p 5.instance_eval { self }`, "5\n"}, + // instance_exec passes its arguments to the block and runs against self. + {`o = Object.new +o.instance_exec(7) {|x| @v = x } +p o.instance_variable_get(:@v)`, "7\n"}, + // A def inside instance_eval fires singleton_method_added on the receiver. + {`o = Object.new +def o.singleton_method_added(n); puts n; end +o.instance_eval { def m2; end }`, "singleton_method_added\nm2\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + // TestSingletonHookUndefRaises covers the undef'd-hook path with no user // method_missing: the definition routes to the default method_missing, which // raises NoMethodError naming the hook. diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index f59d62ad..6e1976fd 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -484,7 +484,9 @@ func (vm *VM) bootstrap() { if len(args) != 0 { raise("ArgumentError", "wrong number of arguments (given %d, expected 0)", len(args)) } - return vm.callBlockSelf(blk, self, nil) + // The block is yielded self (so `instance_eval {|o| ... }` sees the + // receiver) and runs with self's singleton class as the definee. + return vm.callBlockInstanceEval(blk, self, []object.Value{self}) } // String form: instance_eval("code" [, filename [, lineno]]) evaluates the // source with self as the receiver and its singleton class as the definee. @@ -502,7 +504,9 @@ func (vm *VM) bootstrap() { if blk == nil { raise("LocalJumpError", "no block given (yield)") } - return vm.callBlockSelf(blk, self, args) + // instance_exec runs the block with self as receiver and self's singleton + // class as the definee, passing along the caller's arguments as block args. + return vm.callBlockInstanceEval(blk, self, args) }) formatFn := func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { if len(args) == 0 { diff --git a/internal/vm/object_model.go b/internal/vm/object_model.go index 9165009a..d5428140 100644 --- a/internal/vm/object_model.go +++ b/internal/vm/object_model.go @@ -1964,6 +1964,43 @@ func (vm *VM) callBlockSelf(p *Proc, self object.Value, args []object.Value) obj return vm.exec(p.iseq, self, vm.bindBlockArgs(p, args), vm.blockDefinee(p), "", p.env, p.block, p, p.block, nil) } +// callBlockInstanceEval runs a block under instance_eval / instance_exec: like +// callBlockSelf, but the frame's definee is self's singleton class rather than +// the block's captured lexical scope, so a `def` inside the block becomes a +// singleton method of self (a class method for a class/module receiver) and does +// not leak onto the block's home namespace. Constant *lookup* still follows the +// block's textual nesting (exec derives lexCref from the block's cref), matching +// MRI. An immediate receiver has no singleton class, so its class stands in — a +// read-only block still runs. +func (vm *VM) callBlockInstanceEval(p *Proc, self object.Value, args []object.Value) object.Value { + if p.native != nil { + cp := make([]object.Value, len(args)) + copy(cp, args) + return p.native(vm, cp) + } + // The frame's definee stays the block's lexical scope (so constants, class + // variables and `class`/`module` reopenings resolve lexically); only a `def` + // is redirected, via pendingEvalMethodDefinee, to self's singleton class. It is + // set last — after arg binding — so exec is the very next frame to consume it. + boundArgs := vm.bindBlockArgs(p, args) + definee := vm.blockDefinee(p) + vm.pendingEvalMethodDefinee = vm.instanceEvalDefinee(self) + return vm.exec(p.iseq, self, boundArgs, definee, "", p.env, p.block, p, p.block, nil) +} + +// instanceEvalDefinee is the class a `def` inside self.instance_eval / instance_exec +// lands on: self's singleton class (a class/module's metaclass, else a per-object +// singleton class). An immediate receiver has none, so classOf stands in. +func (vm *VM) instanceEvalDefinee(self object.Value) *RClass { + if c, ok := self.(*RClass); ok { + return c.metaClass() + } + if sc, ok := vm.ensureSingleton(self); ok { + return sc + } + return vm.classOf(self) +} + // callProcWithBlock invokes a proc/lambda through Proc#call/[]/=== with the block // the caller passed to that call. That block (blk) binds the proc's own `&b` // block parameter, while a bare `yield` inside the proc still reaches the block diff --git a/internal/vm/vm.go b/internal/vm/vm.go index db84fcf1..26cb7c6c 100644 --- a/internal/vm/vm.go +++ b/internal/vm/vm.go @@ -523,6 +523,14 @@ type VM struct { // leaves the frame to derive its own pair. GVL-guarded. pendingMethodCtx *frameMethod + // pendingEvalMethodDefinee, when non-nil, is the class a `def` in the next exec + // frame lands on instead of the frame's definee — set by instance_eval / + // instance_exec to the receiver's singleton class, so a method defined in the + // block becomes a singleton method of the receiver while the block's constants + // and class variables still resolve against its lexical scope. Read and cleared + // at the top of exec, consumed synchronously before any nested call. GVL-guarded. + pendingEvalMethodDefinee *RClass + // children records finished synthetic child processes (Process.spawn / // Kernel.fork), so Process.waitpid2 can report each one's exit status. // childPidSeq assigns the next synthetic pid. GVL-guarded. @@ -1109,6 +1117,11 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, // other frame derives it from methodName (empty for class bodies / top level). pend := vm.pendingMethodCtx vm.pendingMethodCtx = nil + // Captured here, before arg/keyword binding can run user code and start a + // nested frame that would consume it: the instance_eval/exec method-def target + // (self's singleton class), applied to methodDefinee once the frame is set up. + pendEvalDef := vm.pendingEvalMethodDefinee + vm.pendingEvalMethodDefinee = nil var fm frameMethod switch { case selfBlock != nil: @@ -1356,6 +1369,17 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, // (a native, which pushes no frame of its own) can read the call site's cref. vm.frameCrefs[frameCrefsDepth-1] = lexCref + // methodDefinee is the class a `def` (and `alias`/`undef`) in this frame lands + // on. It is the definee, except under instance_eval/instance_exec, where the + // method-def target is switched to the receiver's singleton class while the + // frame's definee stays the block's lexical scope — so constants, class + // variables and `class`/`module` reopenings in the block keep resolving + // lexically (as MRI), and only method definition targets the singleton. + methodDefinee := definee + if pendEvalDef != nil { + methodDefinee = pendEvalDef + } + // Every frame catches a returnSignal aimed at its own selfTarget (a local // return/next routed through an ensure, or a non-local return whose home is // this frame). A signal for some other target passes through. On a catch the @@ -1699,24 +1723,26 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, push(vm.dispatchSend(recv, bname, callArgs, bblk)) case bytecode.OpDefineMethod: name := iseq.Names[in.A] - m := &Method{name: name, iseq: iseq.Children[in.B], owner: definee, vis: definee.defaultVis} - // Under class_eval/module_eval the def lands on the eval receiver - // (definee) while its bare-constant lookup must follow the block's - // textual nesting (lexCref) — record that scope when the two differ so - // the method body resolves constants as MRI does. - if lexCref != definee { + // methodDefinee is the definee, except under instance_eval/instance_exec + // where the def lands on the receiver's singleton class instead. + m := &Method{name: name, iseq: iseq.Children[in.B], owner: methodDefinee, vis: methodDefinee.defaultVis} + // Under class_eval/module_eval/instance_eval the def lands on the eval + // receiver (methodDefinee) while its bare-constant lookup must follow the + // block's textual nesting (lexCref) — record that scope when the two + // differ so the method body resolves constants as MRI does. + if lexCref != methodDefinee { m.lexScope = lexCref } // Attach the AOT-compiled body only on the first definition of // this name; a redefinition gets a fresh, interpreted Method // (deopt), since the compiled body matched the original source. - if _, redef := definee.methods[name]; !redef { - m.compiled = compiledFor(definee.name, name) + if _, redef := methodDefinee.methods[name]; !redef { + m.compiled = compiledFor(methodDefinee.name, name) } // A redefinition clears any stale per-receiver visibility override so // the new Method's own vis governs (MRI: redefining resets to the // current default visibility). - delete(definee.visOverrides, name) + delete(methodDefinee.visOverrides, name) // A `def` executed INSIDE a running method body is always public in // MRI, regardless of the class's persisted default visibility (which // only governs defs written directly in a class/module body). A block @@ -1727,7 +1753,7 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, switch { case selfBlock == nil && methodName != "": m.vis = visPublic - case definee.funcMode: + case methodDefinee.funcMode: m.vis = visPrivate } // A handful of core hook methods are always defined private, @@ -1735,17 +1761,17 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, if alwaysPrivateMethodName(name) { m.vis = visPrivate } - definee.methods[name] = m - if definee.funcMode { + methodDefinee.methods[name] = m + if methodDefinee.funcMode { sm := *m sm.vis = visPublic - definee.smethods[name] = &sm + methodDefinee.smethods[name] = &sm } bumpMethodSerial() // a (re)definition can change what a cached send resolves to - // Hook: definee.method_added(:name) for a def into a normal class, or - // (attached object).singleton_method_added(:name) for a def into a - // singleton class (class << obj; def m — and class << self; def m). - vm.fireMethodDefined(definee, name) + // Hook: methodDefinee.method_added(:name) for a def into a normal class, + // or (attached object).singleton_method_added(:name) for a def into a + // singleton class (class << obj; def m; instance_eval { def m }). + vm.fireMethodDefined(methodDefinee, name) // `def foo; end` evaluates to :foo (MRI), which is what makes // `private def foo; end` mark the just-defined method. push(object.SymVal(name)) @@ -1782,10 +1808,10 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, } push(vm.exec(iseq.Children[in.A], sc, nil, sc, "", nil, nil, nil, nil, nil)) case bytecode.OpAlias: - vm.aliasMethod(definee, iseq.Names[in.A], iseq.Names[in.B]) + vm.aliasMethod(methodDefinee, iseq.Names[in.A], iseq.Names[in.B]) push(object.NilV) case bytecode.OpUndef: - vm.undefMethod(definee, iseq.Names[in.A]) + vm.undefMethod(methodDefinee, iseq.Names[in.A]) push(object.NilV) case bytecode.OpDefineClass: // Bare `class B` nests into the current lexical scope (definee). From 30b01fef507eca377078bc97bd7c6b2417bd322e Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 12:59:42 +0200 Subject: [PATCH 3/4] BasicObject#method_missing: route blocked private/protected calls, reach class hook MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An explicit-receiver send to a private (or out-of-scope protected) method now reaches the receiver's #method_missing when it defines one, instead of raising outright — and when it does raise, the NoMethodError carries @receiver/@name/@args so NoMethodError#receiver reports the failed call (MRI). The visibility gate on the plain OpSend paths is replaced by enforceSendVisRoute/explicitBlockedRoute, which resolve the block kind without raising and either invoke a user #method_missing (with the name, args and block) or raise the stamped error; the splat/block-argument OpSend forms keep the raise-only gate (now also stamped). An undefined call on a class/module receiver now resolves #method_missing through the receiver's singleton (class) methods first, so `def self.method_missing` handles an unknown class method before the generic Class/BasicObject default. core/basicobject method_missing 21→30 (all green). No regressions across core/{kernel,basicobject,module,method,object,class,comparable,struct} or language (base-vs-new sweep clean); full internal/vm suite green. Co-Authored-By: Claude Opus 4.8 --- internal/vm/basicobject_residuals_test.go | 85 +++++++++++++++ internal/vm/object_model.go | 6 +- internal/vm/visibility.go | 126 +++++++++++++++++----- internal/vm/vm.go | 22 +++- 4 files changed, 205 insertions(+), 34 deletions(-) diff --git a/internal/vm/basicobject_residuals_test.go b/internal/vm/basicobject_residuals_test.go index 5791c959..4b803209 100644 --- a/internal/vm/basicobject_residuals_test.go +++ b/internal/vm/basicobject_residuals_test.go @@ -124,6 +124,91 @@ o.instance_eval { def m2; end }`, "singleton_method_added\nm2\n"}, } } +// TestMethodMissingVisibilityRouting covers a private/protected call reaching the +// receiver's #method_missing, an undefined class method reaching a singleton +// #method_missing, and — with no #method_missing — a NoMethodError whose +// receiver/name are stamped. All match MRI. +func TestMethodMissingVisibilityRouting(t *testing.T) { + cases := []struct{ src, want string }{ + // A blocked private call reaches #method_missing (with the name and args). + {`class MMC + def method_missing(*a) [:mm, *a] end + def priv; end + private :priv +end +p MMC.new.priv +p MMC.new.priv(1, 2)`, "[:mm, :priv]\n[:mm, :priv, 1, 2]\n"}, + // A blocked protected call (from outside) reaches #method_missing. + {`class MMP + def method_missing(*a) :mm end + def prot; end + protected :prot +end +p MMP.new.prot`, ":mm\n"}, + // A literal block flows through to #method_missing. + {`class MMB + def method_missing(*a, &b) b.call end + def priv; end + private :priv +end +p MMB.new.priv { 42 }`, "42\n"}, + // An undefined CLASS method reaches a singleton #method_missing. + {`class MMS + def self.method_missing(*a) [:smm, *a] end +end +p MMS.undefined_thing(3)`, "[:smm, :undefined_thing, 3]\n"}, + // A private CLASS method reaches a singleton #method_missing when blocked. + {`class MMPCM + def self.method_missing(*a) [:g, *a] end + def self.pcm; end + private_class_method :pcm +end +p MMPCM.pcm`, "[:g, :pcm]\n"}, + // A protected call between two kin instances is still allowed (not blocked). + {`class Kin + def initialize(v) @v = v end + def gt(o) val > o.val end + protected + def val; @v end +end +p Kin.new(5).gt(Kin.new(3))`, "true\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + +// TestBlockedCallNoMethodMissing covers the raise path: a private/protected call +// with no #method_missing raises NoMethodError stamped with receiver and name. +func TestBlockedCallNoMethodMissing(t *testing.T) { + got := eval(t, `class NoMM + def priv; end + private :priv +end +o = NoMM.new +begin + o.priv +rescue NoMethodError => e + p e.receiver.equal?(o) + p e.name +end`) + if got != "true\n:priv\n" { + t.Fatalf("got %q", got) + } + // The splat / block-argument send forms use the raise-only gate; a blocked + // private call there still raises NoMethodError. + err := runErr(t, `class NoMM2 + def priv; end + private :priv +end +NoMM2.new.priv(*[1])`) + if err == nil || !strings.Contains(err.Error(), "private method 'priv'") { + t.Fatalf("want private-method NoMethodError, got %v", err) + } +} + // TestSingletonHookUndefRaises covers the undef'd-hook path with no user // method_missing: the definition routes to the default method_missing, which // raises NoMethodError naming the hook. diff --git a/internal/vm/object_model.go b/internal/vm/object_model.go index d5428140..d29e08bf 100644 --- a/internal/vm/object_model.go +++ b/internal/vm/object_model.go @@ -1782,7 +1782,11 @@ func (vm *VM) send(recv object.Value, name string, args []object.Value, blk *Pro return vm.binaryOp(op, recv, args[0]) } } - mm := lookupMethod(c, "method_missing") + // Resolve method_missing the way a real send would: a class/module receiver + // consults its singleton (class) methods first, so `def self.method_missing` on + // the receiver — or on an ancestor's singleton — handles an unknown class method + // before falling back to the generic Class/BasicObject default. + mm := vm.resolveSingletonHook(recv, "method_missing") mmArgs := append([]object.Value{object.SymVal(name)}, args...) return vm.invoke(mm, recv, mmArgs, blk) } diff --git a/internal/vm/visibility.go b/internal/vm/visibility.go index 4871b892..ff7131fa 100644 --- a/internal/vm/visibility.go +++ b/internal/vm/visibility.go @@ -119,11 +119,33 @@ func (vm *VM) resolveClassMethod(cls *RClass, name string) *Method { return undefAsNil(lookupMethod(vm.cClass, name)) } -// enforceSendVis is the slow-path visibility gate used by the OpSend* handlers: -// when the send had an explicit (non-self) receiver, it resolves the target -// method and enforces its access level (raising NoMethodError for a private or -// out-of-scope protected call). An implicit / self send (flag clear) is a no-op. -// A name that resolves to no method (→ method_missing) is left to dispatch. +// enforceSendVisRoute is the slow-path visibility gate used by the OpSend* +// handlers for a send with an explicit (non-self) receiver. It resolves the +// target method and, when the call is a blocked private/protected access, either +// routes it to the receiver's #method_missing (if the receiver defines one) or +// raises the matching NoMethodError — returning (result, true) in that case so +// the caller uses it instead of dispatching. A public (or unresolved → +// method_missing) call, and any implicit/self send, returns (nil, false) so the +// caller dispatches normally. +func (vm *VM) enforceSendVisRoute(flags int, recv object.Value, name string, args []object.Value, blk *Proc, caller object.Value) (object.Value, bool) { + if flags&bytecode.FlagSendExplicit == 0 { + return nil, false + } + var m *Method + if cls, ok := recv.(*RClass); ok { + m = vm.resolveClassMethod(cls, name) + } else { + m = undefAsNil(lookupMethod(vm.dispatchClass(recv), name)) + } + return vm.explicitBlockedRoute(recv, name, m, args, blk, caller) +} + +// enforceSendVis is the raise-only visibility gate still used by the splat / +// block-argument OpSend* handlers (foo(*a), foo(&b), foo(*a, &b)). It resolves +// the target and raises the visibility NoMethodError for a blocked private or +// out-of-scope protected call (with #method_missing NOT intercepted here — the +// plain OpSend paths, which cover the method_missing protocol, use +// enforceSendVisRoute instead). An implicit/self send is a no-op. func (vm *VM) enforceSendVis(flags int, recv object.Value, name string, caller object.Value) { if flags&bytecode.FlagSendExplicit == 0 { return @@ -137,6 +159,75 @@ func (vm *VM) enforceSendVis(flags int, recv object.Value, name string, caller o vm.checkVisibility(recv, name, m, caller) } +// explicitBlockedRoute handles an explicit-receiver send whose target method m is +// already resolved: if the access is blocked (private, or protected called from +// outside), it routes to the receiver's user #method_missing or raises the +// visibility NoMethodError, returning (result, true). A public/allowed call +// returns (nil, false) so the caller invokes m directly. +func (vm *VM) explicitBlockedRoute(recv object.Value, name string, m *Method, args []object.Value, blk *Proc, caller object.Value) (object.Value, bool) { + kind := vm.visBlockedKind(recv, name, m, caller) + if kind != visPrivate && kind != visProtected { + return nil, false + } + // MRI: a private/protected call reaches #method_missing when the receiver + // defines one, rather than raising outright. + if mm := vm.userMethodMissing(recv); mm != nil { + mmArgs := append([]object.Value{object.SymVal(name)}, args...) + return vm.invoke(mm, recv, mmArgs, blk), true + } + vm.raiseVisibilityError(recv, name, kind, args) + return nil, true +} + +// userMethodMissing returns recv's #method_missing when it is a user override +// (not the BasicObject default and not undef'd), else nil — mirroring send's +// resolution order so a class/singleton method_missing is seen. +func (vm *VM) userMethodMissing(recv object.Value) *Method { + m := vm.resolveSingletonHook(recv, "method_missing") + if m == nil || m.undefined || m.owner == vm.cBasicObject { + return nil + } + return m +} + +// raiseVisibilityError raises the NoMethodError for a blocked private/protected +// call, stamping @name/@receiver/@args so NoMethodError#receiver (and #name/#args) +// report the failed call, as MRI. +func (vm *VM) raiseVisibilityError(recv object.Value, name string, kind visibility, args []object.Value) { + word := "private" + if kind == visProtected { + word = "protected" + } + var callArgs object.Value + if len(args) > 0 { + callArgs = object.NewArrayFromSlice(append([]object.Value(nil), args...)) + } + vm.raiseWithIvars("NoMethodError", + word+" method '"+name+"' called for "+vm.recvDesc(recv), + map[string]object.Value{"@name": object.SymVal(name), "@receiver": recv, "@args": callArgs}) +} + +// visBlockedKind reports the access level that blocks an explicit-receiver send: +// visPrivate or visProtected when the call is not permitted, else visPublic. It +// mirrors checkVisibility's receiver resolution without raising. +func (vm *VM) visBlockedKind(recv object.Value, name string, m *Method, caller object.Value) visibility { + if m == nil { + return visPublic // unresolved: dispatch routes it to method_missing + } + var vis visibility + if cls, ok := recv.(*RClass); ok && lookupSMethod(cls, name) == nil && m.owner != vm.cClass { + vis = instanceVisibility(vm.classOf(recv), name, m) + } else if cls, ok := recv.(*RClass); ok { + vis = classMethodVisibilityOf(cls, name, m) + } else { + vis = instanceVisibility(vm.dispatchClass(recv), name, m) + } + if vis == visProtected && caller != nil && classIsA(vm.classOf(caller), m.owner) { + return visPublic // the classic allowed protected call (caller is a kin instance) + } + return vis +} + // sendVisibilityOf reports the effective access level a `recv.name` send would // see for an already-resolved method m. It mirrors the receiver resolution in // checkVisibility: a class receiver dispatching a class method uses the class- @@ -157,29 +248,8 @@ func (vm *VM) sendVisibilityOf(recv object.Value, name string, m *Method) visibi // the calling frame (for the protected check). It is called only for explicit // receivers; implicit-receiver and self-receiver sends never reach here. func (vm *VM) checkVisibility(recv object.Value, name string, m *Method, caller object.Value) { - if m == nil { - return - } - var vis visibility - if cls, ok := recv.(*RClass); ok && lookupSMethod(cls, name) == nil && m.owner != vm.cClass { - // Not a class-method dispatch (the method came from the generic Class/Module - // instance methods, i.e. a normal instance-method visibility applies). - vis = instanceVisibility(vm.classOf(recv), name, m) - } else if cls, ok := recv.(*RClass); ok { - vis = classMethodVisibilityOf(cls, name, m) - } else { - vis = instanceVisibility(vm.dispatchClass(recv), name, m) - } - switch vis { - case visPrivate: - raise("NoMethodError", "private method '%s' called for %s", name, vm.recvDesc(recv)) - case visProtected: - // Allowed when the caller's self is an instance of the method's owner (or a - // descendant) — the classic protected use (a == comparing two instances). - if caller != nil && classIsA(vm.classOf(caller), m.owner) { - return - } - raise("NoMethodError", "protected method '%s' called for %s", name, vm.recvDesc(recv)) + if kind := vm.visBlockedKind(recv, name, m, caller); kind == visPrivate || kind == visProtected { + vm.raiseVisibilityError(recv, name, kind, nil) } } diff --git a/internal/vm/vm.go b/internal/vm/vm.go index 26cb7c6c..95e426b8 100644 --- a/internal/vm/vm.go +++ b/internal/vm/vm.go @@ -1657,9 +1657,15 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, if _, isClass := recv.(*RClass); !isClass { if m := vm.lookupCached(&caches[pc], recv, name); m != nil { // An explicit-receiver send enforces method visibility - // (private/protected); an implicit or `self.` send does not. + // (private/protected); an implicit or `self.` send does not. A + // blocked call routes to #method_missing (or raises). if in.Flags&bytecode.FlagSendExplicit != 0 { - vm.checkVisibility(recv, name, m, self) + if res, done := vm.explicitBlockedRoute(recv, name, m, stack[base:], nil, self); done { + stack = stack[:base-1] + stack = append(stack, res) + pc++ + continue + } } // Pass the args in place from the operand stack: invoke // (→ exec / a native method) consumes them before this frame @@ -1681,8 +1687,10 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, // passed directly here — no per-call args copy. The region is read // (and copied into the callee's env by exec, or defensively by // invokeInPlace) before this frame truncates the stack below. - vm.enforceSendVis(in.Flags, recv, name, self) - res := vm.send(recv, name, stack[base:], nil) + res, done := vm.enforceSendVisRoute(in.Flags, recv, name, stack[base:], nil, self) + if !done { + res = vm.send(recv, name, stack[base:], nil) + } stack = stack[:base-1] stack = append(stack, res) } else { @@ -1690,10 +1698,14 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, copy(callArgs, stack[len(stack)-argc:]) stack = stack[:len(stack)-argc] recv := pop() - vm.enforceSendVis(in.Flags, recv, name, self) // A literal block: capture this frame's env, self, block. markEnvCaptured(env) blk := &Proc{iseq: iseq.Children[in.C-1], env: env, defLocals: iseq.Locals, self: self, block: block, cref: lexCref, home: homeTarget(), superName: homeSuperName, superDefinee: homeSuperDefinee, superArgs: homeSuperArgs, dmBody: homeDmBody, methodCtx: fm} + if res, done := vm.enforceSendVisRoute(in.Flags, recv, name, callArgs, blk, self); done { + push(res) + pc++ + continue + } if vm.anyRefinements { if rm := vm.refinedMethod(definee, recv, name); rm != nil { push(vm.invokeInPlace(rm, recv, callArgs, blk)) From 4bbe5099e546896530ee4ca9519d6d5d4c14145f Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 13:10:57 +0200 Subject: [PATCH 4/4] BasicObject#initialize: reject arguments (MRI) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The default BasicObject#initialize takes no arguments, so BasicObject.new / Object.new with arguments — or a subclass that forwards them here via `super` — now raises ArgumentError, matching MRI. A zero-argument new is unaffected. core/basicobject initialize 1→2 (all green). No regressions across the full core/* conformance sweep; internal/vm suite green. Co-Authored-By: Claude Opus 4.8 --- internal/vm/basicobject_residuals_test.go | 46 +++++++++++++++++++++-- internal/vm/builtins.go | 8 +++- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/internal/vm/basicobject_residuals_test.go b/internal/vm/basicobject_residuals_test.go index 4b803209..09ec41cb 100644 --- a/internal/vm/basicobject_residuals_test.go +++ b/internal/vm/basicobject_residuals_test.go @@ -112,6 +112,8 @@ p Object.new.instance_eval(&IECVar.new.blk)`, "41\n"}, {`o = Object.new o.instance_exec(7) {|x| @v = x } p o.instance_variable_get(:@v)`, "7\n"}, + // A native block (Symbol#to_proc) is yielded self and runs against it. + {`p "abc".instance_eval(&:upcase)`, "\"ABC\"\n"}, // A def inside instance_eval fires singleton_method_added on the receiver. {`o = Object.new def o.singleton_method_added(n); puts n; end @@ -197,16 +199,33 @@ end`) if got != "true\n:priv\n" { t.Fatalf("got %q", got) } + // A blocked protected call with no #method_missing raises the protected-method + // NoMethodError (the visProtected raise branch). + if err := runErr(t, `class ProtNoMM + def prot; end + protected :prot +end +ProtNoMM.new.prot`); err == nil || !strings.Contains(err.Error(), "protected method 'prot'") { + t.Fatalf("want protected-method NoMethodError, got %v", err) + } // The splat / block-argument send forms use the raise-only gate; a blocked - // private call there still raises NoMethodError. - err := runErr(t, `class NoMM2 + // private call there still raises NoMethodError — for an object receiver + // (dispatchClass branch)... + if err := runErr(t, `class NoMM2 def priv; end private :priv end -NoMM2.new.priv(*[1])`) - if err == nil || !strings.Contains(err.Error(), "private method 'priv'") { +NoMM2.new.priv(*[1])`); err == nil || !strings.Contains(err.Error(), "private method 'priv'") { t.Fatalf("want private-method NoMethodError, got %v", err) } + // ...and for a class receiver's private class method (resolveClassMethod branch). + if err := runErr(t, `class NoMM3 + def self.pcm; end + private_class_method :pcm +end +NoMM3.pcm(*[])`); err == nil || !strings.Contains(err.Error(), "private method 'pcm'") { + t.Fatalf("want private class-method NoMethodError, got %v", err) + } } // TestSingletonHookUndefRaises covers the undef'd-hook path with no user @@ -246,6 +265,25 @@ func TestUndefMissingMethodStillRaises(t *testing.T) { } } +// TestDefaultInitializeRejectsArgs covers BasicObject#initialize taking no +// arguments: new with arguments (and a subclass forwarding them via super) is an +// ArgumentError, while a zero-arg new still works. +func TestDefaultInitializeRejectsArgs(t *testing.T) { + if got := eval(t, `p Object.new.class`); got != "Object\n" { + t.Fatalf("zero-arg new broke: %q", got) + } + for _, src := range []string{ + `BasicObject.new(1)`, + `Object.new(1, 2)`, + `class SuperFwd; def initialize(x); super; end; end +SuperFwd.new(1)`, + } { + if err := runErr(t, src); err == nil || !strings.Contains(err.Error(), "ArgumentError") { + t.Errorf("src=%q want ArgumentError, got %v", src, err) + } + } +} + // TestClonePreservesSingletonHooks checks that a cloned object's copied singleton // class still fires the hook for methods added to the clone (its attached object // is the clone, not the source). diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 6e1976fd..59f8e2e9 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -919,7 +919,13 @@ func (vm *VM) bootstrap() { // class descending directly from BasicObject — which does not inherit Object — // still allocates (new → initialize) and reports NoMethodError through // method_missing rather than dereferencing a nil method record. - vm.cBasicObject.define("initialize", func(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { + vm.cBasicObject.define("initialize", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + // The default initialize takes no arguments (MRI): BasicObject.new / Object.new + // with arguments, or a subclass that forwards them here via `super`, is an + // ArgumentError. + if len(args) != 0 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 0)", len(args)) + } return object.NilV }) // ! and != are BasicObject instance methods (dispatchable via send, and