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
66 changes: 62 additions & 4 deletions internal/vm/method_reflect2.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,25 @@ func (vm *VM) registerMethodReflect2() {

// Object#public_method: like #method, but a private or protected target
// raises NameError instead of returning a callable Method.
//
// The NameError is MRI's rb_print_undef / rb_print_inaccessible on the
// receiver's CLASS_OF (proc.c mnew_internal): its #receiver is that class —
// the singleton class when there is one, so a class receiver reports
// #<Class:Foo> — and the message names the class with its visibility.
vm.cObject.define("public_method", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
name := nameArg(args[0])
m := vm.resolveMethod(self, name)
if m == nil {
return raise("NameError", "undefined method '%s' for %s", name, vm.classOf(self).name)
klass := vm.classOfForNameError(self)
return vm.raiseNameError("undefined method '"+name+"' for class '"+vm.nameErrMesgRecv(klass)+"'", name, klass)
}
if vm.sendVisibilityOf(self, name, m) != visPublic {
return raise("NameError", "method '%s' for %s is not public", name, vm.classOf(self).name)
if vis := vm.sendVisibilityOf(self, name, m); vis != visPublic {
kind := "private"
if vis == visProtected {
kind = "protected"
}
klass := vm.classOfForNameError(self)
return vm.raiseNameError("method '"+name+"' for class '"+vm.nameErrMesgRecv(klass)+"' is "+kind, name, klass)
}
return vm.newBoundMethod(self, name, m)
})
Expand All @@ -111,12 +122,59 @@ func (vm *VM) registerMethodReflect2() {
name := nameArg(args[0])
m := vm.singletonOnlyMethod(self, name)
if m == nil || m.undefined {
return raise("NameError", "undefined singleton method '%s' for %s", name, vm.classOf(self).name)
// rb_obj_singleton_method (proc.c v4.0.9:2362): the message names the
// receiver itself, not its class, and #name / #receiver are set.
return vm.raiseNameError("undefined singleton method '"+name+"' for '"+vm.nameErrMesgRecv(self)+"'", name, self)
}
return vm.newBoundMethod(self, name, m)
})
}

// nameErrMesgRecv renders the receiver the way a NameError message's '%2$s'
// does in MRI (name_err_mesg_to_str, error.c v4.0.10:2633-2655): nil, true and
// false as themselves; a class or module by its #name when that is a String;
// anything else -- an anonymous class included -- by #inspect, whose result
// goes through #to_s (an #inspect answering 42 reads '42'). When #inspect
// raises, rb_protect swallows it and rb_any_to_s answers: "#<Weird:0x...>".
func (vm *VM) nameErrMesgRecv(v object.Value) (s string) {
switch t := v.(type) {
case object.Nil:
return "nil"
case object.Bool:
if bool(t) {
return "true"
}
return "false"
}
defer func() {
if r := recover(); r != nil {
if _, isRE := r.(RubyError); !isRE {
panic(r)
}
s = vm.objectIdentityRepr(v) // rb_any_to_s: "#<Class:0x...>" for a class too
}
}()
if c, ok := v.(*RClass); ok {
if n, ok := vm.send(c, "name", nil, nil).(*object.String); ok {
return n.Str()
}
}
return vm.objAsString(vm.send(v, "inspect", nil, nil))
}

// classOfForNameError is MRI's CLASS_OF(obj) as rb_print_undef receives it: the
// singleton class when the value has one (always, for a class or module, whose
// metaclass MRI creates with it), otherwise the value's class.
func (vm *VM) classOfForNameError(v object.Value) *RClass {
if c, ok := v.(*RClass); ok {
return c.metaClass()
}
if sc := vm.objSingleton(v); sc != nil {
return sc
}
return vm.classOf(v)
}

// singletonOnlyMethod resolves name among recv's singleton methods only: the
// methods on an object's singleton class (and modules mixed into it), or a
// class/module's own class methods. Returns nil when name is not a singleton
Expand Down
30 changes: 30 additions & 0 deletions internal/vm/name_err_recv_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm

import (
"testing"

"github.com/go-embedded-ruby/ruby/internal/object"
)

// TestNameErrMesgRecvKeepsAGoPanic pins the other half of nameErrMesgRecv's
// recover: a Ruby exception raised by #name or #inspect falls back to
// rb_any_to_s, but a Go panic is an interpreter bug and must reach the caller
// unchanged rather than be turned into a plausible "#<Class:0x…>".
func TestNameErrMesgRecvKeepsAGoPanic(t *testing.T) {
vm := New(nil)
c := newClass("Boom", vm.consts["Object"].(*RClass))
c.smethods["name"] = &Method{name: "name", owner: c, native: func(*VM, object.Value, []object.Value, *Proc) object.Value {
panic("a Go bug")
}}
defer func() {
if r := recover(); r != "a Go bug" {
t.Fatalf("recovered %#v, want the Go panic itself", r)
}
}()
s := vm.nameErrMesgRecv(c)
t.Fatalf("a Go panic was swallowed into %q", s)
}
90 changes: 90 additions & 0 deletions internal/vm/name_error_receiver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm_test

