diff --git a/internal/vm/anon_inspect_test.go b/internal/vm/anon_inspect_test.go new file mode 100644 index 00000000..d23b460e --- /dev/null +++ b/internal/vm/anon_inspect_test.go @@ -0,0 +1,65 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestAnonymousClassInspect pins the naming of an anonymous class's instance to +// MRI 4.0.10: rb_obj_inspect, rb_any_to_s and the FrozenError message all name +// the class through rb_class_name, which renders an anonymous class as its +// "#" identity. rbgo read the empty name and printed "#<:0x…>" and +// "can't modify frozen : …". Addresses are masked; the shape is MRI's output. +func TestAnonymousClassInspect(t *testing.T) { + const pre = `def h(s) = s.gsub(/0x\h+/, "X") +k = Class.new +` + cases := []struct{ src, want string }{ + {`o = k.new; p [h(o.inspect), h(o.to_s)]`, `["#<#:X>", "#<#:X>"]`}, + {`o = k.new; o.instance_variable_set(:@a, 1); p h(o.inspect)`, `"#<#:X @a=1>"`}, + {`begin; k.new.freeze.instance_variable_set(:@a, 1); rescue => e; p h(e.message); end`, + `"can't modify frozen #: #<#:X>"`}, + {`p h(Class.new(k).new.inspect)`, `"#<#:X>"`}, + // a named class is unchanged. + {`class Named; end; p Named.new.inspect.start_with?("#", its recursion marker +// is "#", and the members go through their own #inspect, as +// rb_inspect does. The expected values are MRI 4.0.10's output. +func TestSetSubclassInspect(t *testing.T) { + const pre = `def h(s) = s.gsub(/0x\h+/, "X") +class Foo < Set; end +` + cases := []struct{ src, want string }{ + {`p Foo[1, 2]`, "#"}, + {`p Foo.new`, "#"}, + {`puts Foo[1].to_s`, "#"}, + {`p Set[Foo[1]]`, "Set[#]"}, + {`p [Foo[2]], {a: Foo[3]}`, "[#]\n{a: #}"}, + {`class Bar < Foo; end; p Bar[3]`, "#"}, + {`r = Foo[1]; r << r; p r`, "#}>"}, + {`p h(Class.new(Set)[1].inspect)`, `"#<#: {1}>"`}, + {`p h(Set[Class.new(Set)[1]].inspect)`, `"Set[#<#: {1}>]"`}, + {`module Outer; class Set < ::Set; end; end; p Outer::Set[1]`, "#"}, + // plain Set keeps the 4.0 literal form, inspect and to_s alike. + {`s = Set[1]; p [s.inspect, s.to_s]`, `["Set[1]", "Set[1]"]`}, + // a member's own #inspect is used, by p and by #inspect. + {`q = Object.new; def q.inspect = "Q!"; p Set[q], Foo[q]`, "Set[Q!]\n#"}, + // a subclass override of #inspect is honoured by p, nested or not. + {`class Baz < Set; def inspect = "BAZ"; end; p Baz[1], Set[Baz[1]], [Baz[1]]`, "BAZ\nSet[BAZ]\n[BAZ]"}, + } + for _, c := range cases { + if got := runSrc(t, pre+c.src); got != c.want { + t.Fatalf("src=%q got=%q want=%q", c.src, got, c.want) + } + } +} diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 86a656c6..d2f84dca 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -6701,7 +6701,7 @@ func (vm *VM) rehomeKernelMethods() { func (vm *VM) defaultObjectInspect(o *RObject, only map[string]bool) string { var b strings.Builder b.WriteString("#<") - b.WriteString(o.class.name) + b.WriteString(vm.classPath(o.class)) b.WriteString(":0x") hex := strconv.FormatUint(uint64(vm.refID(o)), 16) for i := len(hex); i < 16; i++ { @@ -7437,8 +7437,10 @@ func (vm *VM) pInspect(v object.Value) string { // Go Inspect(); those classes register no Ruby #inspect of their own, so // dispatching would render them through the generic one and leave every // Inspect() unreachable. inspectStr takes the same path. + // Set is a container too and registers its own Ruby #inspect, so a member's + // #inspect and a subclass override are honoured by `p set` as by `p [set]`. switch v.(type) { - case *RObject, *object.Array, *object.Hash: + case *RObject, *object.Array, *object.Hash, *Set: r := vm.send(v, "inspect", nil, nil) if s, ok := r.(*object.String); ok { return s.Str() @@ -11549,7 +11551,7 @@ func (vm *VM) checkHashFrozen(h *object.Hash) { // mirroring MRI's "can't modify frozen : " message. func (vm *VM) raiseFrozen(self object.Value) { vm.raiseWithIvars("FrozenError", - "can't modify frozen "+vm.classOf(self).name+": "+vm.inspectStr(self), + "can't modify frozen "+vm.classPath(vm.classOf(self))+": "+vm.inspectStr(self), map[string]object.Value{"@receiver": self}) } diff --git a/internal/vm/exception.go b/internal/vm/exception.go index b5f698b7..29cacd5b 100644 --- a/internal/vm/exception.go +++ b/internal/vm/exception.go @@ -68,6 +68,18 @@ func (vm *VM) classDisplayName(c *RClass) string { return vm.anonClassOrModuleRepr(c) } +// classPath is rb_class_name: the class's permanent name, or for an anonymous +// one its "#" identity. Unlike classDisplayName it never dispatches +// a user #name, as MRI's rb_obj_inspect / rb_any_to_s / rb_error_frozen_object +// do not. Reading c.name directly printed "#<:0x…>" for an instance of an +// anonymous class and "can't modify frozen : …" for its FrozenError. +func (vm *VM) classPath(c *RClass) string { + if c.name != "" { + return c.name + } + return vm.anonClassOrModuleRepr(c) +} + // anonClassOrModuleRepr renders an anonymous class or module as MRI's // "#" / "#" identity string. func (vm *VM) anonClassOrModuleRepr(c *RClass) string { @@ -82,7 +94,7 @@ func (vm *VM) anonClassOrModuleRepr(c *RClass) string { // "#" #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))) + return fmt.Sprintf("#<%s:0x%016x>", vm.classPath(vm.classOf(self)), uint64(vm.refID(self))) } // causeIvar holds an exception's cause (another exception, or nil). MRI keeps the diff --git a/internal/vm/io.go b/internal/vm/io.go index f1294163..c8afe997 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -3105,7 +3105,13 @@ func (vm *VM) displayStr(v object.Value) string { // (possibly user-defined) #inspect; built-in value types use their native // Inspect. A non-String #inspect result falls back to the native Inspect. func (vm *VM) inspectStr(v object.Value) string { - if _, ok := v.(*RObject); !ok { + switch v.(type) { + case *RObject: + case *Set: + // A Set dispatches too: its members are inspected through Ruby (a member's + // own #inspect counts, as rb_inspect calls it), an anonymous subclass is + // named by its # identity, and a subclass may override #inspect. + default: return v.Inspect() } r := vm.send(v, "inspect", nil, nil) diff --git a/internal/vm/set.go b/internal/vm/set.go index 54aa6a5e..229a8ed9 100644 --- a/internal/vm/set.go +++ b/internal/vm/set.go @@ -53,20 +53,39 @@ func (s *Set) Truthy() bool { return true } // order each rendered with Ruby #inspect, with a cycle guard so a Set that // (transitively) contains itself renders "Set[...]" instead of looping. (Ruby 4.0 // replaced the older "#" form with the "Set[…]" literal form.) -func (s *Set) repr() string { +func (s *Set) repr() string { return s.reprWith(nil) } + +// reprWith is repr with a VM to name an anonymous subclass and to inspect each +// member through Ruby. set_i_inspect (set.c, v4.0.10) prints the "Set[…]" +// literal form for Set itself only; an instance of a SUBCLASS keeps the +// pre-4.0 shape, "#", and its recursion marker is +// "#". rbgo printed "Set[…]" for both. +func (s *Set) reprWith(vm *VM) string { + open, close, recur := "Set[", "]", "Set[...]" + if s.cls != nil && s.cls.name != "Set" { + name := s.cls.ToS() + if vm != nil { + name = vm.classPath(s.cls) + } + open, close, recur = "#<"+name+": {", "}>", "#<"+name+": {...}>" + } if !object.ReprEnter(s) { - return "Set[...]" + return recur } defer object.ReprLeave(s) var b strings.Builder - b.WriteString("Set[") + b.WriteString(open) for i, k := range s.h.Keys { if i > 0 { b.WriteString(", ") } - b.WriteString(k.Inspect()) + if vm != nil { + b.WriteString(vm.inspectStr(k)) + } else { + b.WriteString(k.Inspect()) + } } - b.WriteString("]") + b.WriteString(close) return b.String() } @@ -275,8 +294,8 @@ func (vm *VM) registerSet() { }) vm.setInstanceVisibility(vm.cSet, "initialize_copy", visPrivate) - d("to_s", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - return object.NewString(self(v).repr()) + d("to_s", func(vm *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { + return object.NewString(self(v).reprWith(vm)) }) // Genuine built-in aliases share one Method record, so Set.instance_method of diff --git a/internal/vm/set_repr_internal_test.go b/internal/vm/set_repr_internal_test.go new file mode 100644 index 00000000..97ac1d9e --- /dev/null +++ b/internal/vm/set_repr_internal_test.go @@ -0,0 +1,38 @@ +// 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" +) + +// TestSetGoInspect covers Set's Go-level Inspect/ToS, the object.Value face a +// host program (or a Go-side error message) reads without a VM. Ruby's +// Set#inspect goes through reprWith(vm), so nothing in the Ruby suite reaches +// the VM-less path, and the coverage ratchet caught it at 0%. The shapes are +// the ones set_i_inspect prints on MRI 4.0.10: "Set[…]" for Set itself, the +// pre-4.0 "#" for a subclass, and a recursion marker for each. +func TestSetGoInspect(t *testing.T) { + s := newSet() + s.add(object.Integer(1)) + s.add(object.NewString("a")) + s.add(s) + if got, want := s.Inspect(), `Set[1, "a", Set[...]]`; got != want { + t.Errorf("Set Inspect = %q, want %q", got, want) + } + if s.ToS() != s.Inspect() { + t.Errorf("Set ToS %q differs from Inspect %q", s.ToS(), s.Inspect()) + } + + sub := newSet() + sub.cls = newClass("Foo", newClass("Set", nil)) + sub.add(object.Integer(2)) + sub.add(sub) + if got, want := sub.Inspect(), "#}>"; got != want { + t.Errorf("subclass Inspect = %q, want %q", got, want) + } +}