Skip to content

Commit 1a810ac

Browse files
tannevaledclaude
andauthored
vm: Set#dup/#clone go through rb_obj_dup; dup copies generic ivars (#991)
Set overrode dup and clone with a function that built a bare Set, so a copy lost its instance variables, its singleton (clone), a user initialize_copy hook and clone(freeze:). set.c (v4.0.10, Init_Set) defines no dup or clone at all, only initialize_copy. The overrides are gone: - dupValue allocates an empty Set of the receiver's class; - Set#initialize_copy (private) ports set_i_initialize_copy: a self-copy returns at once, a replace during iteration raises RuntimeError, a non-Set source raises TypedData_Get_Struct's TypeError; - Object#dup / #clone copy the generic ivar table first, which is rb_copy_generic_ivar in init_copy (object.c). Without it, Array, String, Hash and Set lost every instance variable on dup and clone. Measured against MRI 4.0.10 with rubydiff: AGREE on every case except a frozen Set, which rbgo's Set cannot record at all yet (filed separately). Closes #866 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1f2727a commit 1a810ac

4 files changed

Lines changed: 157 additions & 13 deletions

File tree

‎internal/vm/builtins.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ func (vm *VM) bootstrap() {
237237
vm.cObject.define("dup", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
238238
cp := dupValue(self)
239239
if cp != self { // an immediate value dups to itself and skips the hook
240+
copyGenericIvars(self, cp)
240241
vm.send(cp, "initialize_dup", []object.Value{self}, nil)
241242
}
242243
return cp
@@ -269,6 +270,7 @@ func (vm *VM) bootstrap() {
269270
if cp == self { // an immediate value clones to itself
270271
return cp
271272
}
273+
copyGenericIvars(self, cp)
272274
vm.cloneSingleton(self, cp)
273275
if freezeGiven {
274276
kw := object.NewHash()
@@ -11402,6 +11404,11 @@ func dupValue(v object.Value) object.Value {
1140211404
copy(dup.structVals, x.structVals)
1140311405
}
1140411406
return dup
11407+
case *Set:
11408+
// rb_obj_dup allocates an EMPTY instance of the receiver's class; the
11409+
// members arrive through Set#initialize_copy (set_i_initialize_copy), so a
11410+
// subclass hook that skips super leaves the copy empty, as in MRI.
11411+
return &Set{h: object.NewHash(), cls: x.cls}
1140511412
case *BoundMethod:
1140611413
cp := *x
1140711414
cp.methodValueState = copyMethodState(x.methodValueState)

‎internal/vm/object_model.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ package vm
22

33
import (
44
"fmt"
5+
"maps"
56
"reflect"
67
"runtime"
8+
"slices"
79
"sort"
810
"strings"
911
"sync"
@@ -2248,6 +2250,34 @@ func genericIvarsOf(self object.Value, create bool) *genericIvars {
22482250
return g
22492251
}
22502252

2253+
// copyGenericIvars gives dst a copy of src's generic-table ivars, in their
2254+
// assignment order. It is rb_copy_generic_ivar, which init_copy (object.c) runs
2255+
// for every dup and clone before the initialize_copy hook: without it, an
2256+
// Array, String, Hash or Set lost every instance variable on dup/clone while an
2257+
// *RObject kept them (dupValue copies those). A source with no entry costs one
2258+
// lookup and creates nothing. Callers pass a fresh copy, never src itself; a dst
2259+
// with no identity (an immediate) has no table to receive them.
2260+
func copyGenericIvars(src, dst object.Value) {
2261+
g := genericIvarsOf(src, false)
2262+
if g == nil {
2263+
return
2264+
}
2265+
ivars, order := g.snapshot()
2266+
d := genericIvarsOf(dst, true)
2267+
if d == nil {
2268+
return
2269+
}
2270+
d.ivars, d.order = ivars, order
2271+
}
2272+
2273+
// snapshot copies g's map and order under the table lock, so a copy never shares
2274+
// storage with its source.
2275+
func (g *genericIvars) snapshot() (map[string]object.Value, []string) {
2276+
genericIvarMu.Lock()
2277+
defer genericIvarMu.Unlock()
2278+
return maps.Clone(g.ivars), slices.Clone(g.order)
2279+
}
2280+
22512281
// hasIdentity reports whether self is a reference. That is what the generic
22522282
// table needs of a key — an entry belongs to ONE object, and a copy of a Go
22532283
// struct value would answer to the entry of every equal copy — and it is the

‎internal/vm/set.go‎

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -247,19 +247,33 @@ func (vm *VM) registerSet() {
247247
return s
248248
})
249249

250-
// dup / clone: a shallow copy with the same members, insertion order and
251-
// compare_by_identity flag (ReplaceWith carries the flag across).
252-
// dup/clone keep the receiver's class, as MRI's rb_obj_dup does — and that
253-
// is also what carries it through `|`, which the prelude writes as
254-
// `n = dup; …` (prelude.rb:1247).
255-
dupFn := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value {
256-
n := newSet()
257-
n.cls = self(v).cls
258-
n.h.ReplaceWith(self(v).h)
259-
return n
260-
}
261-
d("dup", dupFn)
262-
d("clone", dupFn)
250+
// initialize_copy fills a copy's members from the original, which is the only
251+
// copy hook set.c defines (set_i_initialize_copy, Init_Set, v4.0.10): Set has
252+
// no dup or clone of its own. Object#dup / #clone allocate the copy (dupValue
253+
// keeps the class), carry the ivars, singleton and frozen state, and reach
254+
// this through initialize_dup / initialize_clone — so a subclass overriding
255+
// initialize_copy is honoured, as it is in MRI (#866). ReplaceWith carries the
256+
// insertion order and the compare_by_identity flag, as set_copy copies the
257+
// table with its type. Like set_i_initialize_copy, it skips a self-copy and
258+
// refuses to run during an iteration; it has no frozen check of its own.
259+
d("initialize_copy", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value {
260+
s := self(v)
261+
if args[0] == v {
262+
return v
263+
}
264+
if s.iterating > 0 {
265+
raise("RuntimeError", "cannot replace set during iteration")
266+
}
267+
// RSET_TABLE(other) goes through TypedData_Get_Struct, whose refusal
268+
// names the class and the data type's name, "set".
269+
orig, ok := args[0].(*Set)
270+
if !ok {
271+
raise("TypeError", "wrong argument type %s (expected set)", vm.classOf(args[0]).name)
272+
}
273+
s.h.ReplaceWith(orig.h)
274+
return v
275+
})
276+
vm.setInstanceVisibility(vm.cSet, "initialize_copy", visPrivate)
263277

264278
d("to_s", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value {
265279
return object.NewString(self(v).repr())

‎internal/vm/set_copy_test.go‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
// Copyright (c) the go-embedded-ruby/ruby authors
2+
//
3+
// SPDX-License-Identifier: BSD-3-Clause
4+
5+
package vm
6+
7+
import (
8+
"testing"
9+
10+
"github.com/go-embedded-ruby/ruby/internal/object"
11+
)
12+
13+
// TestSetDupClone pins Set#dup / #clone to MRI 4.0.10 (#866): Set defines no dup
14+
// or clone of its own, only initialize_copy (set.c Init_Set), so the copy goes
15+
// through rb_obj_dup / rb_obj_clone and keeps the subclass, the instance
16+
// variables, the singleton (clone only) and a user initialize_copy hook. The
17+
// expected values are MRI's output for the same programs.
18+
func TestSetDupClone(t *testing.T) {
19+
cases := []struct{ src, want string }{
20+
{`sub = Class.new(Set); s = sub.new([1, 2]); s.instance_variable_set(:@tag, 7)
21+
d = s.dup; c = s.clone
22+
p [d.class == sub, d.instance_variable_get(:@tag), d.to_a, c.class == sub, c.instance_variable_get(:@tag), c.to_a]`,
23+
"[true, 7, [1, 2], true, 7, [1, 2]]"},
24+
// the copy is independent of the original.
25+
{`s = Set[1, 2]; d = s.dup; d << 3; p [s.size, d.size]`, "[2, 3]"},
26+
// compare_by_identity survives both, as set_copy copies the table type.
27+
{`t = Set[1].compare_by_identity; p [t.dup.compare_by_identity?, t.clone.compare_by_identity?]`, "[true, true]"},
28+
// clone copies the singleton class, dup does not.
29+
{`s = Set[1]; def s.hello = :hi
30+
p [(s.clone.hello rescue :none), (s.dup.hello rescue :none)]`, "[:hi, :none]"},
31+
// a subclass hook runs, and super fills the members.
32+
{`k = Class.new(Set) { def initialize_copy(o) = (super; @copied = true) }
33+
d = k.new([1]).dup; p [d.instance_variable_get(:@copied), d.to_a]`, "[true, [1]]"},
34+
// a hook that skips super leaves the copy empty: the members arrive only
35+
// through Set#initialize_copy.
36+
{`k = Class.new(Set) { def initialize_copy(o) = nil }; p k.new([1]).dup.to_a`, "[]"},
37+
{`p Set.private_instance_methods(false).include?(:initialize_copy)`, "true"},
38+
// set_i_initialize_copy: a self-copy is a no-op returning self ...
39+
{`s = Set[1, 2]; p [s.send(:initialize_copy, s).equal?(s), s.to_a]`, "[true, [1, 2]]"},
40+
// ... returned BEFORE the iteration check, so it is allowed inside #each.
41+
{`s = Set[1, 2]; s.each { s.send(:initialize_copy, s) }; p s.to_a`, "[1, 2]"},
42+
// ... a replace during an iteration is refused ...
43+
{`s = Set[1]
44+
begin; s.each { s.send(:initialize_copy, Set[9]) }; rescue => e; p [e.class, e.message]; end`,
45+
`[RuntimeError, "cannot replace set during iteration"]`},
46+
// ... a non-Set source fails TypedData_Get_Struct ...
47+
{`begin; Set[1].send(:initialize_copy, [1]); rescue => e; p [e.class, e.message]; end`,
48+
`[TypeError, "wrong argument type Array (expected set)"]`},
49+
// ... and a call replaces the members.
50+
{`p Set[1].send(:initialize_copy, Set[5, 6]).to_a`, "[5, 6]"},
51+
}
52+
for _, c := range cases {
53+
if got := runSrc(t, c.src); got != c.want {
54+
t.Fatalf("src=%q got=%q want=%q", c.src, got, c.want)
55+
}
56+
}
57+
}
58+
59+
// TestDupCopiesGenericIvars: init_copy runs rb_copy_generic_ivar on every dup and
60+
// clone, so a value whose ivars live in the generic table (Array, String, Hash,
61+
// Set) keeps them, in order, and the copy's table is its own.
62+
func TestDupCopiesGenericIvars(t *testing.T) {
63+
cases := []struct{ src, want string }{
64+
{`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)] }
65+
p r`, "[[1, 1], [1, 1], [1, 1], [1, 1]]"},
66+
{`a = [1]; a.instance_variable_set(:@x, 1); a.instance_variable_set(:@y, 2)
67+
d = a.dup; d.instance_variable_set(:@x, 9); p [a.instance_variable_get(:@x), d.instance_variables]`, "[1, [:@x, :@y]]"},
68+
{`p [1].dup.instance_variables`, "[]"},
69+
}
70+
for _, c := range cases {
71+
if got := runSrc(t, c.src); got != c.want {
72+
t.Fatalf("src=%q got=%q want=%q", c.src, got, c.want)
73+
}
74+
}
75+
}
76+
77+
// TestCopyGenericIvarsToImmediate: an immediate has no table, so a copy onto one
78+
// is dropped rather than dereferencing a missing entry.
79+
func TestCopyGenericIvarsToImmediate(t *testing.T) {
80+
src := object.NewArrayFromSlice(nil)
81+
setIvar(src, "@x", object.IntValue(1))
82+
func() {
83+
defer func() {
84+
if r := recover(); r != nil {
85+
t.Fatalf("copy onto an immediate must be dropped, got panic: %v", r)
86+
}
87+
}()
88+
copyGenericIvars(src, object.IntValue(7))
89+
}()
90+
if got := getIvar(src, "@x"); got != object.IntValue(1) {
91+
t.Fatalf("source ivar changed: %v", got)
92+
}
93+
}

0 commit comments

Comments
 (0)