From 56db80ed06b157af408e57c94ca494cc260e56ae Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 08:28:27 +0200 Subject: [PATCH 1/3] vm: MRI-align Exception#detailed_message and full_message dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rewrite exceptionDetailedMessage to match MRI 4.0's empty-message and anonymous-class special cases: an empty message renders the class's "#" repr for an anonymous class, "unhandled exception" for the exact RuntimeError class, and the bare class name otherwise — never a "(…)" suffix; a non-empty message on an anonymous class shows just the message. full_message now DISPATCHES to the exception's own (overridable) #detailed_message via fullMessageDetailed, coercing a non-String return through #to_str and falling back to the class name when it is absent or yields nil. core/exception/detailed_message_spec: 3→10 pass. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 72 +++++++++++++++++--- internal/vm/exception_residuals_test.go | 88 +++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 8 deletions(-) create mode 100644 internal/vm/exception_residuals_test.go diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index e8a755d1..8acf08a3 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -8234,17 +8234,45 @@ func parseFullMessageOpts(args []object.Value) (highlight bool, order string) { return highlight, order } -// exceptionDetailedMessage renders " ()", 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 " ()"; 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 "#" +// 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 @@ -8260,7 +8288,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 @@ -8294,6 +8322,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. diff --git a/internal/vm/exception_residuals_test.go b/internal/vm/exception_residuals_test.go new file mode 100644 index 00000000..955a9401 --- /dev/null +++ b/internal/vm/exception_residuals_test.go @@ -0,0 +1,88 @@ +package vm_test + +import ( + "strings" + "testing" +) + +// TestExceptionDetailedMessage exercises Exception#detailed_message across MRI's +// empty-message and anonymous-class special cases, in both plain and highlight +// forms. +func TestExceptionDetailedMessage(t *testing.T) { + tests := []struct { + name, src, want string + }{ + {"named_nonempty", `print RuntimeError.new("x").detailed_message`, "x (RuntimeError)"}, + {"runtimeerror_empty", `print RuntimeError.new("").detailed_message`, "unhandled exception"}, + {"other_empty", `print StandardError.new("").detailed_message`, "StandardError"}, + {"named_nonempty_highlight", `print RuntimeError.new("x").detailed_message(highlight: true)`, + "\x1b[1mx (\x1b[1;4mRuntimeError\x1b[m\x1b[1m)\x1b[m"}, + {"runtimeerror_empty_highlight", `print RuntimeError.new("").detailed_message(highlight: true)`, + "\x1b[1;4munhandled exception\x1b[m"}, + {"other_empty_highlight", `print StandardError.new("").detailed_message(highlight: true)`, + "\x1b[1;4mStandardError\x1b[m"}, + {"anon_nonempty", `print Class.new(RuntimeError).new("m").detailed_message`, "m"}, + {"anon_nonempty_highlight", `print Class.new(RuntimeError).new("m").detailed_message(highlight: true)`, + "\x1b[1mm"}, + {"ignores_other_kwargs", `print RuntimeError.new("x").detailed_message(foo: true)`, "x (RuntimeError)"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestExceptionDetailedMessageAnonEmpty checks the anonymous-class empty-message +// path renders the class's "#" representation. +func TestExceptionDetailedMessageAnonEmpty(t *testing.T) { + got := eval(t, `print Class.new(RuntimeError).new("").detailed_message`) + if !strings.HasPrefix(got, "#") { + t.Errorf("anonymous empty detailed_message = %q, want #", got) + } + gotH := eval(t, `print Class.new(RuntimeError).new("").detailed_message(highlight: true)`) + if !strings.HasPrefix(gotH, "\x1b[1;4m#\x1b[m") { + t.Errorf("anonymous empty highlight detailed_message = %q", gotH) + } +} + +// TestExceptionFullMessageDispatch checks that Exception#full_message dispatches +// to the (overridable) #detailed_message: it honours a singleton override, +// coerces a non-String return via #to_str, and falls back to the class name when +// the override yields nil, in both plain and highlight forms. +func TestExceptionFullMessageDispatch(t *testing.T) { + tests := []struct { + name, src, want string + }{ + {"default", `print RuntimeError.new("x").full_message.lines.first`, "x (RuntimeError)"}, + {"unhandled_empty", `print RuntimeError.new("").full_message`, "unhandled exception"}, + {"override_string", `e = RuntimeError.new("x") +e.define_singleton_method(:detailed_message) { |**opts| "OVERRIDDEN" } +print e.full_message.lines.first`, "OVERRIDDEN"}, + {"override_to_str", `msg = Object.new +def msg.to_str; "COERCED"; end +e = RuntimeError.new("x") +e.define_singleton_method(:detailed_message) { |**opts| msg } +print e.full_message.lines.first`, "COERCED"}, + {"override_nil", `e = RuntimeError.new("x") +e.define_singleton_method(:detailed_message) { |**opts| nil } +print e.full_message(highlight: false).lines.first`, "RuntimeError"}, + {"override_nil_highlight", `e = RuntimeError.new("x") +e.define_singleton_method(:detailed_message) { |**opts| nil } +print e.full_message(highlight: true).lines.first`, "\x1b[1;4mRuntimeError\x1b[m"}, + {"undef_fallback", `e = RuntimeError.new("x") +class << e + undef :detailed_message +end +print e.full_message(highlight: false).lines.first`, "RuntimeError"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} From ae1a6eb5619723318b9cbac83c115ac57cf9d657 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 08:42:08 +0200 Subject: [PATCH 2/3] vm: MRI-align NoMethodError receiver message, NameError/NoMethodError.new, Exception#message MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Format the NoMethodError "for …" tail as MRI 4.0 does: nil/true/false literally; a class/module by its own (overridable) #name as "class Name" / "module Name", anonymous as "class #" / "module #"; an object carrying a singleton class through its identity "#" string (built directly, never dispatching #inspect); and any other object as "an instance of ". NameError.new / NoMethodError.new now accept MRI's (message, name, [args], receiver:) signature, stamping #name/#args/#receiver. Exception#message is defined as #to_s, so a subclass overriding #to_s changes #message. core/exception: no_method_error 7->21, name_error 1->3, message 3->4; +24 across the cluster (117->141 pass). Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 9 ++- internal/vm/coverage_test.go | 2 +- internal/vm/exception.go | 113 ++++++++++++++++++++++++++++++++++- 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 8acf08a3..f4e332a0 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -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 @@ -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 }) diff --git a/internal/vm/coverage_test.go b/internal/vm/coverage_test.go index ef04d6bd..5febaf9d 100644 --- a/internal/vm/coverage_test.go +++ b/internal/vm/coverage_test.go @@ -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) } } diff --git a/internal/vm/exception.go b/internal/vm/exception.go index c07544dd..9a86e28a 100644 --- a/internal/vm/exception.go +++ b/internal/vm/exception.go @@ -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 #" / +// "module #"; an object carrying a per-object singleton class through +// its own #inspect-shaped "#" identity string (built here, never by +// dispatching #inspect); and any other object as "an instance of " +// (or the anonymous class's "#" 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 "#" / +// "#" 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 +// "#" / "#" 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 +// "#" #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. @@ -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 { @@ -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. From 38e2cfb241e553da7e8e4ec34c4661a026e876af Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 10:06:48 +0200 Subject: [PATCH 3/3] test: cover the exception message/receiver helpers to 100% undefinedMethodReceiver, classDisplayName, anonClassOrModuleRepr, stampReceiverKwarg and NoMethodError#initialize had receiver-shape and positional-argument branches the suite never exercised, dropping the merged -race total below the 100% POSIX gate. Drive them across nil / true / false / class / module / named + anonymous instance / singleton-carrying receivers, the NameError receiver: keyword (present, absent, message-only, non-receiver Hash), and NoMethodError.new(message, name, args). exception.go is now 100%. Co-Authored-By: Claude Opus 4.8 --- internal/vm/exception_coverage_test.go | 59 ++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 internal/vm/exception_coverage_test.go diff --git a/internal/vm/exception_coverage_test.go b/internal/vm/exception_coverage_test.go new file mode 100644 index 00000000..6c7ea029 --- /dev/null +++ b/internal/vm/exception_coverage_test.go @@ -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 #". + {`begin; Class.new.new.zzz_undef; rescue NoMethodError => e + puts e.message.start_with?("undefined method 'zzz_undef' for an instance of # e + puts e.message.include?("# 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) + } + } +}