diff --git a/internal/vm/arith.go b/internal/vm/arith.go index acc7b535..258a59d7 100644 --- a/internal/vm/arith.go +++ b/internal/vm/arith.go @@ -191,8 +191,11 @@ func intFloatCompare(op bytecode.Op, a *big.Int, f float64, floatLeft bool) obje } // bigOp performs an arbitrary-precision integer operation, normalizing the -// result back to an Integer when it fits. big.Int Div/Mod are Euclidean, which -// matches Ruby's floored division (a non-negative modulus). +// result back to an Integer when it fits. Ruby's division is floored: the +// modulo takes the sign of the divisor, so a negative divisor gives a +// non-positive modulo (13 % -4 == -3), unlike big.Int's Euclidean Div/Mod +// (which always give a non-negative remainder). bigFloorDivmod supplies the +// floored quotient and remainder for both signs. func bigOp(op bytecode.Op, a, b *big.Int) object.Value { switch op { case bytecode.OpAdd: @@ -205,12 +208,14 @@ func bigOp(op bytecode.Op, a, b *big.Int) object.Value { if b.Sign() == 0 { raise("ZeroDivisionError", "divided by 0") } - return object.NormInt(new(big.Int).Div(a, b)) + q, _ := bigFloorDivmod(a, b) + return object.NormInt(q) case bytecode.OpMod: if b.Sign() == 0 { raise("ZeroDivisionError", "divided by 0") } - return object.NormInt(new(big.Int).Mod(a, b)) + _, r := bigFloorDivmod(a, b) + return object.NormInt(r) case bytecode.OpLt: return object.Bool(a.Cmp(b) < 0) case bytecode.OpGt: @@ -580,7 +585,13 @@ func floatOp(op bytecode.Op, a, b float64) object.Value { case bytecode.OpDiv: return object.Float(a / b) // matches Ruby: 1.0/0 => Infinity case bytecode.OpMod: - return object.Float(floatMod(a, b)) + // Ruby's Float#% raises on a zero divisor (unlike C fmod) and, for a + // non-finite divisor or a signed zero, follows ruby_float_mod rather than + // a plain remainder (4.2 % Infinity is 4.2, -0.0 % 42 is -0.0). + if b == 0 { + raise("ZeroDivisionError", "divided by 0") + } + return object.Float(rubyFloatMod(a, b)) case bytecode.OpLt: return object.Bool(a < b) case bytecode.OpGt: @@ -1297,11 +1308,3 @@ func floorMod(a, b int64) int64 { } return m } - -func floatMod(a, b float64) float64 { - m := a - b*float64(int64(a/b)) - if m != 0 && ((m < 0) != (b < 0)) { - m += b - } - return m -} diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 1f3b935a..e8a755d1 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -5079,45 +5079,10 @@ func (vm *VM) bootstrap() { a, _ := object.BigOf(self) return object.NormInt(bigLCM(a, integerGcdArg(args[0]))) }) - fdiv := func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - a, _ := toFloat(self) - b, ok := toFloat(args[0]) - if !ok { - // MRI names the receiver's class in the coercion error (Integer#fdiv - // reports "into Integer", Float#fdiv "into Float"). - raise("TypeError", "%s can't be coerced into %s", vm.classOf(args[0]).name, vm.classOf(self).name) - } - return object.Float(a / b) - } - vm.cInteger.define("fdiv", fdiv) - vm.cFloat.define("fdiv", fdiv) - coerce := func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - other := args[0] - _, selfInt := self.(object.Integer) - _, otherInt := other.(object.Integer) - if selfInt && otherInt { - return object.NewArray(other, self) - } - sf, _ := toFloat(self) // self is always numeric here - of, ok := toFloat(other) - if !ok { // MRI coerces via Float(other), so mirror its errors - if s, isStr := other.(*object.String); isStr { - raise("ArgumentError", "invalid value for Float(): %s", s.Inspect()) - } - // MRI names nil/true/false by value, everything else by class. - name := vm.classOf(other).name - switch other.(type) { - case object.Nil: - name = "nil" - case object.Bool: - name = other.ToS() - } - raise("TypeError", "can't convert %s into Float", name) - } - return object.NewArray(object.Float(of), object.Float(sf)) - } - vm.cInteger.define("coerce", coerce) - vm.cFloat.define("coerce", coerce) + // Integer#fdiv / Float#fdiv and Integer#coerce / Float#coerce are defined in + // registerNumericEdges (numeric_edges.go), which runs after this and supersedes + // them with MRI-exact versions; only the shared Numeric#coerce fallback lives + // here now. // Numeric#coerce is the generic fallback a Numeric subclass inherits (Integer // and Float override it above): same-class returns [other, self] unchanged, // otherwise both are converted with Kernel#Float (dispatching #to_f, and @@ -5132,18 +5097,8 @@ func (vm *VM) bootstrap() { of := vm.send(vm.main, "Float", []object.Value{other}, nil) return object.NewArray(of, sf) }) - vm.cInteger.define("bit_length", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - n := intOf(self) - if n < 0 { - n = ^n - } - var c int64 - for n > 0 { - c++ - n >>= 1 - } - return object.IntValue(c) - }) + // Integer#bit_length is defined in registerNumericEdges (numeric_edges.go), + // which handles Bignums; the fixnum-only version that was here is superseded. vm.cInteger.define("divmod", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { return vm.integerDivmod(self, args[0]) }) @@ -5296,19 +5251,8 @@ func (vm *VM) bootstrap() { }) // Float#round is defined (with the half: keyword) in registerNumericEdges, // which runs later and overrides any definition here. - vm.cFloat.define("divmod", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - a := floatOf(self) - b, ok := toFloat(args[0]) - if !ok { - raise("TypeError", "%s can't be coerced into Float", vm.classOf(args[0]).name) - } - if b == 0 { - raise("ZeroDivisionError", "divided by 0") - } - // Floored division: the quotient is an Integer, the modulo a Float. - q := math.Floor(a / b) - return object.NewArray(object.IntValue(int64(q)), object.Float(a-b*q)) - }) + // Float#divmod is defined in registerNumericEdges (numeric_edges.go), which + // supersedes this version. vm.cFloat.define("truncate", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { // Truncate toward zero. ndigits > 0 keeps a Float; otherwise an Integer. return floatRound(floatOf(self), args, math.Trunc) diff --git a/internal/vm/integer_float_residuals_internal_test.go b/internal/vm/integer_float_residuals_internal_test.go new file mode 100644 index 00000000..f9bb3435 --- /dev/null +++ b/internal/vm/integer_float_residuals_internal_test.go @@ -0,0 +1,59 @@ +package vm + +import ( + "io" + "math" + "testing" + + "github.com/go-embedded-ruby/ruby/internal/object" +) + +// TestGuardArgcSkipsMissing exercises the branch of guardArgc that skips a name +// the class does not define (so a rename never silently drops an arity check +// against a phantom method). +func TestGuardArgcSkipsMissing(t *testing.T) { + vm := New(io.Discard) + cls := newClass("GuardProbe", vm.cObject) + // "present" gets a guard; "absent" is never defined, so guardArgc must skip it + // rather than panic on the nil lookup. + cls.define("present", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + return self + }) + guardArgc(cls, 1, 1, "present", "absent") + if _, ok := cls.methods["absent"]; ok { + t.Fatalf("guardArgc defined a phantom method for a missing name") + } + if _, ok := cls.methods["present"]; !ok { + t.Fatalf("guardArgc dropped the present method") + } +} + +// TestArgcMessage covers both the equal-bounds and the range rendering. +func TestArgcMessage(t *testing.T) { + if got := argcMessage(2, 1, 1); got != "wrong number of arguments (given 2, expected 1)" { + t.Errorf("equal bounds: %q", got) + } + if got := argcMessage(2, 0, 1); got != "wrong number of arguments (given 2, expected 0..1)" { + t.Errorf("range bounds: %q", got) + } +} + +// TestRubyFloatModEdges pins the signed-zero and non-finite-divisor behaviour of +// ruby_float_mod directly (the operator and method paths both funnel through it). +func TestRubyFloatModEdges(t *testing.T) { + if got := rubyFloatMod(4.2, math.Inf(1)); got != 4.2 { + t.Errorf("4.2 %% +Inf = %v, want 4.2", got) + } + if got := rubyFloatMod(4.2, math.Inf(-1)); !math.IsInf(got, -1) { + t.Errorf("4.2 %% -Inf = %v, want -Inf", got) + } + if got := rubyFloatMod(math.Inf(1), 42); !math.IsNaN(got) { + t.Errorf("Inf %% 42 = %v, want NaN", got) + } + if got := rubyFloatMod(math.Copysign(0, -1), 42); got != 0 || !math.Signbit(got) { + t.Errorf("-0.0 %% 42 = %v, want -0.0", got) + } + if got := rubyFloatMod(4.0, 2.0); got != 0 { + t.Errorf("4.0 %% 2.0 = %v, want 0", got) + } +} diff --git a/internal/vm/integer_float_residuals_test.go b/internal/vm/integer_float_residuals_test.go index 4db2987e..b9c6f763 100644 --- a/internal/vm/integer_float_residuals_test.go +++ b/internal/vm/integer_float_residuals_test.go @@ -1,7 +1,3 @@ -// Copyright (c) the go-embedded-ruby/ruby authors -// -// SPDX-License-Identifier: BSD-3-Clause - package vm_test import ( @@ -9,181 +5,158 @@ import ( "testing" ) -// TestIntegerBitPredicates covers Integer#allbits?/#anybits?/#nobits?, asserted -// against MRI Ruby 4.0.5. The mask is coerced with to_int semantics (a Float -// truncates), and negative / Bignum receivers use two's-complement bits. -func TestIntegerBitPredicates(t *testing.T) { - cases := []struct{ src, want string }{ - // allbits?: every mask bit set in the receiver. - {`p 0b1010.allbits?(0b1000)`, "true\n"}, - {`p 0b1010.allbits?(0b1010)`, "true\n"}, - {`p 0b1010.allbits?(0b1100)`, "false\n"}, - {`p 0b1010.allbits?(0)`, "true\n"}, // empty mask is vacuously contained - // Float mask truncates via to_int: 1.5 -> 1, and 5 & 1 == 1. - {`p 5.allbits?(1.5)`, "true\n"}, - {`p 5.allbits?(2.9)`, "false\n"}, // 2.9 -> 2, 5 & 2 == 0 != 2 - // Bignum receiver and mask. - {`p (2**70 | 1).allbits?(2**70)`, "true\n"}, - {`p (2**70).allbits?(2**70 | 1)`, "false\n"}, - // Two's-complement: -1 has every bit set. - {`p (-1).allbits?(0b1111)`, "true\n"}, - - // anybits?: at least one shared bit. - {`p 0b1010.anybits?(0b0100)`, "false\n"}, - {`p 0b1010.anybits?(0b1100)`, "true\n"}, - {`p 0.anybits?(5)`, "false\n"}, - {`p (2**70 | 4).anybits?(4)`, "true\n"}, - - // nobits?: no shared bit (the complement of anybits?). - {`p 0b1010.nobits?(0b0101)`, "true\n"}, - {`p 0b1010.nobits?(0b1100)`, "false\n"}, - {`p 0.nobits?(5)`, "true\n"}, - } - for _, c := range cases { - if got := eval(t, c.src); got != c.want { - t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) - } - } +// TestIntegerFloatResiduals covers the MRI 4.0.6 conformance work on +// core/integer, core/float and core/numeric: floored Bignum division/modulo, +// Float#% Inf/NaN and signed-zero rules, exact Integer#fdiv, Integer#div and +// Float#divmod operand rules, round precision coercion, Bignum#bit_length, +// Float#<=> edge cases, coerce via Kernel#Float, and the residual aliases. +func TestIntegerFloatResiduals(t *testing.T) { + const coercePrelude = ` +class FdivCoerce; def coerce(o); [1, 10]; end; end +class DivCoerce; def coerce(o); [10, 2]; end; end +class ModCoerce; def coerce(o); [o, 2.0]; end; end +class ToIntArg; def to_int; -2; end; end +class InfPos; def infinite?; 1; end; end +class InfNeg; def infinite?; -1; end; end +class InfNil; def infinite?; nil; end; end +` + cases := []struct{ name, src, want string }{ + // --- floored Bignum / and % (divisor's sign) --- + {"big_div_neg_divisor", `puts(4 / -(2**64))`, "-1\n"}, + {"big_div_pos", `puts((10**50) / (10**40 + 1))`, "9999999999\n"}, + {"big_div_both_neg", `puts(-(10**50) / -(10**40 + 1))`, "9999999999\n"}, + {"big_mod_neg_divisor", `puts(13 % -(2**64))`, "-18446744073709551603\n"}, + {"big_mod_pos", `puts((10**50) % (10**40 + 1))`, "9999999999999999999999999999990000000001\n"}, - // A non-integer mask that lacks #to_int raises, as does a non-finite Float. - errs := []struct{ src, want string }{ - {`5.allbits?("x")`, "no implicit conversion of String into Integer"}, - {`5.anybits?("x")`, "no implicit conversion of String into Integer"}, - {`5.nobits?("x")`, "no implicit conversion of String into Integer"}, - {`5.allbits?(1.0 / 0)`, "Infinity"}, - } - for _, c := range errs { - if err := runErr(t, c.src); err == nil || !strings.Contains(err.Error(), c.want) { - t.Errorf("src=%q err=%v, want substring %q", c.src, err, c.want) - } - } -} + // --- Float#% operator: Inf / NaN / signed zero --- + {"fmod_pos_inf", `puts(4.2 % Float::INFINITY)`, "4.2\n"}, + {"fmod_neg_inf", `puts(4.2 % -Float::INFINITY)`, "-Infinity\n"}, + {"fmod_inf_self", `puts((Float::INFINITY % 42).nan?)`, "true\n"}, + {"fmod_neg_zero", `r = -0.0 % 42; puts(r); puts(1/r < 0)`, "-0.0\ntrue\n"}, + {"fmod_plain", `puts(6543.21 % 137 < 105)`, "true\n"}, -// TestIntegerCeildiv covers Integer#ceildiv (Ruby 3.2+): the quotient rounded -// toward +Infinity, for positive/negative operands, Float/Rational divisors, and -// Bignum receivers — matching MRI Ruby 4.0.5. -func TestIntegerCeildiv(t *testing.T) { - cases := []struct{ src, want string }{ - {`p 10.ceildiv(3)`, "4\n"}, - {`p 9.ceildiv(3)`, "3\n"}, // exact multiple: no rounding up - {`p (-10).ceildiv(3)`, "-3\n"}, - {`p 10.ceildiv(-3)`, "-3\n"}, - {`p (-10).ceildiv(-3)`, "4\n"}, - {`p 0.ceildiv(3)`, "0\n"}, - {`p 10.ceildiv(3.5)`, "3\n"}, // Float divisor, result still an Integer - {`p 10.ceildiv(2r)`, "5\n"}, // Rational divisor - {`p (10**30).ceildiv(7)`, "142857142857142857142857142858\n"}, - } - for _, c := range cases { - if got := eval(t, c.src); got != c.want { - t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) - } - } + // --- Float#% / #modulo methods (dispatch path) --- + {"fmod_method_inf", `puts(4.2.modulo(Float::INFINITY))`, "4.2\n"}, + {"fmod_method_coerce", coercePrelude + `puts(4.2.send(:%, ModCoerce.new))`, "0.20000000000000018\n"}, + {"fmod_modulo_alias", `puts(Float.instance_method(:modulo) == Float.instance_method(:%))`, "true\n"}, - // Zero divisor raises ZeroDivisionError; a non-numeric divisor raises TypeError. - if err := runErr(t, `10.ceildiv(0)`); err == nil || !strings.Contains(err.Error(), "divided by 0") { - t.Errorf("ceildiv(0) err=%v, want divided by 0", err) - } - if err := runErr(t, `10.ceildiv("x")`); err == nil || !strings.Contains(err.Error(), "coerced") { - t.Errorf("ceildiv(\"x\") err=%v, want a coercion TypeError", err) - } -} + // --- Integer#coerce / Float#coerce via Kernel#Float --- + {"int_coerce_int", `p 1.coerce(2)`, "[2, 1]\n"}, + {"int_coerce_string", `p 1.coerce("2")`, "[2.0, 1.0]\n"}, + {"float_coerce_string", `p 2.0.coerce("2.5")`, "[2.5, 2.0]\n"}, -// TestNumericQuo covers Integer#quo / Float#quo, asserted against MRI Ruby 4.0.5. -// Integer#quo yields a Rational for Integer/Rational operands and a Float for a -// Float operand; Float#quo (an alias of #fdiv) always yields a Float. -func TestNumericQuo(t *testing.T) { - cases := []struct{ src, want string }{ - {`p 3.quo(2)`, "(3/2)\n"}, - {`p 6.quo(3)`, "(2/1)\n"}, // reduced, but the denominator is kept - {`p (-3).quo(2)`, "(-3/2)\n"}, - {`p 3.quo(2.0)`, "1.5\n"}, // Float operand -> Float - {`p 3.quo(2r)`, "(3/2)\n"}, - {`p 3.quo(10**40)`, "(3/10000000000000000000000000000000000000000)\n"}, // Bignum operand - {`p 3.quo(2).class`, "Rational\n"}, - // Float#quo is fdiv: always a Float, and a zero divisor gives Infinity. - {`p 3.0.quo(2)`, "1.5\n"}, - {`p 3.0.quo(2r)`, "1.5\n"}, - {`p 3.0.quo(0)`, "Infinity\n"}, - } - for _, c := range cases { - if got := eval(t, c.src); got != c.want { - t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) - } - } + // --- Integer#fdiv (exact, huge Bignums) --- + {"fdiv_bignum_tiny", `puts(1.fdiv(10**323) == 1.0e-323)`, "true\n"}, + {"fdiv_bignum_ratio", `puts((10**344).fdiv(9 * 10**342))`, "11.11111111111111\n"}, + {"fdiv_zero_inf", `puts(1.fdiv(0).infinite?)`, "1\n"}, + {"fdiv_neg_zero_inf", `puts(-1.fdiv(0).infinite?)`, "-1\n"}, + {"fdiv_float", `puts(8.fdiv(9.0) > 0.88)`, "true\n"}, + {"fdiv_rational", `puts(1.fdiv(Rational(1, 5)))`, "5.0\n"}, + {"fdiv_rational_zero", `puts(1.fdiv(Rational(0, 1)).infinite?)`, "1\n"}, + {"fdiv_coerce", coercePrelude + `puts(1.fdiv(FdivCoerce.new))`, "0.1\n"}, - errs := []struct{ src, want string }{ - {`3.quo(0)`, "divided by 0"}, - {`3.quo(0r)`, "divided by 0"}, - {`3.quo("x")`, "String can't be coerced into Rational"}, - {`3.quo(nil)`, "nil can't be coerced into Rational"}, - {`3.quo(true)`, "true can't be coerced into Rational"}, - {`3.0.quo("x")`, "String can't be coerced into Float"}, - } - for _, c := range errs { - if err := runErr(t, c.src); err == nil || !strings.Contains(err.Error(), c.want) { - t.Errorf("src=%q err=%v, want substring %q", c.src, err, c.want) - } - } -} + // --- Float#fdiv --- + {"float_fdiv", `puts(8.0.fdiv(2))`, "4.0\n"}, -// TestFloatRemainder covers Float#remainder: self - other*(self/other).truncate, -// keeping the dividend's sign, with NaN/Infinity edges — vs MRI Ruby 4.0.5. -func TestFloatRemainder(t *testing.T) { - cases := []struct{ src, want string }{ - {`p 7.0.remainder(3)`, "1.0\n"}, - {`p (-7.0).remainder(3)`, "-1.0\n"}, - {`p 7.0.remainder(-3)`, "1.0\n"}, - {`p 7.0.remainder(3.5)`, "0.0\n"}, - // A zero has a sign, and it is the DIVIDEND's, never the divisor's. - // The subtraction reaches that on its own wherever the arithmetic rounds - // as IEEE 754 says; loong64 under qemu returned -0.0 for the line above, - // which had the nightly red, so the sign is now stated outright. - {`p (-7.0).remainder(3.5)`, "-0.0\n"}, - {`p 7.0.remainder(-3.5)`, "0.0\n"}, - {`p (-7.0).remainder(-3.5)`, "-0.0\n"}, - {`p (-0.0).remainder(3.0)`, "-0.0\n"}, - {`p (0.0 / 0).remainder(3)`, "NaN\n"}, // NaN dividend - {`p (1.0 / 0).remainder(3)`, "NaN\n"}, // Infinity dividend - {`p (-7.5).remainder(3)`, "-1.5\n"}, - } - for _, c := range cases { - if got := eval(t, c.src); got != c.want { - t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) - } - } + // --- Integer#div operand rules --- + {"div_bignum", `puts((2**70).div(2**60))`, "1024\n"}, + {"div_float", `puts(1.div(0.2))`, "5\n"}, + {"div_rational", `puts(5.div(Rational(2, 1)))`, "2\n"}, + {"div_coerce", coercePrelude + `puts(5.div(DivCoerce.new))`, "5\n"}, - if err := runErr(t, `5.0.remainder(0)`); err == nil || !strings.Contains(err.Error(), "divided by 0") { - t.Errorf("remainder(0) err=%v, want divided by 0", err) - } - if err := runErr(t, `5.0.remainder("x")`); err == nil || !strings.Contains(err.Error(), "String can't be coerced into Float") { - t.Errorf("remainder(\"x\") err=%v, want coercion TypeError", err) + // --- Float#divmod --- + {"float_divmod", `p 13.0.divmod(4)`, "[3, 1.0]\n"}, + + // --- round precision: #to_int coercion, finite Float truncation --- + {"round_to_int_mock", coercePrelude + `puts(12345.round(ToIntArg.new))`, "12300\n"}, + {"round_float_ndigits", `puts(12.345678.round(3.999))`, "12.346\n"}, + {"round_big_float_ndigits", `puts(0.42.round(2.0**30))`, "0.42\n"}, + {"int_round_pos_ndigits", `puts(42.round(2))`, "42\n"}, + + // --- Bignum#bit_length --- + {"bit_length_pos", `puts((2**70).bit_length)`, "71\n"}, + {"bit_length_neg", `puts((-2**70).bit_length)`, "70\n"}, + + // --- Float#<=> (Integer / Rational / #coerce / non-numeric) --- + {"cmp_int", `puts(1.5 <=> 5)`, "-1\n"}, + {"cmp_rational", `puts(1.5 <=> Rational(3, 2))`, "0\n"}, + {"cmp_coerce", coercePrelude + `puts(2.33 <=> ModCoerce.new)`, "1\n"}, + {"cmp_non_numeric", `p 1.0 <=> "1"`, "nil\n"}, + + // --- residual aliases (identity of the two UnboundMethods) --- + {"alias_int_inspect", `puts(Integer.instance_method(:inspect) == Integer.instance_method(:to_s))`, "true\n"}, + {"alias_int_magnitude", `puts(Integer.instance_method(:magnitude) == Integer.instance_method(:abs))`, "true\n"}, + {"alias_int_next", `puts(Integer.instance_method(:next) == Integer.instance_method(:succ))`, "true\n"}, + {"alias_float_to_int", `puts(Float.instance_method(:to_int) == Float.instance_method(:to_i))`, "true\n"}, + {"alias_float_magnitude", `puts(Float.instance_method(:magnitude) == Float.instance_method(:abs))`, "true\n"}, + {"alias_num_modulo", `puts(Numeric.instance_method(:modulo) == Numeric.instance_method(:%))`, "true\n"}, + {"alias_num_magnitude", `puts(Numeric.instance_method(:magnitude) == Numeric.instance_method(:abs))`, "true\n"}, + {"alias_num_conj", `puts(Numeric.instance_method(:conj) == Numeric.instance_method(:conjugate))`, "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) + } + }) } } -// TestFloatStep covers Float#step: the enumerator form (no block) and the -// block form walking [self, limit] by step (default 1), incl. a negative step — -// asserted against MRI Ruby 4.0.5. -func TestFloatStep(t *testing.T) { - cases := []struct{ src, want string }{ - {`p 1.0.step(3.0).to_a`, "[1.0, 2.0, 3.0]\n"}, // default step, enumerator - {`p 1.0.step(3.0, 0.5).to_a`, "[1.0, 1.5, 2.0, 2.5, 3.0]\n"}, - {`p 5.0.step(1.0, -2.0).to_a`, "[5.0, 3.0, 1.0]\n"}, // negative step - {`p 1.0.step(3.0) { |x| }`, "1.0\n"}, // block form returns self - {`a = []; 1.0.step(2.0, 0.25) { |x| a << x }; p a`, "[1.0, 1.25, 1.5, 1.75, 2.0]\n"}, - } - for _, c := range cases { - if got := eval(t, c.src); got != c.want { - t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) - } - } +// TestIntegerFloatResidualErrors covers the raising branches: floored Bignum +// division by zero, Float#% zero and Float#divmod NaN/Infinity/zero, argument +// coercion failures, round-precision RangeError/TypeError, and the arity guards. +func TestIntegerFloatResidualErrors(t *testing.T) { + const prelude = ` +class BadToInt; def to_int; "x"; end; end +` + cases := []struct{ name, src, want string }{ + // --- division by zero --- + {"big_div_zero", `(2**70) / 0`, "ZeroDivisionError"}, + {"big_mod_zero", `(2**70) % 0`, "ZeroDivisionError"}, + {"float_mod_zero_int", `1.0 % 0`, "ZeroDivisionError"}, + {"float_mod_zero_float", `1.0 % 0.0`, "ZeroDivisionError"}, + {"float_modulo_zero", `1.0.modulo(0)`, "ZeroDivisionError"}, + {"int_div_float_zero", `10.div(0.0)`, "ZeroDivisionError"}, + {"int_div_int_zero", `10.div(0)`, "ZeroDivisionError"}, - // A bare Float#step (no limit) is an unbounded walk of step 1.0, matching MRI - // (the block must break out); a zero step raises ArgumentError. - if got := eval(t, `r = []; 1.0.step { |x| r << x; break if x >= 3.0 }; p r`); got != "[1.0, 2.0, 3.0]\n" { - t.Errorf("bare Float#step got=%q, want unbounded walk", got) - } - if err := runErr(t, `1.0.step(3.0, 0) { |x| }`); err == nil || !strings.Contains(err.Error(), "step can't be 0") { - t.Errorf("step(3.0,0) err=%v, want step can't be 0", err) + // --- Float#divmod domain / zero --- + {"divmod_nan_self", `Float::NAN.divmod(1)`, "FloatDomainError"}, + {"divmod_nan_other", `1.0.divmod(Float::NAN)`, "FloatDomainError"}, + {"divmod_inf_self", `Float::INFINITY.divmod(1)`, "FloatDomainError"}, + {"divmod_zero", `1.0.divmod(0)`, "ZeroDivisionError"}, + {"divmod_non_numeric", `1.0.divmod("x")`, "TypeError"}, + + // --- coerce / fdiv operand errors --- + {"int_coerce_nil", `1.coerce(nil)`, "TypeError"}, + {"int_coerce_bad_string", `1.coerce(":)")`, "ArgumentError"}, + {"int_fdiv_non_numeric", `1.fdiv("x")`, "TypeError"}, + {"float_fdiv_non_numeric", `1.0.fdiv("x")`, "TypeError"}, + + // --- round precision RangeError / TypeError --- + {"round_bignum_ndigits", `42.round(10**40)`, "RangeError"}, + {"round_beyond_int", `42.round(1 << 31)`, "RangeError"}, + {"round_infinity", `42.round(Float::INFINITY)`, "RangeError"}, + {"round_nan", `42.round(Float::NAN)`, "RangeError"}, + {"round_no_to_int", `5.round("x")`, "TypeError"}, + {"round_to_int_bad", prelude + `5.round(BadToInt.new)`, "TypeError"}, + + // --- arity guards --- + {"gcd_arity", `12.gcd(30, 20)`, "given 2, expected 1"}, + {"lcm_arity", `12.lcm(30, 20)`, "ArgumentError"}, + {"gcdlcm_arity", `12.gcdlcm(30, 20)`, "ArgumentError"}, + {"to_r_arity", `287.to_r(2)`, "given 1, expected 0"}, + {"rationalize_arity", `1.rationalize(1, 2)`, "expected 0..1"}, + {"float_rationalize_arity", `1.0.rationalize(1, 2)`, "ArgumentError"}, + {"imaginary_arity", `1.imaginary(1)`, "ArgumentError"}, + {"fdiv_arity", `1.fdiv(6, 0.2)`, "ArgumentError"}, + {"float_fdiv_arity", `1.0.fdiv(6, 0.2)`, "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.want) { + t.Errorf("src=%q: got err=%v, want containing %q", tc.src, err, tc.want) + } + }) } } diff --git a/internal/vm/numeric_edges.go b/internal/vm/numeric_edges.go index 86bcfa5c..fbb95035 100644 --- a/internal/vm/numeric_edges.go +++ b/internal/vm/numeric_edges.go @@ -5,6 +5,7 @@ package vm import ( + "fmt" "math" "math/big" @@ -23,10 +24,51 @@ import ( // are shared with the Rational rounding path (see rational.go): roundArgs peels // the ndigits and mode with the same ratPrecision / ratHalfMode helpers. -// roundArgs splits a round argument list into its integer ndigits (default 0) -// and the `half:` rounding mode, validating the mode even when ndigits >= 0. -func roundArgs(args []object.Value) (ndigits int, mode roundMode) { - return int(ratPrecision(args)), ratHalfMode(args) +// roundNdigits splits a round argument list into its ndigits (default 0) and +// the `half:` rounding mode. Unlike the plain ratPrecision reader it follows +// MRI's NUM2INT contract for ndigits: the value is coerced through #to_int, a +// magnitude beyond a C int raises RangeError (a Bignum or a Float ±Infinity +// included), and a finite Float truncates toward zero. +func (vm *VM) roundNdigits(args []object.Value) (ndigits int, mode roundMode) { + mode = ratHalfMode(args) + for _, a := range args { + if _, ok := a.(*object.Hash); ok { // the half: keyword hash + continue + } + return vm.toRoundInt(a), mode + } + return 0, mode +} + +// toRoundInt coerces a round precision argument to a C-int-range Go int the way +// MRI's rb_num2int does, raising RangeError when the value cannot fit. +func (vm *VM) toRoundInt(a object.Value) int { + switch v := a.(type) { + case object.Integer: + if int64(v) < math.MinInt32 || int64(v) > math.MaxInt32 { + raise("RangeError", "integer %d too big to convert to `int'", int64(v)) + } + return int(v) + case *object.Bignum: + raise("RangeError", "bignum too big to convert into `long'") + case object.Float: + f := math.Trunc(float64(v)) + if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) || f < math.MinInt32 || f > math.MaxInt32 { + raise("RangeError", "float %s out of range of integer", v.ToS()) + } + return int(f) + } + if vm.respondsToDynamic(a, "to_int") { + r := vm.send(a, "to_int", nil, nil) + switch r.(type) { + case object.Integer, *object.Bignum: + return vm.toRoundInt(r) + } + raise("TypeError", "can't convert %s to Integer (%s#to_int gives %s)", + classNameOf(a), classNameOf(a), classNameOf(r)) + } + raise("TypeError", "no implicit conversion of %s into Integer", classNameOf(a)) + return 0 } // --- Float rounding, ported from CRuby numeric.c --------------------------- @@ -421,8 +463,8 @@ func (vm *VM) registerNumericEdges() { }) // Integer#round — MRI-faithful, honouring negative ndigits and `half:`. - vm.cInteger.define("round", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - ndigits, mode := roundArgs(args) + vm.cInteger.define("round", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + ndigits, mode := vm.roundNdigits(args) if ndigits >= 0 { return self } @@ -438,8 +480,8 @@ func (vm *VM) registerNumericEdges() { }) // Float#round — MRI-faithful, honouring `half:` and the ndigits contract. - vm.cFloat.define("round", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - ndigits, mode := roundArgs(args) + vm.cFloat.define("round", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + ndigits, mode := vm.roundNdigits(args) return floRound(floatOf(self), ndigits, mode) }) @@ -536,6 +578,186 @@ func (vm *VM) registerNumericEdges() { } return self }) + + vm.registerNumericAliasesAndEdges() +} + +// registerNumericAliasesAndEdges installs the residual alias tables and the +// coerce/fdiv/modulo edge cases that MRI 4.0 defines. It runs at the end of +// registerNumericEdges (so its definitions win) and is split out only to keep +// the parent function readable. +func (vm *VM) registerNumericAliasesAndEdges() { + floatOf := func(self object.Value) float64 { return float64(self.(object.Float)) } + cNumeric := vm.cComplex.super // Complex < Numeric, so this is the Numeric class + + // --- Method aliases (true aliases: instance_method(:a) == instance_method(:b)). + // The alias specs compare the two UnboundMethods for identity, so each pair + // must share a single method-table entry rather than be two closures. + aliasBuiltin(cNumeric, "modulo", "%") + aliasBuiltin(cNumeric, "magnitude", "abs") + aliasBuiltin(cNumeric, "conj", "conjugate") + aliasBuiltin(cNumeric, "imag", "imaginary") + aliasBuiltin(cNumeric, "rect", "rectangular") + aliasBuiltin(cNumeric, "angle", "arg") + aliasBuiltin(cNumeric, "phase", "arg") + aliasBuiltin(vm.cInteger, "inspect", "to_s") + aliasBuiltin(vm.cInteger, "magnitude", "abs") + aliasBuiltin(vm.cInteger, "next", "succ") + aliasBuiltin(vm.cFloat, "inspect", "to_s") + aliasBuiltin(vm.cFloat, "to_int", "to_i") + aliasBuiltin(vm.cFloat, "magnitude", "abs") + + // --- Integer#coerce / Float#coerce via Kernel#Float --- + // MRI coerces a non-Integer operand of Integer#coerce with rb_Float (parsing a + // String, dispatching #to_f on an object, raising ArgumentError/TypeError like + // Float()); an Integer/Bignum operand stays exact and returns [other, self]. + vm.cInteger.define("coerce", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, "coerce") + other := args[0] + if _, ok := object.BigOf(other); ok { + return object.NewArray(other, self) + } + of := vm.send(vm.main, "Float", []object.Value{other}, nil) + sf := vm.send(vm.main, "Float", []object.Value{self}, nil) + return object.NewArray(of, sf) + }) + // Float#coerce converts the operand with Kernel#Float and returns [other, self] + // (self is already a Float). + vm.cFloat.define("coerce", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, "coerce") + of := vm.send(vm.main, "Float", []object.Value{args[0]}, nil) + return object.NewArray(of, self) + }) + + // --- Integer#fdiv — exact division so huge Bignums round correctly --- + // self.to_f / other.to_f overflows to Inf/Inf = NaN for operands beyond a + // double's range; MRI divides exactly (rb_big_fdiv) so 1.fdiv(10**323) is + // 1e-323 rather than 0.0 and (10**400).fdiv(10**402) is 0.01 rather than NaN. + vm.cInteger.define("fdiv", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, "fdiv") + other := args[0] + if f, ok := other.(object.Float); ok { + sf, _ := toFloat(self) + return object.Float(sf / float64(f)) + } + a, _ := object.BigOf(self) + if b, ok := object.BigOf(other); ok { + if b.Sign() == 0 { // 1.fdiv(0) is ±Infinity, not a division error + sf, _ := toFloat(self) + return object.Float(sf / 0.0) + } + q, _ := new(big.Rat).SetFrac(a, b).Float64() + return object.Float(q) + } + if r, ok := other.(*object.Rational); ok { + if r.R.Sign() == 0 { + sf, _ := toFloat(self) + return object.Float(sf / 0.0) + } + q, _ := new(big.Rat).Quo(new(big.Rat).SetInt(a), r.R).Float64() + return object.Float(q) + } + return vm.numCoerceDispatch(self, other, "fdiv") + }) + + // Float#fdiv is exactly one argument, then float division (a zero divisor + // yields ±Infinity, never a ZeroDivisionError); a non-numeric divisor is + // coerced, matching Numeric#coerce ("into Float"). + vm.cFloat.define("fdiv", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, "fdiv") + b, ok := toFloat(args[0]) + if !ok { + raise("TypeError", "%s can't be coerced into Float", vm.classOf(args[0]).name) + } + return object.Float(floatOf(self) / b) + }) + // Float#quo is a true alias of #fdiv; re-establish it now that #fdiv has been + // redefined above (the earlier alias pointed at the previous #fdiv record). + aliasBuiltin(vm.cFloat, "quo", "fdiv") + + // --- Integer#div — floored quotient, MRI operand rules --- + // An Integer/Bignum divisor gives a floored Integer; a Float divisor floors + // self.to_f/other but raises ZeroDivisionError on a 0.0 divisor (unlike + // Float#/); a Rational divisor floors the exact quotient; anything else runs + // the coerce protocol (other.coerce(self) then #div on the pair). + vm.cInteger.define("div", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, "div") + other := args[0] + if b, ok := object.BigOf(other); ok { + if b.Sign() == 0 { + raise("ZeroDivisionError", "divided by 0") + } + a, _ := object.BigOf(self) + q, _ := bigFloorDivmod(a, b) + return object.NormInt(q) + } + if f, ok := other.(object.Float); ok { + if float64(f) == 0 { + raise("ZeroDivisionError", "divided by 0") + } + a, _ := toFloat(self) + return floatToInt(math.Floor(a / float64(f))) + } + if _, ok := other.(*object.Rational); ok { + q := vm.send(self, "/", []object.Value{other}, nil) + return vm.send(q, "floor", nil, nil) + } + return vm.numCoerceDispatch(self, other, "div") + }) + + // --- Float#% / #modulo / #divmod — MRI Inf/NaN and sign rules --- + // ruby_float_mod: fmod, but a non-finite divisor of a finite dividend returns + // the dividend, and the result takes the divisor's sign (so 4.2 % Infinity is + // 4.2 and 4.2 % -Infinity is -Infinity). A zero divisor raises; a non-numeric + // divisor is coerced (mock#coerce, then re-dispatch %). + vm.cFloat.define("%", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, "%") + b, ok := toFloat(args[0]) + if !ok { + return vm.numCoerceDispatch(self, args[0], "%") + } + if b == 0 { + raise("ZeroDivisionError", "divided by 0") + } + return object.Float(rubyFloatMod(floatOf(self), b)) + }) + aliasBuiltin(vm.cFloat, "modulo", "%") + // Float#divmod: an Integer quotient (floored) and a Float modulo. A NaN or + // Infinite quotient has no Integer value, so MRI raises FloatDomainError; a + // zero divisor raises ZeroDivisionError. + vm.cFloat.define("divmod", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, "divmod") + b, ok := toFloat(args[0]) + if !ok { + raise("TypeError", "%s can't be coerced into Float", vm.classOf(args[0]).name) + } + if b == 0 { + raise("ZeroDivisionError", "divided by 0") + } + a := floatOf(self) + q := floatToInt(math.Floor(a / b)) // FloatDomainError for NaN/±Infinity + return object.NewArray(q, object.Float(rubyFloatMod(a, b))) + }) + + // Integer#bit_length — the number of bits in the two's-complement + // representation (excluding the sign). The earlier definition used a machine + // long and raised RangeError for a Bignum; compute it over big.Int so a + // Bignum answers (a negative number uses ~n, since -n-1 has the same magnitude + // pattern as MRI's leftmost-0-bit count). + vm.cInteger.define("bit_length", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + n := bigVal(self) + if n.Sign() < 0 { + n = new(big.Int).Not(n) // ~n = -n-1 + } + return object.IntValue(int64(n.BitLen())) + }) + + // --- Zero-or-one / exactly-one argument-count guards MRI enforces --- + guardOneArg(vm.cInteger, "gcd", "lcm", "gcdlcm") + guardNoArg(vm.cInteger, "to_r") + guardAtMostOneArg(vm.cInteger, "rationalize") + guardAtMostOneArg(vm.cFloat, "rationalize") + guardNoArg(cNumeric, "imaginary", "real", "rectangular") } // ratOf converts an Integer/Bignum/Rational value to a *big.Rat for exact @@ -552,6 +774,63 @@ func ratOf(v object.Value) (*big.Rat, bool) { return nil, false } +// rubyFloatMod is CRuby's ruby_float_mod: fmod(x, y), except a non-finite +// divisor of a finite dividend returns the dividend, and the result is made to +// carry the divisor's sign (adding y when they differ). It matches MRI's +// Float#% for every finite/Infinite/NaN and signed-zero combination. +func rubyFloatMod(x, y float64) float64 { + mod := math.Mod(x, y) + if math.IsInf(y, 0) && !math.IsInf(x, 0) && !math.IsNaN(x) { + mod = x + } + if mod != 0 && (y < 0) != (mod < 0) { + mod += y + } + return mod +} + +// checkArgc raises MRI's ArgumentError when a method that takes exactly n +// positional arguments is called with a different count. +func checkArgc(args []object.Value, n int, _ string) { + if len(args) != n { + raise("ArgumentError", "%s", argcMessage(len(args), n, n)) + } +} + +// argcMessage renders MRI's "wrong number of arguments" text for a given/min/max +// triple ("expected N" when the bounds are equal, "expected min..max" otherwise). +func argcMessage(given, min, max int) string { + if min == max { + return fmt.Sprintf("wrong number of arguments (given %d, expected %d)", given, min) + } + return fmt.Sprintf("wrong number of arguments (given %d, expected %d..%d)", given, min, max) +} + +// guardArgc re-wraps each named method of cls with a positional-argument-count +// check ([min, max]; max < 0 means unbounded), preserving the original body. +// A name the class does not define is skipped. +func guardArgc(cls *RClass, min, max int, names ...string) { + for _, name := range names { + m, ok := cls.methods[name] + if !ok { + continue + } + orig := m.native + cls.define(name, func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { + if len(args) < min || (max >= 0 && len(args) > max) { + raise("ArgumentError", "%s", argcMessage(len(args), min, max)) + } + return orig(vm, self, args, blk) + }) + } +} + +// guardOneArg / guardNoArg / guardAtMostOneArg apply the three arity shapes MRI +// enforces on these numeric methods. +func guardOneArg(cls *RClass, names ...string) { guardArgc(cls, 1, 1, names...) } +func guardNoArg(cls *RClass, names ...string) { guardArgc(cls, 0, 0, names...) } +func guardAtMostOneArg(cls *RClass, names ...string) { guardArgc(cls, 0, 1, names...) } + // coerceName names a value the way MRI does in "X can't be coerced" errors: // nil/true/false by their literal, everything else by class name. func coerceName(v object.Value) string { diff --git a/internal/vm/numeric_edges_coverage_internal_test.go b/internal/vm/numeric_edges_coverage_internal_test.go new file mode 100644 index 00000000..cb81a8a6 --- /dev/null +++ b/internal/vm/numeric_edges_coverage_internal_test.go @@ -0,0 +1,37 @@ +package vm + +import ( + "io" + "math/big" + "testing" + + "github.com/go-embedded-ruby/ruby/internal/object" +) + +// TestSpaceshipNumericExact drives spaceshipNumeric (Integer#<=>) directly across +// its exact-integer branches. The `<=>` operator on two integers is inlined by +// the VM, so the Integer-Integer and Bignum-Bignum comparison paths are only +// reachable by calling the method function itself. +func TestSpaceshipNumericExact(t *testing.T) { + vm := New(io.Discard) + big70 := object.NormInt(new(big.Int).Lsh(big.NewInt(1), 70)) // 2**70 + big71 := object.NormInt(new(big.Int).Lsh(big.NewInt(1), 71)) // 2**71 + for _, c := range []struct { + self, other object.Value + want int64 + }{ + {object.Integer(1), object.Integer(2), -1}, // fixnum <=> fixnum + {object.Integer(5), object.Integer(5), 0}, + {object.Integer(9), object.Integer(3), 1}, + {big70, big71, -1}, // bignum <=> bignum + {big71, big70, 1}, + {big70, big70, 0}, + {big70, object.Integer(7), 1}, // bignum <=> fixnum + } { + got := spaceshipNumeric(vm, c.self, []object.Value{c.other}, nil) + gi, ok := got.(object.Integer) + if !ok || int64(gi) != c.want { + t.Errorf("spaceshipNumeric(%v, %v) = %v, want %d", c.self, c.other, got, c.want) + } + } +} diff --git a/internal/vm/numeric_edges_coverage_test.go b/internal/vm/numeric_edges_coverage_test.go new file mode 100644 index 00000000..0d642d2b --- /dev/null +++ b/internal/vm/numeric_edges_coverage_test.go @@ -0,0 +1,126 @@ +package vm_test + +import ( + "strings" + "testing" +) + +// TestNumericEdgesCoverage exercises every method registered in +// registerNumericEdges across each of its branches — bit reference forms, the +// exact-quotient (#quo) Rational/Float/error paths, Float#remainder sign and +// error handling, the bit predicates, #ceildiv, #size, and Float#step — plus +// the numeric-operator branches (floored Bignum div/mod, Float % zero-divisor) +// that the shared arith dispatch grew. Each result is printed with `p` and +// checked against MRI Ruby 4.0.6's output. +func TestNumericEdgesCoverage(t *testing.T) { + ok := []struct{ expr, want string }{ + // Integer#[] — single bit, two-arg (start,len) slice, and Range forms. + {`5[0]`, "1"}, {`5[1]`, "0"}, {`5[2]`, "1"}, + {`0b1011001[2,3]`, "6"}, + {`0b1011001[2..4]`, "6"}, + {`0b1011001[2...5]`, "6"}, + {`255[4..]`, "15"}, + // Integer#size — fixnum is 8, a Bignum reports its byte length. + {`1.size`, "8"}, + {`(256**20).size`, "21"}, + // Integer#ord / #integer?. + {`65.ord`, "65"}, {`5.integer?`, "true"}, + // Integer#round with negative ndigits, half: modes, and ndigits>=0 (self). + {`12345.round(-2)`, "12300"}, + {`15.round(-1)`, "20"}, + {`15.round(-1,half: :even)`, "20"}, + {`25.round(-1,half: :down)`, "20"}, + {`123.round(2)`, "123"}, + // Float#next_float / #prev_float bracket the value. + {`1.0.next_float > 1.0`, "true"}, + {`1.0.prev_float < 1.0`, "true"}, + // Float#round honouring half: and ndigits. + {`2.5.round`, "3"}, {`2.5.round(half: :even)`, "2"}, + {`3.14159.round(2)`, "3.14"}, + // Bit predicates + their #to_int mask coercion (Float mask truncates). + {`0b1100.allbits?(0b0100)`, "true"}, + {`0b1100.allbits?(0b0110)`, "false"}, + {`0b1100.anybits?(0b0110)`, "true"}, + {`0b1100.anybits?(0b0011)`, "false"}, + {`0b1100.nobits?(0b0011)`, "true"}, + {`0b1100.nobits?(0b0100)`, "false"}, + {`0b1100.allbits?(4.9)`, "true"}, // Float mask truncates to 4 + // Integer#ceildiv rounds toward +Infinity, both signs. + {`7.ceildiv(3)`, "3"}, {`-7.ceildiv(3)`, "-2"}, {`6.ceildiv(3)`, "2"}, + // Integer#quo: Float operand -> Float; Integer/Rational -> Rational. + {`7.quo(2)`, "(7/2)"}, + {`7.quo(2.0)`, "3.5"}, + {`7.quo(Rational(1,2))`, "(14/1)"}, + {`(2**70).quo(2)`, "(590295810358705651712/1)"}, + {`7.quo(2**70)`, "(7/1180591620717411303424)"}, + // Float#quo is an exact fdiv; a zero divisor gives Infinity. + {`10.0.quo(4)`, "2.5"}, + {`(1.0.quo(0)).infinite?`, "1"}, + // Float#remainder keeps the dividend's sign; the zero result is signed. + {`7.0.remainder(3.5)`, "0.0"}, + {`7.5.remainder(2.0)`, "1.5"}, + {`-7.5.remainder(2.0)`, "-1.5"}, + {`(-7.0).remainder(3.5)`, "-0.0"}, + // Float#step without a block yields an Enumerator (materialised here). + {`1.0.step(2.0,0.5).to_a`, "[1.0, 1.5, 2.0]"}, + // Shared numeric operators the arith dispatch grew: floored Bignum div/mod + // with a negative divisor, and Float % with special divisors. + {`(2**70) % -3`, "-2"}, + {`(-(2**70)) % 3`, "2"}, + {`(2**70) / -3`, "-393530540239137101142"}, + {`(7.0 % 3.0)`, "1.0"}, + {`(-7.0 % 3.0)`, "2.0"}, + // Numeric#<=> across every exact/float/Bignum path, NaN (nil), and a + // non-numeric operand (nil) — dispatched through the method (via #send) so + // it exercises spaceshipNumeric rather than the inlined comparison opcode. + {`1.send(:"<=>", 2)`, "-1"}, + {`5.send(:"<=>", 5)`, "0"}, + {`(2**70).send(:"<=>", 2**71)`, "-1"}, + {`(2**70).send(:"<=>", 1.0e30)`, "-1"}, + {`(2**70).send(:"<=>", 0.0/0.0)`, "nil"}, + {`1.0.send(:"<=>", 2**70)`, "-1"}, + {`(0.0/0.0).send(:"<=>", 2**70)`, "nil"}, + {`1.5.send(:"<=>", 2)`, "-1"}, + {`1.send(:"<=>", "x")`, "nil"}, + {`1.send(:"<=>", Rational(1, 2))`, "1"}, // Integer <=> Rational: toFloat fallback + } + for _, c := range ok { + if got := eval(t, "p ("+c.expr+")"); got != c.want+"\n" { + t.Errorf("p (%s) = %q, want %q", c.expr, got, c.want+"\n") + } + } + + // Float#step with a block walks [self, limit] by step. + if got := eval(t, `r = []; 1.0.step(2.0, 0.5) { |x| r << x }; p r`); got != "[1.0, 1.5, 2.0]\n" { + t.Errorf("Float#step block form = %q", got) + } + + // Numeric <=> with a non-numeric operand that defines #coerce: the value runs + // the coerce protocol and re-dispatches <=> on the returned pair. + if got := eval(t, `class Cz; def coerce(o); [o, 0]; end; end; p (5.send(:"<=>", Cz.new))`); got != "1\n" { + t.Errorf("spaceshipNumeric coerce form = %q", got) + } + + errs := []struct{ src, want string }{ + // Integer#quo error paths: non-numeric coercion and division by zero. + {`7.quo("x")`, "can't be coerced into Rational"}, + {`7.quo(0)`, "divided by 0"}, + // Float#remainder error paths. + {`7.0.remainder("x")`, "can't be coerced into Float"}, + {`7.0.remainder(0)`, "divided by 0"}, + // A String bit mask raises rather than coercing. + {`12.allbits?("x")`, "no implicit conversion"}, + // Float % by zero raises (the grown floatOp branch). + {`7.0 % 0`, "divided by 0"}, + } + for _, c := range errs { + err := runErr(t, c.src) + if err == nil { + t.Errorf("runErr(%q) = nil, want error containing %q", c.src, c.want) + continue + } + if !strings.Contains(err.Error(), c.want) { + t.Errorf("runErr(%q) error = %q, want containing %q", c.src, err.Error(), c.want) + } + } +} diff --git a/internal/vm/whitebox_test.go b/internal/vm/whitebox_test.go index 46e088a6..d3c3e439 100644 --- a/internal/vm/whitebox_test.go +++ b/internal/vm/whitebox_test.go @@ -77,8 +77,8 @@ func TestClassOfUnknown(t *testing.T) { } func TestFloatModSign(t *testing.T) { - if got := floatMod(-7.5, 2.0); got != 0.5 { - t.Errorf("floatMod(-7.5,2.0)=%v want 0.5", got) + if got := rubyFloatMod(-7.5, 2.0); got != 0.5 { + t.Errorf("rubyFloatMod(-7.5,2.0)=%v want 0.5", got) } }