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
81 changes: 71 additions & 10 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,12 @@ func (vm *VM) bootstrap() {
}
return object.NewString(vm.classOf(self).name)
}
cException.define("message", excMessage)
// Exception#message is defined as `to_s` in MRI, so a subclass that overrides
// #to_s changes what #message reports — dispatch through #to_s rather than
// reading @message directly.
cException.define("message", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
return vm.send(self, "to_s", nil, nil)
})
cException.define("to_s", excMessage)

// backtrace: the captured frame list (Array of String), or nil when the
Expand Down Expand Up @@ -851,7 +856,7 @@ func (vm *VM) bootstrap() {
callArgs = object.NewArrayFromSlice(append([]object.Value(nil), args[1:]...))
}
vm.raiseWithIvars("NoMethodError",
"undefined method '"+string(nameSym)+"' for "+vm.classOf(self).name,
"undefined method '"+string(nameSym)+"' for "+vm.undefinedMethodReceiver(self),
map[string]object.Value{"@name": nameSym, "@receiver": self, "@args": callArgs})
return object.NilV
})
Expand Down Expand Up @@ -8234,17 +8239,45 @@ func parseFullMessageOpts(args []object.Value) (highlight bool, order string) {
return highlight, order
}

// exceptionDetailedMessage renders "<message> (<ClassName>)", the body MRI's
// Exception#detailed_message produces and that full_message embeds. With
// highlight it wraps the message bold and the class name bold-underline, matching
// MRI's terminal form.
// exceptionDetailedMessage renders the body MRI's Exception#detailed_message
// produces and that full_message embeds. With a non-empty message on a named
// class it is "<message> (<ClassName>)"; highlight wraps the message bold and the
// class name bold-underline, matching MRI's terminal form.
//
// The empty-message and anonymous-class cases follow MRI's special-casing: an
// empty message on an anonymous class shows the class's "#<Class:0x…>"
// representation, on the exact RuntimeError class shows "unhandled exception",
// and on any other named class shows just the class name — never a "(…)" suffix.
// A non-empty message on an anonymous class shows just the message.
func (vm *VM) exceptionDetailedMessage(self object.Value, highlight bool) string {
msg := vm.exceptionMessageText(self)
cls := vm.classOf(self).name
cls := vm.classOf(self)
anonymous := cls.name == ""
if msg == "" {
var label string
switch {
case anonymous:
label = anonClassRepr(cls)
case cls == vm.consts["RuntimeError"].(*RClass):
label = "unhandled exception"
default:
label = cls.name
}
if highlight {
return "\x1b[1;4m" + label + "\x1b[m"
}
return label
}
if anonymous {
if highlight {
return "\x1b[1m" + msg
}
return msg
}
if highlight {
return "\x1b[1m" + msg + " (\x1b[1;4m" + cls + "\x1b[m\x1b[1m)\x1b[m"
return "\x1b[1m" + msg + " (\x1b[1;4m" + cls.name + "\x1b[m\x1b[1m)\x1b[m"
}
return msg + " (" + cls + ")"
return msg + " (" + cls.name + ")"
}

