From 66eb778f2b0ecf8dfbecfd50d0672cb6c2299a08 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 08:28:25 +0200 Subject: [PATCH 1/2] Kernel: proper Array()/String()/Hash() conversion protocol, frozen numerics, singleton freeze Kernel#Array now follows MRI's rb_Array: #to_ary then #to_a (each may decline with nil), a non-Array result is a TypeError, and only an unconvertible value is wrapped as [v]. Kernel#Hash is newly defined (nil/empty-Array to {}, #to_hash otherwise, TypeError on failure) and registered as a module_function. Kernel#String returns a String/String-subclass untouched (no #to_s), honours an overridden #respond_to?(:to_s) that hides an existing #to_s, and turns a NoMethodError from a missing #to_s into a TypeError while still allowing a #method_missing answer. isFrozen now reports Bignum, Complex and Rational as frozen (immutable value objects), and Object#freeze also freezes an already-materialised singleton class. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 105 ++++++++++++++- internal/vm/kernel_residuals_test.go | 192 +++++++++++++++++++++++++++ 2 files changed, 290 insertions(+), 7 deletions(-) create mode 100644 internal/vm/kernel_residuals_test.go diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index e8a755d1..d7dff520 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -214,6 +214,11 @@ func (vm *VM) bootstrap() { o.Frozen = true case *RObject: o.frozen = true + // Freezing an object also freezes an already-materialised singleton + // class, matching MRI (a lazily-created one stays unfrozen until used). + if o.singleton != nil { + o.singleton.frozen = true + } case *RClass: o.frozen = true } @@ -1023,17 +1028,82 @@ func (vm *VM) bootstrap() { return fail("TypeError", "can't convert %s into Float", vm.convErrName(other)) }) vm.cObject.define("String", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - return vm.send(args[0], "to_s", nil, nil) + v := args[0] + // A String (or String-subclass instance) is returned as-is: #to_s is not + // called, matching MRI's rb_check_string_type shortcut. + if classIsA(vm.classOf(v), vm.cString) { + return v + } + // An overridden #respond_to? that answers false for :to_s hides an existing + // #to_s, so no conversion is attempted — MRI raises TypeError. + respondsToS := vm.send(v, "respond_to?", []object.Value{object.Symbol("to_s")}, nil).Truthy() + if !respondsToS && vm.findMethod(v, "to_s") != nil { + raise("TypeError", "can't convert %s into String", vm.convErrName(v)) + } + // Call #to_s. When it is undefined (and only the default #method_missing is + // present) the dispatch raises NoMethodError, which rb_String turns into a + // TypeError; a #method_missing that answers instead yields its value. + r, ok := vm.stringConvToS(v) + if !ok { + raise("TypeError", "can't convert %s into String", vm.convErrName(v)) + } + if classIsA(vm.classOf(r), vm.cString) { + return r + } + raise("TypeError", "can't convert %s to String (%s#to_s gives %s)", + vm.convErrName(v), vm.convErrName(v), vm.classOf(r).name) + return object.NilV }) - vm.cObject.define("Array", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + vm.cObject.define("Array", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + // A real Array is returned untouched — neither #to_ary nor #to_a is called. + if a, ok := args[0].(*object.Array); ok { + return a + } + v := args[0] + // #to_ary first (private included), then #to_a, mirroring MRI's rb_Array: + // each may return nil to decline; a non-Array, non-nil result is a + // TypeError; if neither yields an Array, the argument is wrapped as [v]. + for _, conv := range []string{"to_ary", "to_a"} { + if !vm.respondsToDynamic(v, conv) { + continue + } + r := vm.send(v, conv, nil, nil) + if object.IsNil(r) { + continue + } + if a, ok := r.(*object.Array); ok { + return a + } + raise("TypeError", "can't convert %s to Array (%s#%s gives %s)", + vm.convErrName(v), vm.convErrName(v), conv, vm.classOf(r).name) + } + return object.NewArray(v) + }) + vm.cObject.define("Hash", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + // A real Hash is returned untouched; nil and an empty Array both become {} + // (MRI's special cases). Otherwise #to_hash converts, and anything that + // neither is a Hash nor answers #to_hash with one is a TypeError. switch v := args[0].(type) { + case *object.Hash: + return v case object.Nil: - return object.NewArray() + return object.NewHash() case *object.Array: - return v - default: - return object.NewArray(v) + if len(v.Elems) == 0 { + return object.NewHash() + } + } + v := args[0] + if vm.respondsToDynamic(v, "to_hash") { + r := vm.send(v, "to_hash", nil, nil) + if h, ok := r.(*object.Hash); ok { + return h + } + raise("TypeError", "can't convert %s to Hash (%s#to_hash gives %s)", + vm.convErrName(v), vm.convErrName(v), vm.classOf(r).name) } + raise("TypeError", "can't convert %s into Hash", vm.convErrName(v)) + return object.NilV }) sendFn := func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { return vm.send(self, vm.methodNameArg(args[0]), args[1:], blk) @@ -5455,7 +5525,7 @@ func (vm *VM) bootstrap() { // simply skipped. Runs after every listed method is registered. func (vm *VM) registerKernelModuleFunctions() { names := []string{ - "Array", "Complex", "Float", "Integer", "Rational", "String", + "Array", "Complex", "Float", "Hash", "Integer", "Rational", "String", "__dir__", "abort", "at_exit", "autoload", "autoload?", "caller", "catch", "eval", "exec", "exit", "exit!", "fork", "format", "lambda", "load", "loop", "open", "p", "print", "printf", "proc", "puts", @@ -7540,6 +7610,24 @@ func (vm *VM) integerArg(v object.Value) *big.Int { // the named conversion method (#to_ary/#to_hash/#to_str/#to_int), that is called // and its result must be nil or a kind of target — anything else is a TypeError. // An object that does not respond to the conversion method yields nil. +// stringConvToS calls #to_s on v for Kernel#String, returning (result, true). A +// NoMethodError — v has no usable #to_s (e.g. it was undef'd and only the +// default #method_missing remains) — is reported as ok=false so the caller +// raises the TypeError that MRI's rb_String produces, rather than letting the +// NoMethodError escape. Any other exception propagates unchanged. +func (vm *VM) stringConvToS(v object.Value) (res object.Value, ok bool) { + defer func() { + if r := recover(); r != nil { + if re, isRE := r.(RubyError); isRE && re.Class == "NoMethodError" { + res, ok = object.NilV, false + return + } + panic(r) + } + }() + return vm.send(v, "to_s", nil, nil), true +} + func (vm *VM) tryConvert(obj object.Value, target *RClass, meth string) object.Value { if classIsA(vm.classOf(obj), target) { return obj @@ -8633,6 +8721,9 @@ func isFrozen(v object.Value) bool { switch x := v.(type) { case object.Integer, object.Float, object.Symbol, object.Bool, object.Nil: return true + case *object.Bignum, *object.Complex, *object.Rational: + // Numeric value objects are immutable in Ruby, hence always frozen. + return true case *object.String: return x.Frozen case *object.Array: diff --git a/internal/vm/kernel_residuals_test.go b/internal/vm/kernel_residuals_test.go new file mode 100644 index 00000000..44ea587f --- /dev/null +++ b/internal/vm/kernel_residuals_test.go @@ -0,0 +1,192 @@ +package vm_test + +import ( + "strings" + "testing" +) + +// TestKernelArrayConversion covers Kernel#Array's MRI protocol: the real-Array +// shortcut, the #to_ary-then-#to_a chain (each may decline with nil), the +// single-element wrap when neither yields an Array, and the TypeError raised +// when a conversion returns a non-Array. +func TestKernelArrayConversion(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"real_array", `p Array([1, 2, 3])`, "[1, 2, 3]\n"}, + {"nil", `p Array(nil)`, "[]\n"}, + {"to_ary", ` +class A1; def to_ary; [1, 2]; end; end +p Array(A1.new)`, "[1, 2]\n"}, + {"to_ary_nil_then_to_a", ` +class A2; def to_ary; nil; end; def to_a; [3, 4]; end; end +p Array(A2.new)`, "[3, 4]\n"}, + {"to_a", ` +class A3; def to_a; [5, 6]; end; end +p Array(A3.new)`, "[5, 6]\n"}, + {"to_a_nil_wraps", ` +class A4; def to_a; nil; end; end +o = A4.new +p Array(o) == [o]`, "true\n"}, + {"private_to_ary", ` +class A5; private def to_ary; [7, 8]; end; end +p Array(A5.new)`, "[7, 8]\n"}, + {"wrap_plain", `o = Object.new; p Array(o) == [o]`, "true\n"}, + } + for _, tc := range cases { + 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) + } + }) + } +} + +func TestKernelArrayConversionErrors(t *testing.T) { + cases := []struct{ name, src string }{ + {"to_ary_non_array", ` +class B1; def to_ary; "x"; end; end +Array(B1.new)`}, + {"to_a_non_array", ` +class B2; def to_a; "x"; end; end +Array(B2.new)`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("src=%q: want TypeError, got %v", tc.src, err) + } + }) + } +} + +// TestKernelHashConversion covers Kernel#Hash: the real-Hash shortcut, nil and +// empty-Array to {}, #to_hash conversion, and the TypeErrors for a missing or +// non-Hash-returning #to_hash. +func TestKernelHashConversion(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"real_hash", `p Hash({a: 1})`, "{a: 1}\n"}, + {"nil", `p Hash(nil)`, "{}\n"}, + {"empty_array", `p Hash([])`, "{}\n"}, + {"to_hash", ` +class H1; def to_hash; {b: 2}; end; end +p Hash(H1.new)`, "{b: 2}\n"}, + } + for _, tc := range cases { + 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) + } + }) + } +} + +func TestKernelHashConversionErrors(t *testing.T) { + cases := []struct{ name, src string }{ + {"no_to_hash", `Hash(Object.new)`}, + {"to_hash_non_hash", ` +class H2; def to_hash; "x"; end; end +Hash(H2.new)`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("src=%q: want TypeError, got %v", tc.src, err) + } + }) + } +} + +// TestKernelStringConversion covers Kernel#String: the String / String-subclass +// shortcut (no #to_s call), the ordinary #to_s conversion, and the +// #method_missing path where #to_s is undef'd but answered dynamically. +func TestKernelStringConversion(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"nil", `p String(nil)`, "\"\"\n"}, + {"float", `p String(1.12)`, "\"1.12\"\n"}, + {"bool", `p String(false)`, "\"false\"\n"}, + {"constant", `p String(Object)`, "\"Object\"\n"}, + {"to_s", ` +class S1; def to_s; "hi"; end; end +p String(S1.new)`, "\"hi\"\n"}, + {"same_object", `s = +"x"; p String(s).equal?(s)`, "true\n"}, + {"subclass", ` +sub = Class.new(String) +s = sub.new("y") +p String(s).equal?(s)`, "true\n"}, + {"method_missing", ` +o = Object.new +class << o + undef_method :to_s + def method_missing(m, *a); m == :to_s ? "mm" : super; end +end +p String(o)`, "\"mm\"\n"}, + } + for _, tc := range cases { + 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) + } + }) + } +} + +func TestKernelStringConversionErrors(t *testing.T) { + cases := []struct{ name, src, wantClass string }{ + {"undef_to_s", ` +o = Object.new +class << o; undef_method :to_s; end +String(o)`, "TypeError"}, + {"respond_to_false", ` +o = Object.new +class << o + def respond_to?(m, ip = false); m == :to_s ? false : super; end +end +String(o)`, "TypeError"}, + {"respond_to_true_but_undef", ` +o = Object.new +class << o + undef_method :to_s + def respond_to?(m, ip = false); m == :to_s ? true : super; end +end +String(o)`, "TypeError"}, + {"to_s_non_string", ` +class S2; def to_s; 123; end; end +String(S2.new)`, "TypeError"}, + {"to_s_raises_other", ` +class S3; def to_s; raise ArgumentError, "boom"; end; end +String(S3.new)`, "ArgumentError"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.wantClass) { + t.Errorf("src=%q: want %s, got %v", tc.src, tc.wantClass, err) + } + }) + } +} + +// TestKernelNumericFrozen covers that Bignum, Complex and Rational report as +// frozen (immutable value objects), alongside the singleton-class freezing that +// Object#freeze performs. +func TestKernelNumericFrozen(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"bignum", `p (2 ** 70).frozen?`, "true\n"}, + {"complex", `p Complex(1, 2).frozen?`, "true\n"}, + {"rational", `p Rational(1, 2).frozen?`, "true\n"}, + {"freeze_singleton", ` +o = Object.new +c = o.singleton_class +before = c.frozen? +o.freeze +p [before, c.frozen?]`, "[false, true]\n"}, + } + for _, tc := range cases { + 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 2a912af38750dfbde9564433fa557ce7f4e2568c Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 4 Sep 2026 08:42:08 +0200 Subject: [PATCH 2/2] Kernel#dup/#clone: initialize_copy hooks, clone freeze: kwarg and singleton copy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dup now runs #initialize_dup (which delegates to #initialize_copy) on the shallow copy; clone runs #initialize_clone, copies the frozen state (a freeze: true/false/nil keyword overrides it and is forwarded to #initialize_clone, an invalid value or unknown keyword raising ArgumentError), and clones the singleton class so per-object methods, singleton-included modules and singleton constants carry over — for both an *RObject inline singleton and the side-table singleton of an Array/Hash/String. Adds the default private Kernel copy hooks #initialize_copy (same-object no-op, FrozenError on a frozen receiver, TypeError across classes), #initialize_dup and #initialize_clone, and preserves instance-variable order across dupValue. Fixes core/kernel dup, clone, initialize_copy/dup/clone specs to full MRI parity (clone 18->30) and core/array clone singleton copy. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 133 ++++++++++++++++++++++++++- internal/vm/kernel_residuals_test.go | 68 ++++++++++++++ 2 files changed, 197 insertions(+), 4 deletions(-) diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index d7dff520..a7aa06a2 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -199,11 +199,91 @@ func (vm *VM) bootstrap() { // proc{}.curry.lambda? is false. return vm.curriedProc(p, need, p.isLambda, nil) }) - dupFn := func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return dupValue(self) + // dup makes a shallow copy and runs #initialize_dup (→ #initialize_copy) on it; + // unlike clone it copies neither the frozen state nor the singleton class. + 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 + vm.send(cp, "initialize_dup", []object.Value{self}, nil) + } + return cp + }) + // clone additionally copies the singleton class and the frozen state, and runs + // #initialize_clone. A freeze: keyword (true/false/nil) overrides the copied + // frozen state and is forwarded to #initialize_clone; anything else is an error. + vm.cObject.define("clone", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + freezeVal, freezeGiven := object.Value(object.NilV), false + if len(args) > 0 { + if h, ok := args[len(args)-1].(*object.Hash); ok { + for _, k := range h.Keys { + if sym, isSym := k.(object.Symbol); isSym && sym == object.Symbol("freeze") { + freezeVal, _ = h.Get(k) + freezeGiven = true + continue + } + raise("ArgumentError", "unknown keyword: %s", k.Inspect()) + } + } + } + if freezeGiven { + switch freezeVal.(type) { + case object.Bool, object.Nil: + default: + raise("ArgumentError", "unexpected value for freeze: %s", vm.classOf(freezeVal).name) + } + } + cp := dupValue(self) + if cp == self { // an immediate value clones to itself + return cp + } + vm.cloneSingleton(self, cp) + if freezeGiven { + kw := object.NewHash() + kw.Set(object.Symbol("freeze"), freezeVal) + vm.send(cp, "initialize_clone", []object.Value{self, kw}, nil) + } else { + vm.send(cp, "initialize_clone", []object.Value{self}, nil) + } + // freeze: true/false wins; freeze: nil or no keyword copies the original's + // frozen state. + doFreeze := isFrozen(self) + if b, ok := freezeVal.(object.Bool); ok { + doFreeze = bool(b) + } + if doFreeze { + vm.send(cp, "freeze", nil, nil) + } + return cp + }) + // initialize_copy/dup/clone are Kernel's private copy hooks. The default + // initialize_copy validates the receiver (frozen / same-class) and is a no-op + // otherwise; initialize_dup and initialize_clone delegate to it and return self. + vm.cKernel.define("initialize_copy", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + orig := args[0] + if self == orig { // copying from itself does nothing (even when frozen) + return self + } + if isFrozen(self) { + vm.raiseFrozen(self) + } + if vm.classOf(self) != vm.classOf(orig) { + raise("TypeError", "initialize_copy should take same class object") + } + return self + }) + vm.cKernel.define("initialize_dup", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + vm.send(self, "initialize_copy", []object.Value{args[0]}, nil) + return self + }) + vm.cKernel.define("initialize_clone", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + // A trailing freeze: keyword (from clone(freeze:)) is accepted and ignored + // by the default hook; the positional original is always args[0]. + vm.send(self, "initialize_copy", []object.Value{args[0]}, nil) + return self + }) + for _, n := range []string{"initialize_copy", "initialize_dup", "initialize_clone"} { + vm.setInstanceVisibility(vm.cKernel, n, visPrivate) } - vm.cObject.define("dup", dupFn) - vm.cObject.define("clone", dupFn) vm.cObject.define("freeze", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { switch o := self.(type) { case *object.String: @@ -8677,6 +8757,46 @@ func (vm *VM) defineAttrs(cls *RClass, names []object.Value, reader, writer bool // dupValue shallow-copies a value (Object#dup/#clone). Reference types get a // fresh container with the same elements; immutable value types are their own // copy. +// cloneSingleton gives dst a fresh copy of src's singleton class, when src has +// one, so Object#clone carries over per-object methods, singleton-included +// modules and singleton constants (MRI clones the metaclass). It handles both an +// *RObject's inline singleton and the side-table singleton of a reference value +// (Array/Hash/String). The copied methods are re-owned by the new singleton so +// `super` still resolves up the object's class chain, and the new singleton's +// superclass is dst's class. +func (vm *VM) cloneSingleton(src, dst object.Value) { + sc := vm.objSingleton(src) + if sc == nil { + return + } + ns := newClass("", vm.classOf(dst)) + ns.isSingleton = true + for name, m := range sc.methods { + cp := *m + cp.owner = ns + ns.methods[name] = &cp + } + ns.includes = append(ns.includes, sc.includes...) + ns.prepends = append(ns.prepends, sc.prepends...) + for name, val := range sc.consts { + ns.consts[name] = val + } + if sc.visOverrides != nil { + ns.visOverrides = make(map[string]visibility, len(sc.visOverrides)) + for name, vis := range sc.visOverrides { + ns.visOverrides[name] = vis + } + } + if do, ok := dst.(*RObject); ok { + do.singleton = ns + return + } + if vm.extSingletons == nil { + vm.extSingletons = map[object.Value]*RClass{} + } + vm.extSingletons[dst] = ns +} + func dupValue(v object.Value) object.Value { switch x := v.(type) { case *object.String: @@ -8702,6 +8822,11 @@ func dupValue(v object.Value) object.Value { ivars[k] = val } dup := &RObject{class: x.class, ivars: ivars} + // Preserve instance-variable insertion order so the copy's + // #instance_variables (and #inspect) match the original's ordering. + if x.ivarOrder != nil { + dup.ivarOrder = append([]string(nil), x.ivarOrder...) + } // A Struct instance carries its members in structVals (not ivars), so the // copy must clone that slice too or the duplicate would report all-nil // members (and Struct#hash/#== would diverge from the original). diff --git a/internal/vm/kernel_residuals_test.go b/internal/vm/kernel_residuals_test.go index 44ea587f..99b69909 100644 --- a/internal/vm/kernel_residuals_test.go +++ b/internal/vm/kernel_residuals_test.go @@ -167,6 +167,74 @@ String(S3.new)`, "ArgumentError"}, } } +// TestKernelDupClone covers Object#dup / Object#clone: the #initialize_copy hook +// (via #initialize_dup / #initialize_clone), clone's frozen-state and singleton +// copying, and the freeze: keyword handling. +func TestKernelDupClone(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"dup_immediate", `p 1.dup`, "1\n"}, + {"clone_immediate", `p 1.clone`, "1\n"}, + {"dup_calls_initialize_copy", ` +class D1 + attr_accessor :obj + def initialize; @obj = :orig; end + def initialize_copy(o); @obj = :copied; end +end +p D1.new.dup.obj`, ":copied\n"}, + {"dup_not_frozen", `p [1].freeze.dup.frozen?`, "false\n"}, + {"clone_copies_frozen", `p [1].freeze.clone.frozen?`, "true\n"}, + {"clone_freeze_false", `p [1].freeze.clone(freeze: false).frozen?`, "false\n"}, + {"clone_freeze_true", `p [1].clone(freeze: true).frozen?`, "true\n"}, + {"clone_freeze_nil", `p [1].freeze.clone(freeze: nil).frozen?`, "true\n"}, + {"clone_singleton_method", ` +o = Object.new +def o.special; :yes; end +p o.clone.special`, ":yes\n"}, + {"clone_singleton_on_array", ` +a = [1, 2] +def a.tag; :t; end +p a.clone.tag`, ":t\n"}, + {"clone_no_singleton", `p Object.new.clone.class`, "Object\n"}, + {"initialize_clone_kwargs", ` +class CF + def initialize_clone(other, **kw); @rec = kw; end + attr_reader :rec +end +p CF.new.clone(freeze: true).rec`, "{freeze: true}\n"}, + {"initialize_copy_same", `o = Object.new; p o.send(:initialize_copy, o).equal?(o)`, "true\n"}, + {"initialize_dup_returns_self", `a = Object.new; p a.send(:initialize_dup, Object.new).equal?(a)`, "true\n"}, + {"initialize_clone_returns_self", `a = Object.new; p a.send(:initialize_clone, Object.new).equal?(a)`, "true\n"}, + {"initialize_clone_freeze_kw", `a = Object.new; p a.send(:initialize_clone, Object.new, freeze: true).equal?(a)`, "true\n"}, + } + for _, tc := range cases { + 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) + } + }) + } +} + +func TestKernelDupCloneErrors(t *testing.T) { + cases := []struct{ name, src, wantClass string }{ + {"clone_freeze_bad", `Object.new.clone(freeze: 1)`, "ArgumentError"}, + {"clone_unknown_kw", `Object.new.clone(foo: 1)`, "ArgumentError"}, + {"initialize_copy_frozen", `Object.new.freeze.send(:initialize_copy, Object.new)`, "FrozenError"}, + {"initialize_copy_diff_class", ` +klass = Class.new +sub = Class.new(klass) +klass.new.send(:initialize_copy, sub.new)`, "TypeError"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.wantClass) { + t.Errorf("src=%q: want %s, got %v", tc.src, tc.wantClass, err) + } + }) + } +} + // TestKernelNumericFrozen covers that Bignum, Complex and Rational report as // frozen (immutable value objects), alongside the singleton-class freezing that // Object#freeze performs.