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
65 changes: 65 additions & 0 deletions internal/vm/anon_inspect_test.go
Original file line number Diff line number Diff line change
@@ -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
// "#<Class:0x…>" 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)]`, `["#<#<Class:X>:X>", "#<#<Class:X>:X>"]`},
{`o = k.new; o.instance_variable_set(:@a, 1); p h(o.inspect)`, `"#<#<Class:X>:X @a=1>"`},
{`begin; k.new.freeze.instance_variable_set(:@a, 1); rescue => e; p h(e.message); end`,
`"can't modify frozen #<Class:X>: #<#<Class:X>:X>"`},
{`p h(Class.new(k).new.inspect)`, `"#<#<Class:X>:X>"`},
// a named class is unchanged.
{`class Named; end; p Named.new.inspect.start_with?("#<Named:0x")`, "true"},
}
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)
}
}
}

// TestSetSubclassInspect: set_i_inspect prints the "Set[…]" literal form for Set
// itself only. A subclass instance keeps "#<Foo: {1, 2}>", its recursion marker
// is "#<Foo: {...}>", 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]`, "#<Foo: {1, 2}>"},
{`p Foo.new`, "#<Foo: {}>"},
{`puts Foo[1].to_s`, "#<Foo: {1}>"},
{`p Set[Foo[1]]`, "Set[#<Foo: {1}>]"},
{`p [Foo[2]], {a: Foo[3]}`, "[#<Foo: {2}>]\n{a: #<Foo: {3}>}"},
{`class Bar < Foo; end; p Bar[3]`, "#<Bar: {3}>"},
{`r = Foo[1]; r << r; p r`, "#<Foo: {1, #<Foo: {...}>}>"},
{`p h(Class.new(Set)[1].inspect)`, `"#<#<Class:X>: {1}>"`},
{`p h(Set[Class.new(Set)[1]].inspect)`, `"Set[#<#<Class:X>: {1}>]"`},
{`module Outer; class Set < ::Set; end; end; p Outer::Set[1]`, "#<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#<Foo: {Q!}>"},
// 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)
}
}
}
8 changes: 5 additions & 3 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -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++ {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -11549,7 +11551,7 @@ func (vm *VM) checkHashFrozen(h *object.Hash) {
// mirroring MRI's "can't modify frozen <class>: <inspect>" 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})
}

Expand Down
14 changes: 13 additions & 1 deletion internal/vm/exception.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 "#<Class:0x…>" 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
// "#<Class:0x…>" / "#<Module:0x…>" identity string.
func (vm *VM) anonClassOrModuleRepr(c *RClass) string {
Expand All @@ -82,7 +94,7 @@ func (vm *VM) anonClassOrModuleRepr(c *RClass) string {
// "#<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)))
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
Expand Down
8 changes: 7 additions & 1 deletion internal/vm/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 #<Class:0x…> identity, and a subclass may override #inspect.
default:
return v.Inspect()
}
r := vm.send(v, "inspect", nil, nil)
Expand Down
33 changes: 26 additions & 7 deletions internal/vm/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 "#<Set: {…}>" 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, "#<Foo: {1, 2}>", and its recursion marker is
// "#<Foo: {...}>". 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()
}

Expand Down Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions internal/vm/set_repr_internal_test.go
Original file line number Diff line number Diff line change
@@ -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 "#<Foo: {…}>" 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(), "#<Foo: {2, #<Foo: {...}>}>"; got != want {
t.Errorf("subclass Inspect = %q, want %q", got, want)
}
}
Loading