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
7 changes: 7 additions & 0 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ func (vm *VM) bootstrap() {
vm.cObject.define("dup", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
cp := dupValue(self)
if cp != self { // an immediate value dups to itself and skips the hook
copyGenericIvars(self, cp)
vm.send(cp, "initialize_dup", []object.Value{self}, nil)
}
return cp
Expand Down Expand Up @@ -269,6 +270,7 @@ func (vm *VM) bootstrap() {
if cp == self { // an immediate value clones to itself
return cp
}
copyGenericIvars(self, cp)
vm.cloneSingleton(self, cp)
if freezeGiven {
kw := object.NewHash()
Expand Down Expand Up @@ -11402,6 +11404,11 @@ func dupValue(v object.Value) object.Value {
copy(dup.structVals, x.structVals)
}
return dup
case *Set:
// rb_obj_dup allocates an EMPTY instance of the receiver's class; the
// members arrive through Set#initialize_copy (set_i_initialize_copy), so a
// subclass hook that skips super leaves the copy empty, as in MRI.
return &Set{h: object.NewHash(), cls: x.cls}
case *BoundMethod:
cp := *x
cp.methodValueState = copyMethodState(x.methodValueState)
Expand Down
30 changes: 30 additions & 0 deletions internal/vm/object_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package vm

import (
"fmt"
"maps"
"reflect"
"runtime"
"slices"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -2248,6 +2250,34 @@ func genericIvarsOf(self object.Value, create bool) *genericIvars {
return g
}

// copyGenericIvars gives dst a copy of src's generic-table ivars, in their
// assignment order. It is rb_copy_generic_ivar, which init_copy (object.c) runs
// for every dup and clone before the initialize_copy hook: without it, an
// Array, String, Hash or Set lost every instance variable on dup/clone while an
// *RObject kept them (dupValue copies those). A source with no entry costs one
// lookup and creates nothing. Callers pass a fresh copy, never src itself; a dst
// with no identity (an immediate) has no table to receive them.
func copyGenericIvars(src, dst object.Value) {
g := genericIvarsOf(src, false)
if g == nil {
return
}
ivars, order := g.snapshot()
d := genericIvarsOf(dst, true)
if d == nil {
return
}
d.ivars, d.order = ivars, order
}

// snapshot copies g's map and order under the table lock, so a copy never shares
// storage with its source.
func (g *genericIvars) snapshot() (map[string]object.Value, []string) {
genericIvarMu.Lock()
defer genericIvarMu.Unlock()
return maps.Clone(g.ivars), slices.Clone(g.order)
}

// hasIdentity reports whether self is a reference. That is what the generic
// table needs of a key — an entry belongs to ONE object, and a copy of a Go
// struct value would answer to the entry of every equal copy — and it is the
Expand Down
40 changes: 27 additions & 13 deletions internal/vm/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,19 +247,33 @@ func (vm *VM) registerSet() {
return s
})

// dup / clone: a shallow copy with the same members, insertion order and
// compare_by_identity flag (ReplaceWith carries the flag across).
// dup/clone keep the receiver's class, as MRI's rb_obj_dup does — and that
// is also what carries it through `|`, which the prelude writes as
// `n = dup; …` (prelude.rb:1247).
dupFn := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value {
n := newSet()
n.cls = self(v).cls
n.h.ReplaceWith(self(v).h)
return n
}
d("dup", dupFn)
d("clone", dupFn)
// initialize_copy fills a copy's members from the original, which is the only
// copy hook set.c defines (set_i_initialize_copy, Init_Set, v4.0.10): Set has
// no dup or clone of its own. Object#dup / #clone allocate the copy (dupValue
// keeps the class), carry the ivars, singleton and frozen state, and reach
// this through initialize_dup / initialize_clone — so a subclass overriding
// initialize_copy is honoured, as it is in MRI (#866). ReplaceWith carries the
// insertion order and the compare_by_identity flag, as set_copy copies the
// table with its type. Like set_i_initialize_copy, it skips a self-copy and
// refuses to run during an iteration; it has no frozen check of its own.
d("initialize_copy", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value {
s := self(v)
if args[0] == v {
return v
}
if s.iterating > 0 {
raise("RuntimeError", "cannot replace set during iteration")
}
// RSET_TABLE(other) goes through TypedData_Get_Struct, whose refusal
// names the class and the data type's name, "set".
orig, ok := args[0].(*Set)
if !ok {
raise("TypeError", "wrong argument type %s (expected set)", vm.classOf(args[0]).name)
}
s.h.ReplaceWith(orig.h)
return v
})
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())
Expand Down
93 changes: 93 additions & 0 deletions internal/vm/set_copy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// 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"
)

// TestSetDupClone pins Set#dup / #clone to MRI 4.0.10 (#866): Set defines no dup
// or clone of its own, only initialize_copy (set.c Init_Set), so the copy goes
// through rb_obj_dup / rb_obj_clone and keeps the subclass, the instance
// variables, the singleton (clone only) and a user initialize_copy hook. The
// expected values are MRI's output for the same programs.
func TestSetDupClone(t *testing.T) {
cases := []struct{ src, want string }{
{`sub = Class.new(Set); s = sub.new([1, 2]); s.instance_variable_set(:@tag, 7)
d = s.dup; c = s.clone
p [d.class == sub, d.instance_variable_get(:@tag), d.to_a, c.class == sub, c.instance_variable_get(:@tag), c.to_a]`,
"[true, 7, [1, 2], true, 7, [1, 2]]"},
// the copy is independent of the original.
{`s = Set[1, 2]; d = s.dup; d << 3; p [s.size, d.size]`, "[2, 3]"},
// compare_by_identity survives both, as set_copy copies the table type.
{`t = Set[1].compare_by_identity; p [t.dup.compare_by_identity?, t.clone.compare_by_identity?]`, "[true, true]"},
// clone copies the singleton class, dup does not.
{`s = Set[1]; def s.hello = :hi
p [(s.clone.hello rescue :none), (s.dup.hello rescue :none)]`, "[:hi, :none]"},
// a subclass hook runs, and super fills the members.
{`k = Class.new(Set) { def initialize_copy(o) = (super; @copied = true) }
d = k.new([1]).dup; p [d.instance_variable_get(:@copied), d.to_a]`, "[true, [1]]"},
// a hook that skips super leaves the copy empty: the members arrive only
// through Set#initialize_copy.
{`k = Class.new(Set) { def initialize_copy(o) = nil }; p k.new([1]).dup.to_a`, "[]"},
{`p Set.private_instance_methods(false).include?(:initialize_copy)`, "true"},
// set_i_initialize_copy: a self-copy is a no-op returning self ...
{`s = Set[1, 2]; p [s.send(:initialize_copy, s).equal?(s), s.to_a]`, "[true, [1, 2]]"},
// ... returned BEFORE the iteration check, so it is allowed inside #each.
{`s = Set[1, 2]; s.each { s.send(:initialize_copy, s) }; p s.to_a`, "[1, 2]"},
// ... a replace during an iteration is refused ...
{`s = Set[1]
begin; s.each { s.send(:initialize_copy, Set[9]) }; rescue => e; p [e.class, e.message]; end`,
`[RuntimeError, "cannot replace set during iteration"]`},
// ... a non-Set source fails TypedData_Get_Struct ...
{`begin; Set[1].send(:initialize_copy, [1]); rescue => e; p [e.class, e.message]; end`,
`[TypeError, "wrong argument type Array (expected set)"]`},
// ... and a call replaces the members.
{`p Set[1].send(:initialize_copy, Set[5, 6]).to_a`, "[5, 6]"},
}
for _, c := range cases {
if got := runSrc(t, c.src); got != c.want {
t.Fatalf("src=%q got=%q want=%q", c.src, got, c.want)
}
}
}

// TestDupCopiesGenericIvars: init_copy runs rb_copy_generic_ivar on every dup and
// clone, so a value whose ivars live in the generic table (Array, String, Hash,
// Set) keeps them, in order, and the copy's table is its own.
func TestDupCopiesGenericIvars(t *testing.T) {
cases := []struct{ src, want string }{
{`r = [[1], +"s", {a: 1}, Set[1]].map { |o| o.instance_variable_set(:@x, 1); [o.dup.instance_variable_get(:@x), o.clone.instance_variable_get(:@x)] }
p r`, "[[1, 1], [1, 1], [1, 1], [1, 1]]"},
{`a = [1]; a.instance_variable_set(:@x, 1); a.instance_variable_set(:@y, 2)
d = a.dup; d.instance_variable_set(:@x, 9); p [a.instance_variable_get(:@x), d.instance_variables]`, "[1, [:@x, :@y]]"},
{`p [1].dup.instance_variables`, "[]"},
}
for _, c := range cases {
if got := runSrc(t, c.src); got != c.want {
t.Fatalf("src=%q got=%q want=%q", c.src, got, c.want)
}
}
}

// TestCopyGenericIvarsToImmediate: an immediate has no table, so a copy onto one
// is dropped rather than dereferencing a missing entry.
func TestCopyGenericIvarsToImmediate(t *testing.T) {
src := object.NewArrayFromSlice(nil)
setIvar(src, "@x", object.IntValue(1))
func() {
defer func() {
if r := recover(); r != nil {
t.Fatalf("copy onto an immediate must be dropped, got panic: %v", r)
}
}()
copyGenericIvars(src, object.IntValue(7))
}()
if got := getIvar(src, "@x"); got != object.IntValue(1) {
t.Fatalf("source ivar changed: %v", got)
}
}
Loading