Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
14 changes: 9 additions & 5 deletions internal/vm/object_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand All @@ -422,6 +425,7 @@ func (c *RClass) metaClass() *RClass {
mc := newClass("#<Class:"+c.name+">", 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:
// #<Class:Child> -> #<Class:Base> -> ... This mirrors MRI's metaclass chain.
Expand Down
53 changes: 53 additions & 0 deletions internal/vm/reflection.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package vm

import (
"reflect"
"strings"

"github.com/go-embedded-ruby/ruby/internal/object"
)
Expand Down Expand Up @@ -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)
Expand Down
41 changes: 40 additions & 1 deletion internal/vm/reflection_methods_test.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
}
}
}
2 changes: 1 addition & 1 deletion scripts/conformance/rubyspec/FLOOR
Original file line number Diff line number Diff line change
@@ -1 +1 @@
15770
15790