From d8d4392b47c5ab8f2529623573baa85ec59f6081 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sat, 5 Sep 2026 21:22:16 +0200 Subject: [PATCH 1/3] Method/UnboundMethod: super_method through aliases, metaclass inspect heads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit super_method now follows a method's ORIGINAL name, so an alias (alias_method :meow, :derp) or a visibility-changed inherited method reaches the same super MRI's `super` would — fixing the "undefined method 'owner' for nil" crashes when the alias name has no ancestor. UnboundMethod now records the class it was extracted from (origin) and walks that class's full ancestor list, so a `super` that crosses between two modules mixed into one class is found. Method#inspect / UnboundMethod#inspect now render the receiver/owner head as MRI does: a class method reads Recv.name / Child(Parent).name; a module method reaching a class object shows through its metaclass as #(Owner)#name; an anonymous class instance uses the # separator; and an UnboundMethod's head is the defining module/singleton class inspected. core/method: super_method 5->6, to_s 10->15, unbind 6->7. core/unboundmethod: super_method 4->6. Co-Authored-By: Claude Opus 4.8 --- internal/vm/method_reflect2.go | 77 +++++++-- internal/vm/method_residuals_wave12_test.go | 180 ++++++++++++++++++++ internal/vm/reflection.go | 21 ++- 3 files changed, 260 insertions(+), 18 deletions(-) create mode 100644 internal/vm/method_residuals_wave12_test.go diff --git a/internal/vm/method_reflect2.go b/internal/vm/method_reflect2.go index b8841fdd..66d4a12c 100644 --- a/internal/vm/method_reflect2.go +++ b/internal/vm/method_reflect2.go @@ -53,10 +53,14 @@ func (vm *VM) registerMethodReflect2() { return object.Symbol(methodOriginalName(self.(*UnboundMethod).m)) }) - // #super_method. + // #super_method. The super search follows the method's ORIGINAL name — an + // alias (alias_method :meow, :derp) reaches super along the definition it + // copied, not its alias name — so `super` from an aliased or a + // visibility-changed inherited method finds the same ancestor MRI's `super` + // would (see methodOriginalName). vm.cMethod.define("super_method", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { b := self.(*BoundMethod) - sm := vm.superMethodAfter(vm.dispatchAncestors(b.recv), b.m.owner, b.name) + sm := vm.superMethodAfter(vm.dispatchAncestors(b.recv), b.m.owner, methodOriginalName(b.m)) if sm == nil { return object.NilV } @@ -64,11 +68,16 @@ func (vm *VM) registerMethodReflect2() { }) cUnbound.define("super_method", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { u := self.(*UnboundMethod) - sm := vm.superMethodAfter(vm.ancestors(u.owner), u.owner, u.name) + // Walk the ancestors of the class the UnboundMethod was extracted from + // (u.origin), not those of its defining module: a module owner's own + // ancestor list stops at the module, so a `super` that must cross into + // another module included in the same class (module B's derp calling into + // module A's derp, both included in class C) would otherwise be lost. + sm := vm.superMethodAfter(vm.ancestors(u.origin), u.owner, methodOriginalName(u.m)) if sm == nil { return object.NilV } - return &UnboundMethod{name: u.name, owner: sm.owner, m: sm, vm: vm} + return &UnboundMethod{name: u.name, owner: sm.owner, m: sm, vm: vm, origin: u.origin} }) // #to_s and its alias #inspect (a shared record, so @@ -289,15 +298,9 @@ func localName(is *bytecode.ISeq, slot int) string { // "(orig)" annotation appears only when the lookup name differs from the original // name, and the location suffix only when the source file is known. func (vm *VM) formatCallableString(kind string, recv object.Value, name string, m *Method) string { - head, sep := m.owner.name, "#" + head, sep := m.owner.ToS(), "#" // UnboundMethod: the defining class/module, inspected if kind == "Method" { - if m.owner.name == "" { - head, sep = vm.send(recv, "inspect", nil, nil).ToS(), "." - } else if recvClass := vm.classOf(recv); recvClass == m.owner { - head = recvClass.name - } else { - head = recvClass.name + "(" + m.owner.name + ")" - } + head, sep = vm.methodHead(recv, name, m) } disp := name if orig := methodOriginalName(m); orig != name { @@ -310,6 +313,56 @@ func (vm *VM) formatCallableString(kind string, recv object.Value, name string, return s + ">" } +// methodHead renders the "receiver#owner" (or "receiver.owner") portion of a +// bound Method's # form, and the separator (# or .) that follows it, +// matching MRI. A class/module receiver is shown through its metaclass: +// - a genuine class method (def self.m — reached through the singleton-method +// table) reads as `Recv.m`, with `(Owner)` when inherited: `Child(Parent).m`; +// - any other method reaching the class object (an included/extended module +// method such as Module#include, a Kernel method) reads as +// `#(Owner)#m`. +// +// An ordinary object shows its class, with `(Owner)` when the method is defined +// in an ancestor; a per-object singleton method (def obj.m) shows the receiver's +// own inspect with a `.` separator. +func (vm *VM) methodHead(recv object.Value, name string, m *Method) (head, sep string) { + owner := m.owner + if cls, ok := recv.(*RClass); ok { + if sm := lookupOwnClassMethod(cls, name); sm == m { + head = cls.ToS() + if owner != cls { + head += "(" + owner.ToS() + ")" + } + return head, "." + } + return "#(" + owner.ToS() + ")", "#" + } + if owner.isSingleton && owner.metaOf == nil { + // A per-object singleton method (def obj.m): head is the receiver's inspect. + return vm.send(recv, "inspect", nil, nil).ToS(), "." + } + recvClass := vm.classOf(recv) + if recvClass == owner { + return recvClass.ToS(), "#" + } + return recvClass.ToS() + "(" + owner.ToS() + ")", "#" +} + +// lookupOwnClassMethod resolves name among the genuine class (singleton) methods +// defined with `def self.name` — the smethods tables walked up the super chain — +// but NOT modules mixed into a metaclass via extend. It distinguishes, for +// # rendering, a real class method (shown as `Recv.name`) from a +// module method that merely reaches the class object (shown through its +// metaclass as `#(Owner)#name`). +func lookupOwnClassMethod(c *RClass, name string) *Method { + for ; c != nil; c = c.super { + if m, ok := c.smethods[name]; ok { + return m + } + } + return nil +} + // formatParamList renders a method's parameters as MRI's # signature // fragment, e.g. "(a, b=..., *c, d, e:, f: ..., **g, &blk)". A native method, // whose parameters are unknown, renders as "(*)". diff --git a/internal/vm/method_residuals_wave12_test.go b/internal/vm/method_residuals_wave12_test.go new file mode 100644 index 00000000..1085ed4f --- /dev/null +++ b/internal/vm/method_residuals_wave12_test.go @@ -0,0 +1,180 @@ +package vm_test + +import ( + "strings" + "testing" +) + +// TestMethodInspectHeads covers the receiver/owner head rendering of +// Method#inspect (vm.methodHead) across MRI's cases: a genuine class method +// (Recv.name / Child(Parent).name), a module method reaching a class object via +// its metaclass (#(Owner)#name), an ordinary instance method +// (Recv#name and Recv(Owner)#name), an anonymous class instance, and a +// per-object singleton method. +func TestMethodInspectHeads(t *testing.T) { + tests := []struct { + name, src, want string + }{ + { + "def_self_class_method", + `class WHClsP; def self.cm; end; end +puts WHClsP.method(:cm).inspect.start_with?("#(Module)#include")`, + "true\n", + }, + { + "extended_module_method_on_class_via_metaclass", + `m = Module.new { def whbar; end } +c = Class.new +c.extend(m) +s = c.method(:whbar).inspect +puts s.start_with?("#(#{m.inspect})#whbar")`, + "true\n", + }, + { + "ordinary_instance_method_same_class", + `class WHOrd; def foo; end; end +puts WHOrd.new.method(:foo).inspect.start_with?("#.foo")`, + "true\ntrue\n", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestUnboundMethodInspectHead covers UnboundMethod#inspect head rendering: a +// named module owner inspects to its name, a per-object singleton owner inspects +// to its # form. +func TestUnboundMethodInspectHead(t *testing.T) { + tests := []struct { + name, src, want string + }{ + { + "named_module_owner", + `module WHUMod; def bar; end; end +class WHUInc; include WHUMod; end +puts WHUInc.instance_method(:bar).inspect.start_with?("# form). vm *VM @@ -40,7 +47,7 @@ func (vm *VM) registerReflection() { if m == nil || m.undefined { raise("NameError", "undefined method '%s' for class '%s'", name, mod.name) } - return &UnboundMethod{name: name, owner: m.owner, m: m, vm: vm} + return &UnboundMethod{name: name, owner: m.owner, m: m, vm: vm, origin: mod} }) // Module#public_instance_method(:m): like #instance_method, but the resolved @@ -59,7 +66,7 @@ func (vm *VM) registerReflection() { } raise("NameError", "method '%s' for class '%s' is %s", name, mod.name, kind) } - return &UnboundMethod{name: name, owner: m.owner, m: m, vm: vm} + return &UnboundMethod{name: name, owner: m.owner, m: m, vm: vm, origin: mod} }) // Module#singleton_class?: true when the receiver is a singleton class — a @@ -168,10 +175,12 @@ func (vm *VM) registerReflection() { return sc }) - // Method#unbind → UnboundMethod. - vm.cMethod.define("unbind", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + // Method#unbind → UnboundMethod. The extraction origin is the class the bound + // method dispatched on (its singleton class when it has one), so a later + // #super_method walks the same ancestor chain the original send would. + vm.cMethod.define("unbind", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { b := self.(*BoundMethod) - return &UnboundMethod{name: b.name, owner: b.m.owner, m: b.m, vm: vm} + return &UnboundMethod{name: b.name, owner: b.m.owner, m: b.m, vm: vm, origin: vm.dispatchClass(b.recv)} }) } From 5f3af2203cdee073e81de97733233620729560fa Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sat, 5 Sep 2026 21:29:24 +0200 Subject: [PATCH 2/3] Method/UnboundMethod: instance variables, freeze, and dup/clone copy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BoundMethod and UnboundMethod now carry an embedded methodValueState holding instance variables (with insertion order) and a frozen flag, reached through the boxed interface by the shared ivar/freeze/copy helpers exactly as RObject exposes its own ivars. #instance_variable_set/get/#instance_variables work, #freeze/#frozen? work, #dup copies ivars and resets frozen, and #clone copies ivars and preserves frozen — matching MRI 3.4+. core/method: clone 1->3, dup 1->3. core/unboundmethod: clone 1->3, dup 1->3. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 17 +++++ internal/vm/method.go | 1 + internal/vm/method_residuals_wave12_test.go | 83 +++++++++++++++++++++ internal/vm/object_model.go | 26 ++++++- internal/vm/reflection.go | 34 +++++++++ 5 files changed, 159 insertions(+), 2 deletions(-) diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 513f5de6..3dc2f66b 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -301,6 +301,11 @@ func (vm *VM) bootstrap() { } case *RClass: o.frozen = true + default: + // Bound/UnboundMethod (and any future boxed value) freeze via state. + if b, ok := self.(boxed); ok { + b.state().frozen = true + } } return self }) @@ -9250,6 +9255,14 @@ func dupValue(v object.Value) object.Value { copy(dup.structVals, x.structVals) } return dup + case *BoundMethod: + cp := *x + cp.methodValueState = copyMethodState(x.methodValueState) + return &cp + case *UnboundMethod: + cp := *x + cp.methodValueState = copyMethodState(x.methodValueState) + return &cp default: return v } @@ -9277,6 +9290,10 @@ func isFrozen(v object.Value) bool { case *RClass: return x.frozen } + // Bound/UnboundMethod track their frozen flag in the embedded state. + if b, ok := v.(boxed); ok { + return b.state().frozen + } return false } diff --git a/internal/vm/method.go b/internal/vm/method.go index 189c0a3c..4935e3b5 100644 --- a/internal/vm/method.go +++ b/internal/vm/method.go @@ -14,6 +14,7 @@ type BoundMethod struct { // vm is the interpreter the method belongs to, kept so ToS can render the // receiver's class and the method's parameters (MRI's # form). vm *VM + methodValueState } // newBoundMethod builds a Method bound to recv, resolved under name to m. diff --git a/internal/vm/method_residuals_wave12_test.go b/internal/vm/method_residuals_wave12_test.go index 1085ed4f..8ec652a6 100644 --- a/internal/vm/method_residuals_wave12_test.go +++ b/internal/vm/method_residuals_wave12_test.go @@ -160,6 +160,89 @@ func TestSuperMethodFollowsOriginalName(t *testing.T) { } } +// TestMethodValueStateCopyAndFreeze covers instance variables, freeze/frozen? +// and #dup/#clone copy semantics for BoundMethod and UnboundMethod: #dup and +// #clone copy instance variables, #dup resets the frozen flag while #clone +// preserves it, and setting an ivar on a frozen method raises FrozenError. +func TestMethodValueStateCopyAndFreeze(t *testing.T) { + tests := []struct { + name, src, want string + }{ + { + "bound_ivars_set_and_read", + `m = Object.new.method(:method) +m.instance_variable_set(:@a, 1) +m.instance_variable_set(:@b, 2) +puts m.instance_variables.inspect +puts m.instance_variable_get(:@a)`, + "[:@a, :@b]\n1\n", + }, + { + "unbound_ivars_set_and_read", + `u = Object.instance_method(:method) +u.instance_variable_set(:@x, 9) +puts u.instance_variables.inspect +puts u.instance_variable_get(:@x)`, + "[:@x]\n9\n", + }, + { + "bound_dup_copies_ivars_resets_frozen", + `m = Object.new.method(:method) +m.instance_variable_set(:@ivar, 1) +m.freeze +d = m.dup +puts d.instance_variables.inspect +puts d.frozen?`, + "[:@ivar]\nfalse\n", + }, + { + "bound_clone_preserves_frozen", + `m = Object.new.method(:method) +m.freeze +puts m.frozen? +puts m.clone.frozen?`, + "true\ntrue\n", + }, + { + "unbound_clone_preserves_frozen", + `u = Object.instance_method(:method) +u.freeze +puts u.frozen? +puts u.clone.frozen? +puts u.dup.frozen?`, + "true\ntrue\nfalse\n", + }, + { + "dup_without_ivars_is_distinct", + `m = Object.new.method(:method) +d = m.dup +puts m.equal?(d) +puts m == d +puts d.instance_variables.inspect`, + "false\ntrue\n[]\n", + }, + { + "set_ivar_on_frozen_method_raises", + `m = Object.new.method(:method) +m.freeze +begin + m.instance_variable_set(:@z, 1) + puts "no-raise" +rescue FrozenError + puts "frozen" +end`, + "frozen\n", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + // TestSuperMethodPlainInheritance keeps the ordinary class-inheritance chain // working (no alias, no module owners): super_method walks class supers. func TestSuperMethodPlainInheritance(t *testing.T) { diff --git a/internal/vm/object_model.go b/internal/vm/object_model.go index 82b15523..9032beff 100644 --- a/internal/vm/object_model.go +++ b/internal/vm/object_model.go @@ -2206,9 +2206,13 @@ func getIvar(self object.Value, name string) object.Value { func setIvar(self object.Value, name string, v object.Value) { if t := ivarTable(self); t != nil { - if o, ok := self.(*RObject); ok { - if _, exists := t[name]; !exists { + if _, exists := t[name]; !exists { + switch o := self.(type) { + case *RObject: o.ivarOrder = append(o.ivarOrder, name) + case boxed: + st := o.state() + st.ivarOrder = append(st.ivarOrder, name) } } t[name] = v @@ -2229,6 +2233,16 @@ func ivarNamesInOrder(self object.Value) []object.Value { } return out } + if b, ok := self.(boxed); ok { + st := b.state() + out := make([]object.Value, 0, len(st.ivarOrder)) + for _, n := range st.ivarOrder { + if _, live := st.ivars[n]; live { + out = append(out, object.Symbol(n)) + } + } + return out + } t := ivarTable(self) out := make([]object.Value, 0, len(t)) for n := range t { @@ -2258,5 +2272,13 @@ func ivarTable(self object.Value) map[string]object.Value { } return o.ivars } + // Bound/UnboundMethod carry their ivars in an embedded methodValueState. + if b, ok := self.(boxed); ok { + st := b.state() + if st.ivars == nil { + st.ivars = map[string]object.Value{} + } + return st.ivars + } return nil } diff --git a/internal/vm/reflection.go b/internal/vm/reflection.go index b4c89d32..c4f592e7 100644 --- a/internal/vm/reflection.go +++ b/internal/vm/reflection.go @@ -7,6 +7,39 @@ import ( "github.com/go-embedded-ruby/ruby/internal/object" ) +// methodValueState holds the mutable Ruby-object state a BoundMethod or +// UnboundMethod carries beyond its immutable definition: instance variables +// (with insertion order, so #instance_variables matches MRI) and a frozen flag. +// It is embedded in both so the shared ivar / freeze / copy helpers can reach it +// through the boxed interface, exactly as RObject exposes its own ivars. +type methodValueState struct { + ivars map[string]object.Value + ivarOrder []string + frozen bool +} + +func (s *methodValueState) state() *methodValueState { return s } + +// boxed is implemented by the reflection value types (Bound/UnboundMethod) that, +// unlike the generic RObject, are Go structs yet still carry instance variables +// and a frozen flag (in an embedded methodValueState). +type boxed interface{ state() *methodValueState } + +// copyMethodState deep-copies instance variables for #dup/#clone and resets the +// frozen flag (a plain #dup is never frozen; Object#clone re-freezes afterwards +// when the original was frozen). +func copyMethodState(s methodValueState) methodValueState { + out := methodValueState{} + if s.ivars != nil { + out.ivars = make(map[string]object.Value, len(s.ivars)) + for k, v := range s.ivars { + out.ivars[k] = v + } + out.ivarOrder = append([]string(nil), s.ivarOrder...) + } + return out +} + // UnboundMethod is a method detached from any receiver, produced by // Module#instance_method or Method#unbind. It is re-bound to a compatible // receiver with #bind / #bind_call. @@ -24,6 +57,7 @@ type UnboundMethod struct { // vm is the interpreter the method belongs to, kept so ToS can render the // method's parameters (MRI's # form). vm *VM + methodValueState } func (u *UnboundMethod) ToS() string { From edf9a658b0444f3b7b434d9ba9eb8b998577bb6c Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sat, 5 Sep 2026 21:40:13 +0200 Subject: [PATCH 3/3] Cover bound super_method nil chain and freeze/frozen? fall-through Adds Go tests exercising Method#super_method returning nil at the top of a chain and the freeze/frozen? default fall-through for a non-boxed value, so every added branch is covered. Co-Authored-By: Claude Opus 4.8 --- internal/vm/method_residuals_wave12_test.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/internal/vm/method_residuals_wave12_test.go b/internal/vm/method_residuals_wave12_test.go index 8ec652a6..a8e7b1c3 100644 --- a/internal/vm/method_residuals_wave12_test.go +++ b/internal/vm/method_residuals_wave12_test.go @@ -146,10 +146,15 @@ func TestSuperMethodFollowsOriginalName(t *testing.T) { "WHA\n", }, { - "super_method_nil_at_top_returns_nil", + "unbound_super_method_nil_at_top_returns_nil", inheritedModulesSrc + `puts WHC.instance_method(:derp).super_method.super_method.inspect`, "nil\n", }, + { + "bound_super_method_nil_at_top_returns_nil", + inheritedModulesSrc + `puts WHC.new.method(:derp).super_method.super_method.inspect`, + "nil\n", + }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -221,6 +226,16 @@ puts m == d puts d.instance_variables.inspect`, "false\ntrue\n[]\n", }, + { + // A non-boxed, non-listed value (a Proc) still travels the freeze/frozen? + // default fall-through without being affected, so the added branches stay + // scoped to Bound/UnboundMethod. + "proc_freeze_is_untracked_fall_through", + `p = proc { 1 } +p.freeze +puts p.frozen?`, + "false\n", + }, { "set_ivar_on_frozen_method_raises", `m = Object.new.method(:method)