// exceptionFullMessage renders the MRI-shaped multi-line report. order: :top (the
Expand All @@ -8260,7 +8293,7 @@ func (vm *VM) exceptionDetailedMessage(self object.Value, highlight bool) string
// parser carries no positions) and the source-snippet/caret lines MRI prints are
// omitted, but the file+label chain matches.
func (vm *VM) exceptionFullMessage(self object.Value, highlight bool, order string) string {
detailed := vm.exceptionDetailedMessage(self, highlight)
detailed := vm.fullMessageDetailed(self, highlight)
bt, ok := getIvar(self, backtraceIvar).(*object.Array)
if !ok || len(bt.Elems) == 0 {
return detailed
Expand Down Expand Up @@ -8294,6 +8327,34 @@ func (vm *VM) exceptionFullMessage(self object.Value, highlight bool, order stri
return b.String()
}

// fullMessageDetailed obtains the detailed-message body full_message embeds by
// DISPATCHING to the exception's own #detailed_message (so a singleton override
// is honoured), passing the resolved highlight: flag. MRI coerces the result to a
// String via #to_str, and when the exception does not respond to
// #detailed_message — or it yields a value that is neither a String nor #to_str
// convertible (notably nil) — falls back to the class name, bold-underlined under
// highlight.
func (vm *VM) fullMessageDetailed(self object.Value, highlight bool) string {
if vm.respondsToDynamic(self, "detailed_message") {
h := object.NewHash()
h.Set(object.Symbol("highlight"), object.Bool(highlight))
res := vm.send(self, "detailed_message", []object.Value{h}, nil)
if s, ok := res.(*object.String); ok {
return s.Str()
}
if vm.respondsToDynamic(res, "to_str") {
if s, ok := vm.send(res, "to_str", nil, nil).(*object.String); ok {
return s.Str()
}
}
}
cls := vm.classOf(self).name
if highlight {
return "\x1b[1;4m" + cls + "\x1b[m"
}
return cls
}

// digValue implements Hash#dig: fetch the value at the first key and, via
// digRest, dig into it with the rest — returning nil as soon as a step is
// missing and raising ArgumentError when no keys are given.
Expand Down
2 changes: 1 addition & 1 deletion internal/vm/coverage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func TestErrorMessages(t *testing.T) {
if err == nil || err.Error() == "" {
t.Fatal("expected non-empty parse error")
}
if e := runErr(t, `1.foo`); e == nil || e.Error() != "NoMethodError: undefined method 'foo' for Integer" {
if e := runErr(t, `1.foo`); e == nil || e.Error() != "NoMethodError: undefined method 'foo' for an instance of Integer" {
t.Fatalf("runtime error message = %v", e)
}
}
113 changes: 112 additions & 1 deletion internal/vm/exception.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,72 @@
package vm

import (
"fmt"
"strconv"
"strings"

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

// undefinedMethodReceiver formats the "for …" tail MRI 4.0 appends to an
// "undefined method 'x'" NoMethodError, describing the receiver the failed call
// targeted. MRI renders nil/true/false literally; a named class or module as
// "class Name" / "module Name" and an anonymous one as "class #<Class:0x…>" /
// "module #<Module:0x…>"; an object carrying a per-object singleton class through
// its own #inspect-shaped "#<Class:0x…>" identity string (built here, never by
// dispatching #inspect); and any other object as "an instance of <ClassName>"
// (or the anonymous class's "#<Class:0x…>" repr when the class is unnamed).
func (vm *VM) undefinedMethodReceiver(self object.Value) string {
if object.IsNil(self) {
return "nil"
}
if b, ok := self.(object.Bool); ok {
if bool(b) {
return "true"
}
return "false"
}
if c, ok := self.(*RClass); ok {
kind := "class"
if c.isModule {
kind = "module"
}
return kind + " " + vm.classDisplayName(c)
}
if vm.objSingleton(self) != nil {
return vm.objectIdentityRepr(self)
}
return "an instance of " + vm.classDisplayName(vm.classOf(self))
}

// classDisplayName returns the class/module's name through its own (overridable)
// #name method — matching MRI, which builds the "for class …" / "an instance of
// …" message from receiver.name — or the anonymous "#<Class:0x…>" /
// "#<Module:0x…>" identity when #name yields no String (an anonymous class).
func (vm *VM) classDisplayName(c *RClass) string {
if n, ok := vm.send(c, "name", nil, nil).(*object.String); ok {
return n.Str()
}
return vm.anonClassOrModuleRepr(c)
}

// anonClassOrModuleRepr renders an anonymous class or module as MRI's
// "#<Class:0x…>" / "#<Module:0x…>" identity string.
func (vm *VM) anonClassOrModuleRepr(c *RClass) string {
kind := "Class"
if c.isModule {
kind = "Module"
}
return fmt.Sprintf("#<%s:0x%016x>", kind, uint64(vm.refID(c)))
}

// objectIdentityRepr renders an ordinary object as MRI's default
// "#<ClassName:0x…>" #inspect form, built directly (never dispatching a
// user-defined #inspect).
func (vm *VM) objectIdentityRepr(self object.Value) string {
return fmt.Sprintf("#<%s:0x%016x>", vm.classOf(self).name, uint64(vm.refID(self)))
}

// causeIvar holds an exception's cause (another exception, or nil). MRI keeps the
// cause in a hidden field; rbgo stores it in a double-underscore ivar so casual
// #instance_variables introspection does not surface it.
Expand Down Expand Up @@ -81,15 +141,47 @@ func (vm *VM) registerExceptionMethods(cException *RClass) {
})

cNameError := vm.consts["NameError"].(*RClass)
// NameError.new(msg = nil, name = nil, receiver:) — the name that could not be
// resolved is the second positional and the receiver an optional keyword, both
// stamped so #name/#receiver report what the caller passed (MRI's signature).
cNameError.define("initialize", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
args = vm.stampReceiverKwarg(self, args)
if len(args) > 0 && !object.IsNil(args[0]) {
setIvar(self, "@message", object.NewString(vm.exceptionMessageArg(args[0])))
}
if len(args) > 1 {
setIvar(self, "@name", args[1])
}
return object.NilV
})
// NameError#receiver: the object on which the missing name was looked up.
// MRI raises an ArgumentError ("no receiver is available") when none was
// recorded; rbgo records one at every method-dispatch NameError, so an unset
// receiver only happens for a bare NameError.new — return nil there.
// receiver only happens for a bare NameError.new — return nil there. (Const /
// class-variable NameErrors do not yet record a receiver either, so raising
// here would regress those cases; see the receiver_spec residuals.)
cNameError.define("receiver", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
return getIvar(self, "@receiver")
})

cNoMethodError := vm.consts["NoMethodError"].(*RClass)
// NoMethodError.new(msg = nil, name = nil, args = [], priv = false, receiver:)
// — MRI's signature: the message, the missing method name, the call's own
// arguments, a private-call flag (accepted and ignored here) and the receiver
// keyword, stamped so #name/#args/#receiver report the failed call.
cNoMethodError.define("initialize", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
args = vm.stampReceiverKwarg(self, args)
if len(args) > 0 && !object.IsNil(args[0]) {
setIvar(self, "@message", object.NewString(vm.exceptionMessageArg(args[0])))
}
if len(args) > 1 {
setIvar(self, "@name", args[1])
}
if len(args) > 2 {
setIvar(self, "@args", args[2])
}
return object.NilV
})
// NoMethodError#args: the arguments passed in the failed call (empty array by
// default). #name is inherited from NameError (defined in builtins.go).
cNoMethodError.define("args", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
Expand Down Expand Up @@ -214,6 +306,25 @@ func (vm *VM) applyRaiseCause(exc object.Value, causeGiven bool, causeVal object
setIvar(exc, causeIvar, causeVal)
}

// stampReceiverKwarg peels a trailing `receiver:` keyword off a NameError /
// NoMethodError constructor argument list, stamping @receiver, and returns the
// remaining positional args. The trailing Hash is consumed only when it carries a
// :receiver key, so a genuine positional Hash argument is left untouched.
func (vm *VM) stampReceiverKwarg(self object.Value, args []object.Value) []object.Value {
if len(args) == 0 {
return args
}
h, ok := args[len(args)-1].(*object.Hash)
if !ok {
return args
}
if v, ok := h.Get(object.Symbol("receiver")); ok {
setIvar(self, "@receiver", v)
return args[:len(args)-1]
}
return args
}

// popCauseKwarg splits a trailing `cause:` keyword out of a Kernel#raise argument
// list. The keyword hash is recognised only when its sole key is :cause, so a
// genuine Hash message (raise SomeError, {...}) is left untouched.
Expand Down
59 changes: 59 additions & 0 deletions internal/vm/exception_coverage_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package vm_test

import "testing"

// TestExceptionMessageCoverage exercises the receiver-formatting and
// receiver-keyword branches of the exception subsystem — undefinedMethodReceiver,
// classDisplayName, anonClassOrModuleRepr and stampReceiverKwarg — across nil, a
// class, a named/anonymous instance, an anonymous module, and NameError's
// `receiver:` keyword in its present / absent / message-only forms. Checked
// against MRI Ruby 4.0.6 (identity hex addresses are matched by prefix).
func TestExceptionMessageCoverage(t *testing.T) {
ok := []struct{ src, want string }{
// undefinedMethodReceiver: nil, true/false, a class, a named instance, and
// an object carrying a per-object singleton class (rendered by identity).
{`begin; nil.zzz_undef; rescue NoMethodError => e; puts e.message; end`,
"undefined method 'zzz_undef' for nil\n"},
{`begin; true.zzz_undef; rescue NoMethodError => e; puts e.message; end`,
"undefined method 'zzz_undef' for true\n"},
{`begin; false.zzz_undef; rescue NoMethodError => e; puts e.message; end`,
"undefined method 'zzz_undef' for false\n"},
{`begin; String.zzz_undef; rescue NoMethodError => e; puts e.message; end`,
"undefined method 'zzz_undef' for class String\n"},
{`begin; Object.new.zzz_undef; rescue NoMethodError => e; puts e.message; end`,
"undefined method 'zzz_undef' for an instance of Object\n"},
{`o = Object.new; def o.sing; end
begin; o.zzz_undef; rescue NoMethodError => e
puts e.message.start_with?("undefined method 'zzz_undef' for #<Object:0x")
end`, "true\n"},
// classDisplayName anonymous branch + anonClassOrModuleRepr (Class kind):
// an instance of an anonymous class renders as "#<Class:0x…>".
{`begin; Class.new.new.zzz_undef; rescue NoMethodError => e
puts e.message.start_with?("undefined method 'zzz_undef' for an instance of #<Class:0x")
end`, "true\n"},
// anonClassOrModuleRepr Module kind: a method missing on an anonymous module.
{`begin; Module.new.zzz_undef; rescue NoMethodError => e
puts e.message.include?("#<Module:0x")
end`, "true\n"},
// stampReceiverKwarg: the receiver: keyword is peeled off and stored.
{`p NameError.new("x", receiver: 42).receiver`, "42\n"},
// stampReceiverKwarg: a String last arg is left untouched (no keyword hash).
{`p NameError.new("x").message`, "\"x\"\n"},
// stampReceiverKwarg: empty args returns unchanged (default message).
{`p NameError.new.is_a?(NameError)`, "true\n"},
// stampReceiverKwarg: a Symbol name arg is not a keyword hash (left as-is).
{`p NameError.new("x", :some_name).name`, ":some_name\n"},
// stampReceiverKwarg: a trailing Hash without a :receiver key is left as-is.
{`p NameError.new("x", {"a" => 1}).message`, "\"x\"\n"},
// NoMethodError.new(message, name, args): the positional message/name/args
// branches of its initialize.
{`p NoMethodError.new("boom", :meth, [1, 2]).name`, ":meth\n"},
{`p NoMethodError.new("boom", :meth, [1, 2]).args`, "[1, 2]\n"},
{`p NoMethodError.new("boom", :meth, [1, 2]).message`, "\"boom\"\n"},
}
for _, c := range ok {
if got := eval(t, c.src); got != c.want {
t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want)
}
}
}
Loading