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: 4 additions & 3 deletions internal/vm/arith.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
174 changes: 145 additions & 29 deletions internal/vm/complex.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -258,24 +299,28 @@ 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 {
return raise("ArgumentError", "invalid value for convert(): %s", s.Inspect())
}
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}
}
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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{
Expand All @@ -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]
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
120 changes: 120 additions & 0 deletions internal/vm/numeric_residuals_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
Loading