From f5b15d2549b625f5c3f3d02cc3c08c21d027edac Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 1 Sep 2026 09:43:42 +0200 Subject: [PATCH 1/2] Complex/Rational: advance MRI 4.0.6 conformance Close the measurable gaps between rbgo and MRI 4.0.6 on core/complex and core/rational rubyspec: - Complex() / Complex.rectangular accept any real Numeric (including a user subclass of Numeric) and a zero-imaginary Complex component, via a shared realComponent helper, rather than only float-convertible values. - Complex#/ is a real method (routed through the operator) with #quo as its true alias sharing one Method record; same for Rational#/ and #quo, so Complex/Rational.instance_method(:quo) == instance_method(:/). - Complex#/ by a real (zero-imaginary) divisor divides each component directly, so /0.0 yields signed Infinity per component (not 0/0 NaN). - Complex#to_s / #inspect build the string from the parts' own #to_s / #inspect (sign from imag<0, trailing * before i for a non-digit tail) when a part is a Numeric subclass; built-in parts keep the exact object-level formatter (-0.0 / Infinity / NaN). - Rational#** (and Rational ** Float) return the principal Complex root when the base is negative and the exponent is not a whole number. - Complex#marshal_dump / Rational#marshal_dump (private) return [real, imag] / [numerator, denominator]; Marshal bytes unchanged. - arith.go (minimal, noted): Complex/Rational join Integer/Float/Bignum in the reflexive `==` case so `complex == obj` / `rational == obj` delegate to `obj == self` for a non-numeric right operand (MRI's Complex#== / Rational#==), keeping component-wise equality against a number. Co-Authored-By: Claude Opus 4.8 --- internal/vm/arith.go | 7 +- internal/vm/complex.go | 174 +++++++++++++++++++++++++++++++++------- internal/vm/rational.go | 38 +++++++-- 3 files changed, 180 insertions(+), 39 deletions(-) diff --git a/internal/vm/arith.go b/internal/vm/arith.go index f22090ef..acc7b535 100644 --- a/internal/vm/arith.go +++ b/internal/vm/arith.go @@ -253,10 +253,11 @@ func (vm *VM) binaryOp(op bytecode.Op, a, b object.Value) object.Value { // A built-in Integer/Float/Bignum compared against a non-numeric right // operand runs MRI's reflexive coercion: Numeric#== returns `other == self`, // so `1 == obj` dispatches obj's == (letting a user #== match a number). - // numeric-vs-numeric keeps the structural compare below; Complex/Rational - // keep their own component-wise equality (complexEqual/rationalEqual). + // numeric-vs-numeric keeps the structural compare below. Complex and Rational + // are in the switch too: their #== returns `other == self` for a non-number + // right operand, and keeps component-wise equality against a number. switch a.(type) { - case object.Integer, object.Float, *object.Bignum: + case object.Integer, object.Float, *object.Bignum, *object.Complex, *object.Rational: if !isNumericValue(b) { eq := vm.send(b, "==", []object.Value{a}, nil).Truthy() if op == bytecode.OpNeq { diff --git a/internal/vm/complex.go b/internal/vm/complex.go index ecdaae19..2a181b02 100644 --- a/internal/vm/complex.go +++ b/internal/vm/complex.go @@ -177,6 +177,40 @@ func asComplexVal(v object.Value) (*object.Complex, bool) { return nil, false } +// valueIsNumeric reports whether v is a Ruby Numeric — a built-in numeric value +// or an instance of a user subclass of Numeric (whose ancestry includes the +// Numeric class). MRI requires a Complex component to be a Numeric. +func (vm *VM) valueIsNumeric(v object.Value) bool { + if isNumericValue(v) { + return true + } + cNumeric := vm.cComplex.super // Complex < Numeric, so this is the Numeric class + for _, a := range vm.ancestors(vm.classOf(v)) { + if a == cNumeric { + return true + } + } + return false +} + +// realComponent validates and canonicalises a value used as a Complex real or +// imaginary part, following MRI: the value must be a real Numeric. A Complex +// whose imaginary part is zero contributes its real part; a Complex with a +// non-zero imaginary part, or any non-Numeric (or a Numeric answering #real? +// with false), is not a real. ok is false in those rejecting cases. +func (vm *VM) realComponent(v object.Value) (object.Value, bool) { + if c, ok := v.(*object.Complex); ok { + if imagNumericZero(c.Im) { + return c.Re, true + } + return nil, false + } + if vm.valueIsNumeric(v) && vm.send(v, "real?", nil, nil).Truthy() { + return v, true + } + return nil, false +} + // complexEqual reports Complex equality, including Complex(x, 0) == x. func complexEqual(c *object.Complex, other object.Value) bool { if oc, ok := other.(*object.Complex); ok { @@ -207,11 +241,18 @@ func complexOp(op bytecode.Op, a *object.Complex, b object.Value) object.Value { im := binary(bytecode.OpAdd, binary(bytecode.OpMul, a.Re, bc.Im), binary(bytecode.OpMul, a.Im, bc.Re)) return &object.Complex{Re: re, Im: im} case bytecode.OpDiv: + // A real divisor (imaginary part zero) divides each component directly, so + // dividing by a Float 0.0 gives ±Infinity per component with the correct + // sign (MRI's Complex(20, 40) / 0.0 == Complex(Infinity, Infinity)) rather + // than the 0/0 = NaN the general formula would produce. numQuo keeps + // Integer/Rational parts exact and raises ZeroDivisionError on an exact 0. + if imagNumericZero(bc.Im) { + return &object.Complex{Re: numQuo(a.Re, bc.Re), Im: numQuo(a.Im, bc.Re)} + } // (a+bi)/(c+di) = ((ac+bd) + (bc−ad)i)/(c²+d²). This stays exact on // Integer/Rational components (each final division is quo, so 3/2 becomes // Rational(3,2) rather than an integer floor) and drops to Float only when a - // Float component is present. A real integer 0 divisor raises - // ZeroDivisionError; a Float 0.0 divisor yields non-finite components. + // Float component is present. c, d := bc.Re, bc.Im den := binary(bytecode.OpAdd, binary(bytecode.OpMul, c, c), binary(bytecode.OpMul, d, d)) reNum := binary(bytecode.OpAdd, binary(bytecode.OpMul, a.Re, c), binary(bytecode.OpMul, a.Im, d)) @@ -258,7 +299,7 @@ func complexFloat(v object.Value) float64 { // first argument is the real part and an optional second the imaginary part, each // required to be a real number (a non-real part is a TypeError). Every failure // path raises, so the constructor can wrap it for exception: false. -func makeComplex(args []object.Value) object.Value { +func (vm *VM) makeComplex(args []object.Value) object.Value { if s, ok := args[0].(*object.String); ok && len(args) == 1 { c, ok := stringToC(s.Str(), true) if !ok { @@ -266,16 +307,20 @@ func makeComplex(args []object.Value) object.Value { } return c } - re := args[0] - im := object.Value(object.IntValue(0)) - if len(args) > 1 { - im = args[1] + // A lone Complex argument is returned unchanged (MRI's Complex(Complex(1,2))). + if c, ok := args[0].(*object.Complex); ok && len(args) == 1 { + return c } - if _, ok := toFloat(re); !ok { - return raise("TypeError", "can't convert %s into Complex", re.Inspect()) + re, ok := vm.realComponent(args[0]) + if !ok { + return raise("TypeError", "can't convert %s into Complex", vm.classOf(args[0]).name) } - if _, ok := toFloat(im); !ok { - return raise("TypeError", "can't convert %s into Complex", im.Inspect()) + im := object.Value(object.IntValue(0)) + if len(args) > 1 { + im, ok = vm.realComponent(args[1]) + if !ok { + return raise("TypeError", "not a real") + } } return &object.Complex{Re: re, Im: im} } @@ -284,7 +329,7 @@ func makeComplex(args []object.Value) object.Value { func (vm *VM) registerComplex() { vm.cObject.define("Complex", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { args, doRaise := popExceptionKwarg(args) - return vm.numericCtor(doRaise, func() object.Value { return makeComplex(args) }) + return vm.numericCtor(doRaise, func() object.Value { return vm.makeComplex(args) }) }) // Integer#to_c / Float#to_c wrap a real number as Complex(self, 0); String#to_c @@ -355,11 +400,11 @@ func (vm *VM) registerComplex() { return object.NewArray(mag, ang) }) - vm.cComplex.define("to_s", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return object.NewString(cval(self).ToS()) + vm.cComplex.define("to_s", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + return object.NewString(vm.complexFormat(cval(self), false)) }) - vm.cComplex.define("inspect", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return object.NewString(cval(self).Inspect()) + vm.cComplex.define("inspect", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + return object.NewString(vm.complexFormat(cval(self), true)) }) // A Complex is never real and never an integer, whatever its parts. @@ -427,6 +472,14 @@ func (vm *VM) registerComplex() { return object.NormInt(complexDenominator(cval(self))) }) + // marshal_dump is the private hook Marshal uses to serialise a Complex: the + // two-element [real, imaginary] array (MRI's Complex#marshal_dump). + vm.cComplex.define("marshal_dump", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + c := cval(self) + return object.NewArray(c.Re, c.Im) + }) + vm.setInstanceVisibility(vm.cComplex, "marshal_dump", visPrivate) + vm.cComplex.define("fdiv", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { c := cval(self) return &object.Complex{ @@ -446,9 +499,13 @@ func (vm *VM) registerComplex() { return raise("TypeError", "%s can't be coerced into Complex", vm.classOf(other).name) }) - vm.cComplex.define("quo", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - return vm.send(self, "/", []object.Value{args[0]}, nil) + // Complex#/ is a real method (so Complex.instance_method(:/) resolves) routed + // through the operator fast path, and #quo is its true alias, sharing the one + // Method record — Complex.instance_method(:quo) == Complex.instance_method(:/). + vm.cComplex.define("/", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + return vm.binaryOp(bytecode.OpDiv, self, args[0]) }) + vm.cComplex.methods["quo"] = vm.cComplex.methods["/"] vm.cComplex.define("**", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { exp := args[0] @@ -515,8 +572,8 @@ func (vm *VM) registerComplex() { } // Class constructors Complex.rectangular / .rect / .polar. - rectCtor := &Method{name: "rectangular", owner: vm.cComplex, native: func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - return complexRectangular(args) + rectCtor := &Method{name: "rectangular", owner: vm.cComplex, native: func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + return vm.complexRectangular(args) }} vm.cComplex.smethods["rectangular"] = rectCtor vm.cComplex.smethods["rect"] = rectCtor @@ -591,20 +648,79 @@ func complexNumerator(c *object.Complex) object.Value { } // complexRectangular builds Complex(re, im=0) from real arguments (MRI's -// Complex.rectangular), raising TypeError on a non-real part. -func complexRectangular(args []object.Value) object.Value { - re := args[0] +// Complex.rectangular), raising TypeError on a non-real part. A Complex argument +// whose imaginary part is zero contributes its real part (so +// Complex.rectangular(1.0+0i, 2+0.0i) == Complex(1.0, 2)); a non-zero imaginary +// part is not a real. +func (vm *VM) complexRectangular(args []object.Value) object.Value { + re, ok := vm.realComponent(args[0]) + if !ok { + return raise("TypeError", "not a real") + } im := object.Value(object.IntValue(0)) if len(args) > 1 { - im = args[1] + im, ok = vm.realComponent(args[1]) + if !ok { + return raise("TypeError", "not a real") + } } - if _, ok := toFloat(re); !ok { - return raise("TypeError", "not a real") + return &object.Complex{Re: re, Im: im} +} + +// complexFormat renders a Complex for #to_s (insp=false) or #inspect (insp=true). +// When both parts are plain built-in numbers the exact object-level formatter is +// used (it handles Float -0.0 / Infinity / NaN). Otherwise — a Numeric-subclass +// part — MRI builds the string from the parts' own #to_s / #inspect: the sign is +// taken from `imag < 0`, a trailing `*` is inserted before `i` when the +// imaginary string does not end in a digit, and inspect wraps the whole in +// parentheses. +func (vm *VM) complexFormat(c *object.Complex, insp bool) string { + if formattableComplexPart(c.Re) && formattableComplexPart(c.Im) { + if insp { + return c.Inspect() + } + return c.ToS() } - if _, ok := toFloat(im); !ok { - return raise("TypeError", "not a real") + meth := "to_s" + if insp { + meth = "inspect" } - return &object.Complex{Re: re, Im: im} + reStr := vm.strVal(vm.send(c.Re, meth, nil, nil)) + im := c.Im + sign := "+" + if vm.send(c.Im, "<", []object.Value{object.IntValue(0)}, nil).Truthy() { + sign = "-" + im = vm.send(c.Im, "-@", nil, nil) + } + imStr := vm.strVal(vm.send(im, meth, nil, nil)) + tail := "i" + if n := len(imStr); n == 0 || imStr[n-1] < '0' || imStr[n-1] > '9' { + tail = "*i" + } + s := reStr + sign + imStr + tail + if insp { + return "(" + s + ")" + } + return s +} + +// formattableComplexPart reports whether a Complex part is a built-in number the +// object-level formatter renders directly (Integer/Bignum/Float/Rational). +func formattableComplexPart(v object.Value) bool { + switch v.(type) { + case object.Integer, *object.Bignum, object.Float, *object.Rational: + return true + } + return false +} + +// strVal returns the Go string of a value expected to be a Ruby String (the +// result of #to_s / #inspect); a non-String falls back to its own inspect. +func (vm *VM) strVal(v object.Value) string { + if s, ok := v.(*object.String); ok { + return s.Str() + } + return v.Inspect() } // polarReal reads a real value for Complex.polar's modulus/argument: a real diff --git a/internal/vm/rational.go b/internal/vm/rational.go index 19f19006..83e2d254 100644 --- a/internal/vm/rational.go +++ b/internal/vm/rational.go @@ -3,6 +3,7 @@ package vm import ( "math" "math/big" + "math/cmplx" "github.com/go-embedded-ruby/ruby/internal/bytecode" "github.com/go-embedded-ruby/ruby/internal/object" @@ -179,7 +180,7 @@ func ratPow(ra, rb *big.Rat) object.Value { if !rb.IsInt() { af, _ := ra.Float64() bf, _ := rb.Float64() - return object.Float(math.Pow(af, bf)) + return realPow(af, bf) } e := rb.Num() base := ra @@ -201,6 +202,18 @@ func ratPow(ra, rb *big.Rat) object.Value { return &object.Rational{R: new(big.Rat).SetFrac(pn, pd)} } +// realPow raises the real base to the real exponent. A negative base with a +// non-whole exponent has no real value, so MRI returns the principal Complex +// root (exp(exp·ln base)); every other case yields a Float. This is why +// Rational(-3, 2) ** 1.5 and Rational(-3, 4) ** Rational(-4, 3) are Complex. +func realPow(base, exp float64) object.Value { + if base < 0 && exp != math.Trunc(exp) { + p := cmplx.Pow(complex(base, 0), complex(exp, 0)) + return &object.Complex{Re: object.Float(real(p)), Im: object.Float(imag(p))} + } + return object.Float(math.Pow(base, exp)) +} + // rationalEqual reports equality, coercing an Integer (Rational(2,1) == 2) or a // Float (Rational(1,2) == 0.5). func rationalEqual(r *object.Rational, other object.Value) bool { @@ -452,9 +465,9 @@ func (vm *VM) registerRational() { }) vm.cRational.define("**", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { r := rval(self).R - if ef, ok := args[0].(object.Float); ok { // Float exponent → Float result + if ef, ok := args[0].(object.Float); ok { // Float exponent rf, _ := r.Float64() - return object.Float(math.Pow(rf, float64(ef))) + return realPow(rf, float64(ef)) } eb, ok := toRat(args[0]) if !ok { @@ -521,11 +534,22 @@ func (vm *VM) registerRational() { return m }) - // quo is the exact-division alias of #/, routed through the operator so it - // picks up the same numeric-coercion protocol. - vm.cRational.define("quo", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - return vm.send(self, "/", []object.Value{args[0]}, nil) + // Rational#/ is a real method (so Rational.instance_method(:/) resolves) + // routed through the operator fast path, and #quo is its true alias sharing + // the one Method record — Rational.instance_method(:quo) == + // Rational.instance_method(:/). + vm.cRational.define("/", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + return vm.binaryOp(bytecode.OpDiv, self, args[0]) + }) + vm.cRational.methods["quo"] = vm.cRational.methods["/"] + + // marshal_dump is the private hook Marshal uses to serialise a Rational: the + // two-element [numerator, denominator] array (MRI's Rational#marshal_dump). + vm.cRational.define("marshal_dump", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + r := rval(self).R + return object.NewArray(object.NormInt(r.Num()), object.NormInt(r.Denom())) }) + vm.setInstanceVisibility(vm.cRational, "marshal_dump", visPrivate) vm.cRational.define("coerce", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { other := args[0] From 8d3a30117f95b36ccde4b462e4f0ca6407a30b7e Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 1 Sep 2026 09:52:17 +0200 Subject: [PATCH 2/2] test(vm): cover Complex/Rational conformance residuals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add internal/vm/numeric_residuals_test.go exercising every new branch: constructor acceptance of real Numerics and zero-imaginary Complex parts, #/ + #quo aliasing, real-divisor division (including /0.0 → Infinity), #to_s/#inspect over Numeric subclasses (sign, the `*i` tail, strVal fallback), negative-base fractional exponentiation, marshal_dump, and the reflexive #== fallback. All changed functions reach 100% coverage. Co-Authored-By: Claude Opus 4.8 --- internal/vm/numeric_residuals_test.go | 120 ++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 internal/vm/numeric_residuals_test.go diff --git a/internal/vm/numeric_residuals_test.go b/internal/vm/numeric_residuals_test.go new file mode 100644 index 00000000..9bbbde67 --- /dev/null +++ b/internal/vm/numeric_residuals_test.go @@ -0,0 +1,120 @@ +package vm_test + +import ( + "strings" + "testing" +) + +// TestComplexRationalResiduals covers the MRI 4.0.6 conformance work on +// core/complex and core/rational: construction accepting any real Numeric, +// #/ + #quo aliasing, real-divisor division, #to_s/#inspect over Numeric +// subclasses, negative-base fractional exponentiation, marshal_dump, and the +// reflexive #== fallback. +func TestComplexRationalResiduals(t *testing.T) { + // numeric subclass fixtures reused across cases: a formattable numeric whose + // parts drive #to_s / #inspect / sign / negation, a non-real numeric, and a + // numeric whose #to_s returns a non-String (to exercise the strVal fallback). + const prelude = ` +class MyNum < Numeric + def initialize(v); @v = v; end + def to_s; @v.to_s; end + def inspect; "<#{@v}>"; end + def <(o); @v < 0; end + def -@; MyNum.new(-@v); end +end +class NotReal < Numeric + def real?; false; end +end +class Weird < Numeric + def to_s; 5; end + def <(o); false; end +end +` + cases := []struct{ name, src, want string }{ + // --- constructors accept real Numerics / zero-imaginary Complex --- + {"ctor_string", `puts Complex("1+2i")`, "1+2i\n"}, + {"ctor_lone_complex", `puts Complex(Complex(1, 2))`, "1+2i\n"}, + {"ctor_real_parts", `puts Complex(1, 2)`, "1+2i\n"}, + {"ctor_subclass_parts", prelude + `c = Complex(MyNum.new(1), MyNum.new(2)); puts c.real.to_s; puts c.imag.to_s`, "1\n2\n"}, + {"rect_zero_imag_complex", `c = Complex.rectangular(Complex(1, 0), Complex(2, 0)); puts c.real; puts c.imag`, "1\n2\n"}, + {"rect_real", `c = Complex.rectangular(3, 4); puts c`, "3+4i\n"}, + + // --- #to_s / #inspect over built-ins and Numeric subclasses --- + {"to_s_builtin", `puts Complex(1, 2).to_s`, "1+2i\n"}, + {"inspect_builtin", `puts Complex(1, 2).inspect`, "(1+2i)\n"}, + {"to_s_neg_builtin", `puts Complex(1, -2).to_s`, "1-2i\n"}, + {"to_s_subclass", prelude + `puts Complex(MyNum.new(1), MyNum.new(2)).to_s`, "1+2i\n"}, + {"inspect_subclass_star", prelude + `puts Complex(MyNum.new(1), MyNum.new(2)).inspect`, "(<1>+<2>*i)\n"}, + {"to_s_subclass_neg", prelude + `puts Complex(MyNum.new(1), MyNum.new(-2)).to_s`, "1-2i\n"}, + {"to_s_strval_fallback", prelude + `puts Complex(Weird.new, Weird.new).to_s`, "5+5i\n"}, + + // --- division: real divisor divides each part; /0.0 → signed Infinity --- + {"div_real_exact", `puts Complex(4, 8) / 2`, "2+4i\n"}, + {"div_zero_infinity", `c = Complex(20, 40) / 0.0; puts c.real.infinite?; puts c.imag.infinite?`, "1\n1\n"}, + {"div_zero_neg", `puts((Complex(-20, 40) / 0.0).real.infinite?)`, "-1\n"}, + {"div_complex_divisor", `puts Complex(1, 1) / Complex(1, 1)`, "1+0i\n"}, + + // --- #/ is a real method with #quo as its true alias --- + {"complex_quo_is_div", `puts(Complex.instance_method(:quo) == Complex.instance_method(:/))`, "true\n"}, + {"complex_quo_call", `puts Complex(6, 0).quo(Complex(2, 0))`, "3+0i\n"}, + {"complex_div_send", `puts Complex(6, 0).send(:/, Complex(2, 0))`, "3+0i\n"}, + {"rational_quo_is_div", `puts(Rational.instance_method(:quo) == Rational.instance_method(:/))`, "true\n"}, + {"rational_quo_call", `puts Rational(1, 2).quo(Rational(1, 3))`, "3/2\n"}, + + // --- negative-base fractional exponent → principal Complex root --- + {"rat_pow_rat_complex", `x = Rational(-2, 1) ** Rational(1, 3); puts x.class`, "Complex\n"}, + {"rat_pow_float_complex", `x = Rational(-3, 2) ** 1.5; puts x.class; puts((x - Complex(0.0, -1.8371173070873836)).abs < 1e-6)`, "Complex\ntrue\n"}, + {"rat_pow_pos_float_real", `puts((Rational(3, 1) ** 1.5).class)`, "Float\n"}, + {"rat_pow_neg_int_float_real", `puts Rational(-2, 1) ** 2.0`, "4.0\n"}, + {"rat_pow_pos_rat_real", `puts((Rational(3, 4) ** Rational(4, 3)).class)`, "Float\n"}, + + // --- reflexive #== delegates to a non-numeric right operand --- + {"complex_eq_reflexive", `o = Object.new; def o.==(x); :yes; end; puts(Complex(3, 0) == o)`, "true\n"}, + {"complex_neq_reflexive", `o = Object.new; def o.==(x); true; end; puts(Complex(3, 0) != o)`, "false\n"}, + {"complex_eq_numeric", `puts(Complex(3, 0) == 3)`, "true\n"}, + {"rational_eq_reflexive", `o = Object.new; def o.==(x); :yes; end; puts(Rational(3, 4) == o)`, "true\n"}, + {"rational_eq_numeric", `puts(Rational(4, 2) == 2)`, "true\n"}, + + // --- marshal_dump (private) returns the component array --- + {"complex_marshal_dump", `p Complex(1, 2).send(:marshal_dump)`, "[1, 2]\n"}, + {"rational_marshal_dump", `p Rational(3, 4).send(:marshal_dump)`, "[3, 4]\n"}, + {"complex_marshal_private", `puts Complex.private_instance_methods(false).include?(:marshal_dump)`, "true\n"}, + {"complex_marshal_roundtrip", `puts Marshal.load(Marshal.dump(Complex(1, 2)))`, "1+2i\n"}, + {"rational_marshal_roundtrip", `puts Marshal.load(Marshal.dump(Rational(3, 4)))`, "3/4\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) + } + }) + } +} + +// TestComplexRationalResidualErrors covers the raising branches of the +// constructors and rectangular: a non-real component is a TypeError, an invalid +// Complex string is an ArgumentError. +func TestComplexRationalResidualErrors(t *testing.T) { + const prelude = ` +class NotReal < Numeric + def real?; false; end +end +` + cases := []struct{ name, src, want string }{ + {"ctor_symbol", `Complex(:sym)`, "TypeError"}, + {"ctor_imag_symbol", `Complex(1, :sym)`, "TypeError"}, + {"ctor_not_real_numeric", prelude + `Complex(NotReal.new)`, "TypeError"}, + {"ctor_invalid_string", `Complex("not a number!")`, "ArgumentError"}, + {"rect_nonzero_imag_complex", `Complex.rectangular(Complex(1, 1), 2)`, "TypeError"}, + {"rect_imag_nonzero_complex", `Complex.rectangular(1, Complex(2, 3))`, "TypeError"}, + {"rect_symbol", `Complex.rectangular(:sym)`, "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.want) { + t.Errorf("src=%q: got err=%v, want containing %q", tc.src, err, tc.want) + } + }) + } +}