From a0a2a418a352a9c8a8e7dbde282cda7ef6b62523 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Wed, 26 Aug 2026 23:42:13 +0200 Subject: [PATCH] Module: module_exec, singleton_class?, public_instance_method, set_temporary_name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add four missing Module reflection methods: - module_exec is Module#class_exec (the block runs with the module as self and receives the given arguments). - singleton_class? reports whether the receiver is a singleton class — a per-object singleton or a class metaclass — tracked by a new isSingleton flag set wherever a singleton class is created. - public_instance_method returns an UnboundMethod like #instance_method, but raises NameError when the resolved method is private or protected. - set_temporary_name gives an anonymous module a non-permanent name (or clears it with nil), rejecting a permanently-named module, an empty name, and any name that reads as a constant or constant path, exactly as MRI does. Verified against ruby 4.0.6. Whole-package coverage stays at 100%; the ruby/spec floor rises 15770 -> 15790 (language+core +21). Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 8 +++- internal/vm/object_model.go | 14 ++++--- internal/vm/reflection.go | 53 ++++++++++++++++++++++++++ internal/vm/reflection_methods_test.go | 41 +++++++++++++++++++- scripts/conformance/rubyspec/FLOOR | 2 +- 5 files changed, 109 insertions(+), 9 deletions(-) diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index f127d80f..19310cc1 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -1316,12 +1316,16 @@ func (vm *VM) bootstrap() { } vm.cModule.define("class_eval", classEvalFn) vm.cModule.define("module_eval", classEvalFn) - vm.cModule.define("class_exec", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { + classExec := func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { if blk == nil { raise("LocalJumpError", "no block given (yield)") } return vm.classEval(self.(*RClass), blk, args) - }) + } + vm.cModule.define("class_exec", classExec) + // Module#module_exec is Module#class_exec (the block runs with the module as + // self and receives the given arguments). + vm.cModule.define("module_exec", classExec) vm.cModule.define("define_method", func(_ *VM, self object.Value, args []object.Value, blk *Proc) object.Value { cls := self.(*RClass) name := nameArg(args[0]) diff --git a/internal/vm/object_model.go b/internal/vm/object_model.go index aeef50d2..69f99f63 100644 --- a/internal/vm/object_model.go +++ b/internal/vm/object_model.go @@ -209,11 +209,12 @@ type RClass struct { // named reports whether this class/module has acquired a permanent name yet. // An anonymous class (Class.new / Module.new) starts unnamed; the first time // it is assigned to a constant it takes that constant's qualified name. - named bool - isModule bool - 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 - funcMode bool // module_function (no-arg) mode: subsequent instance defs are also copied as module/singleton methods + named bool + isModule bool + 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?) + 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, // set by a bare `private` / `protected` / `public` with no args. It resets to // visPublic at the start of each class/module body (a fresh RClass starts at @@ -335,6 +336,7 @@ type RObject struct { func (vm *VM) singletonClass(o *RObject) *RClass { if o.singleton == nil { o.singleton = newClass("", o.class) + o.singleton.isSingleton = true } return o.singleton } @@ -398,6 +400,7 @@ func (vm *VM) ensureSingleton(v object.Value) (*RClass, bool) { return sc, true } sc := newClass("", vm.classOf(v)) + sc.isSingleton = true vm.extSingletons[v] = sc return sc, true } @@ -422,6 +425,7 @@ func (c *RClass) metaClass() *RClass { mc := newClass("#", nil) mc.methods = c.smethods // alias: defs here become class methods of c mc.metaOf = c // back-pointer: lets `private :foo` in `class << c` reach c's class methods + mc.isSingleton = true // The metaclass superclass is the superclass's metaclass, so a class-method // `super` (def self.foo / class << self) walks to the inherited class method: // # -> # -> ... This mirrors MRI's metaclass chain. diff --git a/internal/vm/reflection.go b/internal/vm/reflection.go index f40670a1..6a8001f5 100644 --- a/internal/vm/reflection.go +++ b/internal/vm/reflection.go @@ -2,6 +2,7 @@ package vm import ( "reflect" + "strings" "github.com/go-embedded-ruby/ruby/internal/object" ) @@ -42,6 +43,58 @@ func (vm *VM) registerReflection() { return &UnboundMethod{name: name, owner: m.owner, m: m, vm: vm} }) + // Module#public_instance_method(:m): like #instance_method, but the resolved + // method must be public — a private or protected one raises NameError. + vm.cModule.define("public_instance_method", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + mod := self.(*RClass) + name := nameArg(args[0]) + m := vm.lookupForModuleOp(mod, name) + if m == nil || m.undefined { + raise("NameError", "undefined method '%s' for class '%s'", name, mod.name) + } + if vis := instanceVisibility(mod, name, m); vis != visPublic { + kind := "private" + if vis == visProtected { + kind = "protected" + } + raise("NameError", "method '%s' for class '%s' is %s", name, mod.name, kind) + } + return &UnboundMethod{name: name, owner: m.owner, m: m, vm: vm} + }) + + // Module#singleton_class?: true when the receiver is a singleton class — a + // per-object singleton or a class metaclass — false for an ordinary class or + // module. + vm.cModule.define("singleton_class?", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + return object.Bool(self.(*RClass).isSingleton) + }) + + // Module#set_temporary_name(name) gives an anonymous module a temporary name + // (or clears it with nil) without making it permanent, so a later constant + // assignment can still name it. A permanently-named module, a constant path, + // or an empty string is rejected the way MRI does. + vm.cModule.define("set_temporary_name", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + mod := self.(*RClass) + if mod.named { + raise("RuntimeError", "can't change permanent name") + } + if object.IsNil(args[0]) { + mod.name = "" + return mod + } + name := strArg(args[0]) + switch { + case name == "": + raise("ArgumentError", "empty class/module name") + case strings.Contains(name, "::") || constNameWellFormed(name): + // A name that reads as a constant (or a constant path) is rejected, so a + // temporary name is never mistaken for a real, permanently-assigned one. + raise("ArgumentError", "the temporary name must not be a constant path to avoid confusion") + } + mod.name = name + return mod + }) + // Module#method_defined?(:m): true if m resolves up the ancestor chain. vm.cModule.define("method_defined?", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { mod := self.(*RClass) diff --git a/internal/vm/reflection_methods_test.go b/internal/vm/reflection_methods_test.go index 0b6d0f5a..9bf61e20 100644 --- a/internal/vm/reflection_methods_test.go +++ b/internal/vm/reflection_methods_test.go @@ -1,6 +1,9 @@ package vm_test -import "testing" +import ( + "strings" + "testing" +) // TestInstanceMethodsAndSymbolCompare covers Module#instance_methods, // Object#methods, and Symbol#<=> / Symbol being Comparable. Asserted against MRI @@ -31,3 +34,39 @@ p [A.instance_methods(false).sort, A.instance_methods.include?(:mm)]`, "[[:foo], } } } + +// TestModuleReflectionC37 covers Module#module_exec, #singleton_class?, +// #public_instance_method and #set_temporary_name, asserted against MRI 4.0.6. +func TestModuleReflectionC37(t *testing.T) { + cases := []struct{ src, want string }{ + // module_exec runs the block with the module as self, passing arguments. + {`class C1; end; C1.module_exec(7) { |x| define_method(:v) { x } }; p C1.new.v`, "7\n"}, + // singleton_class?: a per-object singleton and a class metaclass are + // singletons; an ordinary class or module is not. + {`p [Integer.singleton_class?, Integer.singleton_class.singleton_class?, Object.new.singleton_class.singleton_class?, Module.new.singleton_class?]`, "[false, true, true, false]\n"}, + // public_instance_method returns an UnboundMethod for a public method. + {`class C2; def foo; 1; end; end; m = C2.public_instance_method(:foo); p [m.class, m.bind(C2.new).call]`, "[UnboundMethod, 1]\n"}, + // set_temporary_name assigns and clears a non-permanent name. + {`m = Module.new; m.set_temporary_name("handy"); n1 = m.name; m.set_temporary_name(nil); p [n1, m.name]`, "[\"handy\", 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 }{ + {`class C3; private def foo; end; end; C3.public_instance_method(:foo)`, "is private"}, + {`class C3b; protected def bar; end; end; C3b.public_instance_method(:bar)`, "is protected"}, + {`class C3c; end; C3c.public_instance_method(:nope)`, "undefined method 'nope'"}, + {`Object.set_temporary_name("x")`, "can't change permanent name"}, + {`Module.new.set_temporary_name("Foo::Bar")`, "must not be a constant path"}, + {`Module.new.set_temporary_name("Const")`, "must not be a constant path"}, + {`Module.new.set_temporary_name("")`, "empty class/module name"}, + } + 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) + } + } +} diff --git a/scripts/conformance/rubyspec/FLOOR b/scripts/conformance/rubyspec/FLOOR index c70c60d5..064f584f 100644 --- a/scripts/conformance/rubyspec/FLOOR +++ b/scripts/conformance/rubyspec/FLOOR @@ -1 +1 @@ -15770 +15790