import "testing"

// TestSingletonMethodNameErrorNamesTheReceiver: Object#singleton_method's
// NameError names the receiver itself (rb_obj_singleton_method, proc.c
// v4.0.9:2362, '%2$s'), not its class, and carries #name and #receiver. The
// receiver is rendered as error.c's name_err_mesg_to_str does: nil/true/false
// literally, a class or module by #name, anything else by #inspect through #to_s,
// and rb_any_to_s when #inspect raises. Expected output: MRI 4.0.10.
func TestSingletonMethodNameErrorNamesTheReceiver(t *testing.T) {
checkCases(t, []runCase{
{`class Foo; def inspect = "FOO!"; end
class Weird; def inspect = raise("no"); end
class Weird2; def inspect = 42; end
[Foo.new, Foo, Comparable, nil, false, 1, :sym, "str", [1], {a: 1}, Weird.new, Weird2.new, Class.new].each do |r|
begin
r.singleton_method(:nope)
rescue NameError => e
puts e.message.gsub(/0x\h+/, "0xX")
puts "#{e.name.inspect} #{e.receiver.equal?(r)}"
end
end
begin; singleton_method(:z); rescue NameError => e; puts e.message; end
class K; def self.inspect = "INSPECT"; end
c = Class.new; def c.name = raise("n")
m = Module.new; def m.name = raise("n"); def m.inspect = raise("i")
[true, K, c, m].each do |r|
begin
r.singleton_method(:nope)
rescue NameError => e
puts e.message.gsub(/0x\h+/, "0xX")
end
end`,
"undefined singleton method 'nope' for 'FOO!'\n:nope true\n" +
"undefined singleton method 'nope' for 'Foo'\n:nope true\n" +
"undefined singleton method 'nope' for 'Comparable'\n:nope true\n" +
"undefined singleton method 'nope' for 'nil'\n:nope true\n" +
"undefined singleton method 'nope' for 'false'\n:nope true\n" +
"undefined singleton method 'nope' for '1'\n:nope true\n" +
"undefined singleton method 'nope' for ':sym'\n:nope true\n" +
"undefined singleton method 'nope' for '\"str\"'\n:nope true\n" +
"undefined singleton method 'nope' for '[1]'\n:nope true\n" +
"undefined singleton method 'nope' for '{a: 1}'\n:nope true\n" +
"undefined singleton method 'nope' for '#<Weird:0xX>'\n:nope true\n" +
"undefined singleton method 'nope' for '42'\n:nope true\n" +
"undefined singleton method 'nope' for '#<Class:0xX>'\n:nope true\n" +
"undefined singleton method 'z' for 'main'\n" +
// true literally; a class by #name, not #inspect; a class whose #name
// raises, and a module whose #name and #inspect both raise, fall back
// to rb_any_to_s.
"undefined singleton method 'nope' for 'true'\n" +
"undefined singleton method 'nope' for 'K'\n" +
"undefined singleton method 'nope' for '#<Class:0xX>'\n" +
"undefined singleton method 'nope' for '#<Module:0xX>'\n"},
})
}

// TestPublicMethodNameErrorNamesTheClassOf: Object#public_method raises
// through rb_print_undef / rb_print_inaccessible on CLASS_OF(receiver), so the
// NameError's #receiver is that class -- the singleton class when there is one,
// which a class receiver always has -- and the message names the visibility
// ("is private" / "is protected"), not "is not public". Expected output: MRI
// 4.0.10.
func TestPublicMethodNameErrorNamesTheClassOf(t *testing.T) {
checkCases(t, []runCase{
{`class Foo; private def priv; end; protected def prot; end; end
o = Foo.new
s = Object.new
def s.x; end
[[o, :nope], [Foo, :nope], [o, :priv], [o, :prot], [s, :nope], [nil, :nope]].each do |r, n|
begin
r.public_method(n)
rescue NameError => e
puts e.message.gsub(/0x\h+/, "0xX")
puts "#{e.name.inspect} #{e.receiver.inspect.gsub(/0x\h+/, "0xX")}"
end
end`,
"undefined method 'nope' for class 'Foo'\n:nope Foo\n" +
"undefined method 'nope' for class '#<Class:Foo>'\n:nope #<Class:Foo>\n" +
"method 'priv' for class 'Foo' is private\n:priv Foo\n" +
"method 'prot' for class 'Foo' is protected\n:prot Foo\n" +
"undefined method 'nope' for class '#<Class:#<Object:0xX>>'\n:nope #<Class:#<Object:0xX>>\n" +
"undefined method 'nope' for class 'NilClass'\n:nope NilClass\n"},
})
}
Loading