From ddddb1d64e2cffb26323fd803d8925264e96b45b Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 8 Sep 2026 12:26:03 +0200 Subject: [PATCH] module: extend_object, const_source_location, const_added/const_set warn, cvar ancestry, Module.constants, def hooks, .new block arg (core/module +19) Advance MRI-4.0.x conformance of Module/Class (core/module). Each change is byte-for-byte checked against local MRI 4.0.5 and cited to ruby/ruby v3_4_0. - Module#extend_object: the private primitive Object#extend dispatches to. Mixes self into the object's singleton class (methods + constants); TypeError when self is a Class (rb_include_module), FrozenError for a frozen object; undefined on Class. Ref object.c rb_mod_extend_object / rb_extend_object. - Module#const_source_location: rbgo tracks no per-constant source position, so it returns nil for a resolvable name (as MRI does for an absent one) while honouring the full NameError/TypeError name-validation contract. Ref variable.c rb_const_source_location. (+6, errors 35->1) - Module#const_set: fire const_added on every set (ref variable.c rb_const_set) and warn "already initialized constant" on redefining a real value, gated by $VERBOSE non-nil (rb_warn semantics; a pending autoload does not warn). - class_variable_get/_set/_defined? and #class_variables now search the whole ancestry (included modules), not only the superclass chain; _set writes through to the owning module. Ref variable.c rb_cvar_get / rb_cvar_set. - Module.constants (singleton): no-arg returns every top-level constant (equal to Object.constants); with an argument behaves like Module#constants. Ref variable.c rb_mod_s_constants. - Module#remove_const made private (rb_define_private_method). - remove_method / undef_method fire method_removed / method_undefined on an ordinary class (singleton classes keep routing to the singleton hooks). - Module.new / Class.new yield the new module/class to their block. Ref object.c rb_mod_initialize / rb_class_initialize -> rb_mod_module_exec(module,1,&module). Whitebox tests in module_wave20_test.go cover every new branch. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 160 +++++++++++++++++-- internal/vm/module_residuals.go | 21 +++ internal/vm/module_wave20_test.go | 257 ++++++++++++++++++++++++++++++ internal/vm/modulefunc.go | 21 ++- 4 files changed, 445 insertions(+), 14 deletions(-) create mode 100644 internal/vm/module_wave20_test.go diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 2849998b..d0387f41 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -1422,6 +1422,39 @@ func (vm *VM) bootstrap() { vm.mixinModule(mod, target, true) return mod }) + // Module#extend_object(obj) (private): the primitive Object#extend dispatches + // to. It mixes self (the module) into obj's singleton class, so the module's + // instance methods AND constants become available on obj — Object#extend then + // fires the module's #extended hook. self being a Class rather than a plain + // Module is a TypeError ("wrong argument type Class (expected Module)"), which + // rb_include_module raises for a Class operand; since extend_object is undefined + // on Class this only bites a rebind onto a Class receiver. A frozen obj raises + // FrozenError before any change. Returns obj. Reference: ruby/ruby v3_4_0 + // object.c rb_mod_extend_object / rb_extend_object → rb_include_module. + vm.cModule.define("extend_object", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + mod := self.(*RClass) + if !mod.isModule { + raise("TypeError", "wrong argument type Class (expected Module)") + } + obj := args[0] + if isFrozen(obj) { + vm.raiseFrozen(obj) + } + if t, ok := obj.(*RClass); ok { + // Extending a class/module object mixes mod into its metaclass, so mod's + // instance methods become class methods (the same insertion `extend` makes). + mc := t.metaClass() + mc.includes = append(mc.includes, mod) + } else { + // Every value ensureSingleton cannot give a singleton class (an immediate: + // Integer, Symbol, Float, true/false/nil) is frozen, so the frozen check + // above already rejected it — a non-frozen obj here always gets a singleton. + sc, _ := vm.ensureSingleton(obj) + sc.includes = append(sc.includes, mod) + } + bumpMethodSerial() + return obj + }) // The default no-op mix-in / definition hooks MRI defines as private instance // methods of Module (each rb_obj_dummy1, returning nil): a user overrides them // with `def self.included(base)` etc. Reference: ruby/ruby v3_4_0 object.c @@ -1435,15 +1468,15 @@ func (vm *VM) bootstrap() { // PRIVATE instance methods of Module in MRI (object.c, eval.c): reachable as a // functional call or through the include/prepend/def machinery, but not as // `mod.append_features(x)` with an explicit receiver. - for _, n := range []string{"append_features", "prepend_features", "included", "extended", "prepended", "method_added", "method_removed", "method_undefined", "const_added"} { + for _, n := range []string{"append_features", "prepend_features", "extend_object", "included", "extended", "prepended", "method_added", "method_removed", "method_undefined", "const_added"} { vm.cModule.methods[n].vis = visPrivate } - // MRI undefines append_features / prepend_features on Class + // MRI undefines append_features / prepend_features / extend_object on Class // (rb_undef_method(rb_cClass, …)), so Class.private_instance_methods omits // them and a rebind onto a Class receiver has no method to reach. An undefined // tombstone halts ancestor lookup, hiding the inherited Module definition from // method listing without removing it for module receivers. - for _, n := range []string{"append_features", "prepend_features"} { + for _, n := range []string{"append_features", "prepend_features", "extend_object"} { vm.cClass.methods[n] = &Method{name: n, owner: vm.cClass, undefined: true} } vm.cModule.define("ancestors", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { @@ -1503,7 +1536,7 @@ func (vm *VM) bootstrap() { // superclass chain via cvarOwner, mirroring how @@name resolves at runtime. vm.cModule.define("class_variable_get", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { name := vm.coerceCvarName(args[0]) - if c := cvarOwner(self.(*RClass), name); c != nil { + if c := vm.cvarOwnerAnc(self.(*RClass), name); c != nil { return c.cvars[name] } raise("NameError", "uninitialized class variable %s in %s", name, self.(*RClass).name) @@ -1515,7 +1548,7 @@ func (vm *VM) bootstrap() { vm.raiseFrozen(cls) } name := vm.coerceCvarName(args[0]) - if c := cvarOwner(cls, name); c != nil { + if c := vm.cvarOwnerAnc(cls, name); c != nil { c.cvars[name] = args[1] } else { cls.cvars[name] = args[1] @@ -1523,7 +1556,7 @@ func (vm *VM) bootstrap() { return args[1] }) vm.cModule.define("class_variable_defined?", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - return object.Bool(cvarOwner(self.(*RClass), vm.coerceCvarName(args[0])) != nil) + return object.Bool(vm.cvarOwnerAnc(self.(*RClass), vm.coerceCvarName(args[0])) != nil) }) vm.cModule.define("class_variables", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { // class_variables(inherit=true): own variables, then ancestors', each @@ -1531,7 +1564,16 @@ func (vm *VM) bootstrap() { inherit := len(args) == 0 || args[0].Truthy() seen := map[string]bool{} var names []string - for c := self.(*RClass); c != nil; c = c.super { + // class_variables shares across the whole ancestry (included modules and the + // superclass chain), not just the superclass chain: a variable defined in an + // included module is listed too. inherit=false stops at the receiver's own + // table. Reference: ruby/ruby v3_4_0 variable.c rb_mod_class_variables + // (mod_cvar_of walks the ancestor list). + levels := []*RClass{self.(*RClass)} + if inherit { + levels = vm.ancestors(self.(*RClass)) + } + for _, c := range levels { level := make([]string, 0, len(c.cvars)) for name := range c.cvars { if !seen[name] { @@ -1543,9 +1585,6 @@ func (vm *VM) bootstrap() { // is deterministic (windows-latest runs the same test). sort.Strings(level) names = append(names, level...) - if !inherit { - break - } } out := make([]object.Value, len(names)) for i, n := range names { @@ -1559,12 +1598,25 @@ func (vm *VM) bootstrap() { vm.raiseFrozen(cls) } name := vm.coerceConstName(args[0]) + // Overwriting an already-initialised constant (a real value, not a pending + // autoload — those live in cls.autoloads, so cls.consts misses them and no + // warning fires) warns "already initialized constant X". MRI uses rb_warn + // here, which fires whenever $VERBOSE is non-nil (false or true), suppressed + // only when $VERBOSE is nil. Reference: ruby/ruby v3_4_0 variable.c + // rb_const_set → const_set_raise / rb_warn on the already-set case. + if _, existed := cls.consts[name]; existed && !object.IsNil(vm.globals["$VERBOSE"]) { + vm.warnRedefineConst(cls, name) + } // Route through assignConstIn so an anonymous class/module bound here gains // the qualified name of its constant (Ruby's "permanent name on first // constant binding" rule) — the same path a `Foo::Bar = ...` literal takes. // Top-level (Object) constants live in the flat namespace that a bare // constant reference reads, which assignConstIn handles for Object. vm.assignConstIn(cls, name, args[1]) + // Module#const_added(name) fires on every const_set (MRI's rb_const_set calls + // const_added unconditionally). The default is a private no-op; a user + // `def self.const_added` override observes the new constant. + vm.fireConstAdded(cls, name) return args[1] }) // Module#remove_const deletes a constant defined directly on the receiver and @@ -1632,6 +1684,32 @@ func (vm *VM) bootstrap() { } return object.NewArrayFromSlice(out) }) + // Module.constants (the SINGLETON method, distinct from Module#constants) has + // two forms in MRI (rb_mod_s_constants): with no argument it returns the + // constants accessible in the caller's scope — at the top level, every + // top-level constant, equal to Object.constants; with an argument it behaves + // like Module#constants on the receiver (Module's own + inherited). It shadows + // the instance method only for the Module class and its subclasses (a plain + // class's `.constants` still finds the instance method through the Class chain). + // Reference: ruby/ruby v3_4_0 variable.c rb_mod_s_constants. + instConstants := vm.cModule.methods["constants"] + vm.cModule.smethods["constants"] = &Method{name: "constants", owner: vm.cModule, + native: func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { + if len(args) > 0 { + return vm.invoke(instConstants, self, args, blk) + } + names := vm.topLevelConstNames() + out := make([]object.Value, len(names)) + for i, n := range names { + out[i] = object.Symbol(n) + } + return object.NewArrayFromSlice(out) + }} + // Module#remove_const is a PRIVATE instance method in MRI + // (rb_define_private_method(rb_cModule, "remove_const", …)), reachable as a + // functional call inside a class/module body but not through an explicit + // receiver — so a spec must `send(:remove_const, …)` to reach it. + vm.cModule.methods["remove_const"].vis = visPrivate // Module#< <= > >= compare by the inheritance/inclusion hierarchy: A < B is // true if A is a proper descendant of B, false if a proper ancestor (or, for // <=/>=, equal), and nil when the two are unrelated. @@ -5966,7 +6044,11 @@ func (vm *VM) bootstrap() { c := newClass("", super) vm.registerLiveClass(c) if blk != nil { - vm.classEval(c, blk, nil) + // The block runs as the class body (self = c) AND receives c as its + // block argument, so `Class.new { |cls| … }` can name the new class — + // MRI yields the class to the block. Reference: ruby/ruby v3_4_0 + // object.c rb_class_initialize → rb_mod_module_exec(module, 1, &module). + vm.classEval(c, blk, []object.Value{c}) } return c }} @@ -5983,7 +6065,11 @@ func (vm *VM) bootstrap() { m.defaultVis, m.funcMode = visPublic, false vm.registerLiveClass(m) if blk != nil { - vm.classEval(m, blk, nil) + // The block runs as the module body (self = m) AND receives m as its + // block argument, so `Module.new { |mod| … }` can name the new module — + // MRI yields the module to the block. Reference: ruby/ruby v3_4_0 + // object.c rb_mod_initialize → rb_mod_module_exec(module, 1, &module). + vm.classEval(m, blk, []object.Value{m}) } return m }} @@ -9129,6 +9215,56 @@ func (vm *VM) mixinModule(mod, target *RClass, prepend bool) { bumpMethodSerial() } +// cvarOwnerAnc returns the nearest class/module in c's ANCESTOR chain — its own +// table, its included/prepended modules, then the superclass chain and their +// modules — that already defines the class variable name, or nil if none does. +// MRI shares class variables across the whole ancestry, so +// Module#class_variable_get / _set / _defined? see (and, for _set, write through +// to) a variable defined in an included module, not only one in a superclass. +// Reference: ruby/ruby v3_4_0 variable.c rb_cvar_get / rb_cvar_set (cvar_front_klass +// walks RCLASS_SUPER, which threads the included modules into the ancestor chain). +func (vm *VM) cvarOwnerAnc(c *RClass, name string) *RClass { + for _, anc := range vm.ancestors(c) { + if _, ok := anc.cvars[name]; ok { + return anc + } + } + return nil +} + +// fireConstAdded invokes cls.const_added(:name) when cls defines that hook as a +// class/singleton method (def self.const_added), mirroring fireMethodAdded. The +// default Module#const_added is a private no-op, so only a user override is +// observable — MRI dispatches const_added on every rb_const_set. Reference: +// ruby/ruby v3_4_0 variable.c const_set → rb_const_added / object.c const_added. +func (vm *VM) fireConstAdded(cls *RClass, name string) { + if hook := lookupSMethod(cls, "const_added"); hook != nil { + vm.invoke(hook, cls, []object.Value{object.SymVal(name)}, nil) + } +} + +// topLevelConstNames returns the sorted, de-duplicated names of every top-level +// constant, which back the no-argument form of Module.constants (equal to +// Object.constants in MRI). Top-level constants live in two tables in rbgo: the +// core classes/modules registered in vm.consts and the user-defined ones written +// to cObject.consts, so the union of the two is enumerated. Only well-formed +// constant names are reported, filtering any internal bookkeeping key. +func (vm *VM) topLevelConstNames() []string { + set := map[string]bool{} + for name := range vm.consts { + set[name] = true + } + for name := range vm.cObject.consts { + set[name] = true + } + names := make([]string, 0, len(set)) + for name := range set { + names = append(names, name) + } + sort.Strings(names) + return names +} + func constNameArg(v object.Value) string { var name string switch n := v.(type) { diff --git a/internal/vm/module_residuals.go b/internal/vm/module_residuals.go index 6913cc32..f7a93028 100644 --- a/internal/vm/module_residuals.go +++ b/internal/vm/module_residuals.go @@ -44,6 +44,27 @@ func (vm *VM) registerModuleResiduals() { return object.Bool(vm.moduleConstDefined(self.(*RClass), args[0], inherit)) }) + // Module#const_source_location(name, inherit=true): in MRI this returns the + // [file, line] where the constant was defined, [] for a constant defined in C, + // or nil when the name resolves to no constant in the search path. rbgo does + // not record where each constant was defined, so a locatable constant cannot + // report its position — we return nil (the same value MRI gives an absent + // constant) after performing MRI's full name validation, so the NameError / + // TypeError contract (a lowercase or malformed name, a Symbol carrying a scope + // path, an empty path segment, or a #to_str that fails/returns non-String) is + // honoured exactly even though the location itself is unavailable. inherit is + // accepted for signature compatibility. Reference: ruby/ruby v3_4_0 variable.c + // rb_const_source_location / rb_const_source_location_at. + vm.cModule.define("const_source_location", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + segs, _, orig := vm.constPathSegs(args[0]) + for _, seg := range segs { + if !constNameWellFormed(seg) { + raise("NameError", "wrong constant name %s", orig) + } + } + return object.NilV + }) + // Module#const_missing(sym): the default hook, raising a NameError naming the // missing constant. The toplevel (Object) form omits the "Object::" qualifier, // matching MRI. The NameError carries the name so NameError#name returns it. diff --git a/internal/vm/module_wave20_test.go b/internal/vm/module_wave20_test.go new file mode 100644 index 00000000..2f7d55c4 --- /dev/null +++ b/internal/vm/module_wave20_test.go @@ -0,0 +1,257 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "strings" + "testing" +) + +// TestModuleWave20ClassVariables covers the class-variable reflection methods +// searching the whole ancestor chain (an included module, not only the +// superclass chain) — Module#class_variable_get / _set / _defined? and +// #class_variables. Asserted against MRI 4.0. +func TestModuleWave20ClassVariables(t *testing.T) { + cases := []struct{ src, want string }{ + // class_variable_get sees a variable defined in an INCLUDED module. + {`module MV; @@mv = :mv; end +c = Class.new { include MV } +p c.class_variable_get(:@@mv)`, ":mv\n"}, + // class_variable_defined? sees an included module's variable. + {`module MV2; @@mv = 1; end +c = Class.new { include MV2 } +p c.class_variable_defined?(:@@mv)`, "true\n"}, + // class_variable_set writes THROUGH to the module that owns the variable. + {`module MV3; @@mv = 1; end +c = Class.new { include MV3 } +c.class_variable_set(:@@mv, 99) +p MV3.class_variable_get(:@@mv)`, "99\n"}, + // class_variable_set with no owner in the chain writes on the receiver. + {`c = Class.new +c.class_variable_set(:@@fresh, 7) +p c.class_variable_get(:@@fresh)`, "7\n"}, + // class_variables (inherit, the default) lists an included module's variable; + // class_variables(false) is own-only. + {`module MV4; @@mv = 1; end +c = Class.new { include MV4 } +p [c.class_variables, c.class_variables(false)]`, "[[:@@mv], []]\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) + } + } + // A class variable defined nowhere in the ancestry is a NameError. + if err := runErr(t, `Class.new.class_variable_get(:@@nope)`); err == nil || + !strings.Contains(err.Error(), "NameError") { + t.Errorf("missing cvar: got %v, want NameError", err) + } +} + +// TestModuleWave20ExtendObject covers Module#extend_object: it is a private +// instance method that mixes the module into an object's singleton class +// (methods and constants), is undefined on Class, raises TypeError when rebound +// onto a Class receiver, and raises FrozenError for a frozen object. Asserted +// against MRI 4.0. +func TestModuleWave20ExtendObject(t *testing.T) { + cases := []struct{ src, want string }{ + // extend_object mixes the module's methods AND constants onto an object. + {`module EM; C = :test; def hi; "hello"; end; end +o = Object.new +EM.send(:extend_object, o) +p [o.hi, o.singleton_class.const_get(:C)]`, `["hello", :test]` + "\n"}, + // It is a private instance method of Module, undefined on Class. + {`p [Module.private_instance_methods(false).include?(:extend_object), + Class.private_instance_methods(true).include?(:extend_object)]`, "[true, false]\n"}, + // Extending a class/module object mixes into its singleton (class methods). + {`module EM2; def cm; :cm; end; end +c = Class.new +EM2.send(:extend_object, c) +p c.cm`, ":cm\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) + } + } + errs := []struct{ src, want string }{ + // Rebinding onto a Class receiver raises TypeError (Class is not a Module). + {`Module.instance_method(:extend_object).bind(Class.new).call(Object.new)`, "TypeError"}, + // A frozen object raises FrozenError (a RuntimeError) before extending. + {`Module.new.send(:extend_object, Object.new.freeze)`, "FrozenError"}, + } + for _, c := range errs { + if err := runErr(t, c.src); err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("src=%q err=%v, want substring %q", c.src, err, c.want) + } + } +} + +// TestModuleWave20ConstSet covers Module#const_set firing const_added and +// warning on the redefinition of an already-initialised constant (gated by +// $VERBOSE), plus Module#remove_const being a private method. Asserted against +// MRI 4.0. +func TestModuleWave20ConstSet(t *testing.T) { + cases := []struct{ src, want string }{ + // const_set fires the const_added hook with the new name. + {`m = Module.new do + def self.const_added(n); ($ca ||= []) << n; end +end +m.const_set(:Foo, 1) +p $ca`, "[:Foo]\n"}, + // A fresh const_set on a module with no const_added override is a no-op hook. + {`m = Module.new +m.const_set(:Foo, 1) +p m.const_get(:Foo)`, "1\n"}, + // Redefining an initialised constant warns under $VERBOSE. + {`require "stringio" +c = Class.new +c.const_set(:X, 1) +$VERBOSE = true +o = $stderr; $stderr = StringIO.new +c.const_set(:X, 2) +w = $stderr.string; $stderr = o +p [c.const_get(:X), w.include?("already initialized constant")]`, "[2, true]\n"}, + // The same redefinition does NOT warn when $VERBOSE is nil. + {`require "stringio" +c = Class.new +c.const_set(:X, 1) +$VERBOSE = nil +o = $stderr; $stderr = StringIO.new +c.const_set(:X, 2) +w = $stderr.string; $stderr = o +p w.empty?`, "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) + } + } + // remove_const is private: an explicit receiver raises NoMethodError, while + // #send reaches it. + if err := runErr(t, `class C; X = 1; end; C.remove_const(:X)`); err == nil || + !strings.Contains(err.Error(), "NoMethodError") { + t.Errorf("remove_const explicit: got %v, want NoMethodError", err) + } + if got := eval(t, `class C; X = 1; end; p C.send(:remove_const, :X)`); got != "1\n" { + t.Errorf("remove_const send: got %q, want %q", got, "1\n") + } +} + +// TestModuleWave20Constants covers the Module.constants SINGLETON method: with +// no argument it returns every top-level constant (equal to Object.constants), +// with an argument it behaves like Module#constants on the receiver. Asserted +// against MRI 4.0. +func TestModuleWave20Constants(t *testing.T) { + cases := []struct{ src, want string }{ + // No argument: a superset of the core class names, and +1 when a top-level + // module is added. + {`p [Module.constants.include?(:Array), Module.constants.include?(:String)]`, "[true, true]\n"}, + {`c = Module.constants.size +module TopLevelAdded20; end +r = Module.constants.size == c + 1 +Object.send(:remove_const, :TopLevelAdded20) +p r`, "true\n"}, + // With an argument it is Module#constants on Module itself (own + inherited), + // so a freshly added Module constant shows up under the false form. + {`before = Module.constants(false) +class Module; MODULE_C20 = :x; end +r = (Module.constants(false) - before) == [:MODULE_C20] +Module.send(:remove_const, :MODULE_C20) +p r`, "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) + } + } +} + +// TestModuleWave20ConstSourceLocation covers Module#const_source_location: rbgo +// does not track constant source positions, so it returns nil for a resolvable +// name, but still enforces MRI's name validation (NameError for a malformed name +// or a Symbol carrying a scope path; TypeError for a failed #to_str). Asserted +// against MRI 4.0. +func TestModuleWave20ConstSourceLocation(t *testing.T) { + cases := []struct{ src, want string }{ + // A well-formed name (resolvable or not) yields nil (no location tracked). + {`class C20; K = 1; end; p C20.const_source_location(:K)`, "nil\n"}, + {`p Object.const_source_location(:CS_ABSENT_20)`, "nil\n"}, + // A String or Symbol both accepted; a valid scoped path is well-formed. + {`p Module.const_source_location("Object")`, "nil\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) + } + } + errs := []struct{ src, want string }{ + // A name not starting with a capital letter is a NameError. + {`Module.const_source_location("name")`, "NameError"}, + // A malformed segment (trailing '=') is a NameError. + {`Module.const_source_location("K=")`, "NameError"}, + // A Symbol carrying a scope path is a NameError. + {`Module.const_source_location(:"A::B")`, "NameError"}, + // An empty path segment ("::") is a NameError. + {`Module.const_source_location("::")`, "NameError"}, + // A non-String, non-Symbol without #to_str is a TypeError. + {`Module.const_source_location(123)`, "TypeError"}, + } + for _, c := range errs { + if err := runErr(t, c.src); err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("src=%q err=%v, want substring %q", c.src, err, c.want) + } + } +} + +// TestModuleWave20DefinitionHooks covers Module#method_removed / #method_undefined +// firing on an ordinary class, and the singleton-class variants routing to the +// singleton hooks instead. Also covers Module.new / Class.new yielding the new +// module/class to their block. Asserted against MRI 4.0. +func TestModuleWave20DefinitionHooks(t *testing.T) { + cases := []struct{ src, want string }{ + // remove_method fires method_removed on an ordinary class. + {`c = Class.new do + def self.method_removed(n); ($mr ||= []) << n; end + def foo; end +end +c.send(:remove_method, :foo) +p $mr`, "[:foo]\n"}, + // undef_method fires method_undefined on an ordinary class. + {`c = Class.new do + def self.method_undefined(n); ($mu ||= []) << n; end + def bar; end +end +c.send(:undef_method, :bar) +p $mu`, "[:bar]\n"}, + // On a singleton class, remove/undef route to the singleton hooks, NOT the + // module method_removed/method_undefined — so the module counters stay unset. + {`$smr = nil +o = Object.new +def o.singleton_method_removed(n); $smr = n; end +def o.gone; end +class << o; remove_method :gone; end +p $smr`, ":gone\n"}, + {`$smu = nil +o = Object.new +def o.singleton_method_undefined(n); $smu = n; end +def o.gone; end +class << o; undef_method :gone; end +p $smu`, ":gone\n"}, + // Module.new yields the new module to its block. + {`m = Module.new { |mod| $mod = mod } +p m.equal?($mod)`, "true\n"}, + // Class.new yields the new class to its block (and to its superclass form). + {`c = Class.new { |cls| $cls = cls } +p c.equal?($cls)`, "true\n"}, + {`c = Class.new(String) { |cls| $cls2 = cls } +p [c.equal?($cls2), c.superclass]`, "[true, String]\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) + } + } +} diff --git a/internal/vm/modulefunc.go b/internal/vm/modulefunc.go index fa154eeb..ace9951b 100644 --- a/internal/vm/modulefunc.go +++ b/internal/vm/modulefunc.go @@ -180,6 +180,11 @@ func (vm *VM) registerModuleExtras() { raise("NameError", "undefined method '%s' for %s '%s'", name, kind, recv) } vm.undefMethod(mod, name) + // undefMethod fires singleton_method_undefined for a singleton class; for + // an ordinary class/module the corresponding hook is Module#method_undefined. + if !mod.isSingleton { + vm.fireModuleMethodHook(mod, "method_undefined", name) + } } return mod }) @@ -205,6 +210,9 @@ func (vm *VM) registerModuleExtras() { // 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) + } else { + // An ordinary class/module fires Module#method_removed instead. + vm.fireModuleMethodHook(mod, "method_removed", name) } } return mod @@ -427,8 +435,17 @@ func (vm *VM) checkTransplantBindable(cls, owner *RClass) { // fireMethodAdded invokes cls.method_added(:name) when cls defines that hook as a // singleton method, mirroring the OpDefineMethod path for `def`. func (vm *VM) fireMethodAdded(cls *RClass, name string) { - if hook := lookupSMethod(cls, "method_added"); hook != nil { - vm.invoke(hook, cls, []object.Value{object.SymVal(name)}, nil) + vm.fireModuleMethodHook(cls, "method_added", name) +} + +// fireModuleMethodHook invokes cls.(:name) when cls defines the hook as a +// class/singleton method (e.g. def self.method_removed) — the definition-tracking +// hooks method_added / method_removed / method_undefined. The default is a private +// no-op, so only a user override is observable. Reference: ruby/ruby v3_4_0 +// vm_method.c rb_add_method / remove_method / undef_method calling the hooks. +func (vm *VM) fireModuleMethodHook(cls *RClass, hook, name string) { + if h := lookupSMethod(cls, hook); h != nil { + vm.invoke(h, cls, []object.Value{object.SymVal(name)}, nil) } }