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
67 changes: 12 additions & 55 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -4534,14 +4534,12 @@ func (vm *VM) bootstrap() {
return object.NormInt(new(big.Int).Not(bigVal(self)))
})
vm.cInteger.define("gcd", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return object.IntValue(gcdInt(intOf(self), intArg(args[0])))
a, _ := object.BigOf(self)
return object.NormInt(bigGCD(a, integerGcdArg(args[0])))
})
vm.cInteger.define("lcm", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
a, b := intOf(self), intArg(args[0])
if a == 0 || b == 0 {
return object.IntValue(0)
}
return object.IntValue(absInt(a / gcdInt(a, b) * b))
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)
Expand Down Expand Up @@ -4608,30 +4606,16 @@ func (vm *VM) bootstrap() {
}
return object.IntValue(c)
})
vm.cInteger.define("divmod", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
a, b := intOf(self), intArg(args[0])
if b == 0 {
raise("ZeroDivisionError", "divided by 0")
}
return object.NewArray(object.IntValue(floorDiv(a, b)), object.IntValue(floorMod(a, b)))
vm.cInteger.define("divmod", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return vm.integerDivmod(self, args[0])
})
vm.cInteger.define("gcdlcm", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
a, b := intOf(self), intArg(args[0])
g := gcdInt(a, b)
var lcm int64
if a != 0 && b != 0 {
lcm = absInt(a / g * b)
}
return object.NewArray(object.IntValue(g), object.IntValue(lcm))
})
vm.cInteger.define("remainder", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
// remainder truncates toward zero (keeping the dividend's sign), unlike %
// which floors — exactly Go's % operator.
a, b := intOf(self), intArg(args[0])
if b == 0 {
raise("ZeroDivisionError", "divided by 0")
}
return object.IntValue(a % b)
a, _ := object.BigOf(self)
b := integerGcdArg(args[0])
return object.NewArray(object.NormInt(bigGCD(a, b)), object.NormInt(bigLCM(a, b)))
})
vm.cInteger.define("remainder", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return vm.integerRemainder(self, args[0])
})
// truncate with ndigits >= 0 leaves an Integer unchanged; with ndigits < 0 it
// truncates toward zero to the nearest 10**(-ndigits). Integer#round is defined
Expand Down Expand Up @@ -7636,14 +7620,6 @@ func powNumeric(_ *VM, self object.Value, args []object.Value, _ *Proc) object.V
return object.Float(math.Pow(a, b))
}

// absInt is the absolute value of an int64.
func absInt(n int64) int64 {
if n < 0 {
return -n
}
return n
}

// stringLineSegs splits the receiver into line segments for String#lines /
// #each_line, honouring the optional record separator (default "\n"; nil = the
// whole string; "" = paragraph mode) and a chomp: keyword that strips the
Expand Down Expand Up @@ -7979,16 +7955,6 @@ func bigVal(v object.Value) *big.Int {
return b
}

// bigArg returns an integer argument as a *big.Int, raising TypeError when the
// argument is not an Integer/Bignum (as Ruby's bitwise operators do).
func bigArg(v object.Value) *big.Int {
if b, ok := object.BigOf(v); ok {
return b
}
raise("TypeError", "%s can't be coerced into Integer", classNameOf(v))
return nil
}

// integerBitOp applies a bitwise operator (&, |, ^) to an Integer receiver. An
// Integer or Bignum right operand is combined directly; any other operand except
// a Float runs Ruby's coerce protocol — rhs.coerce(self) yields a [x, y] pair and
Expand Down Expand Up @@ -8124,15 +8090,6 @@ func (vm *VM) integerShiftBig(a, m *big.Int) object.Value {
return nil
}

// gcdInt is the (non-negative) greatest common divisor by Euclid's algorithm.
func gcdInt(a, b int64) int64 {
a, b = absInt(a), absInt(b)
for b != 0 {
a, b = b, a%b
}
return a
}

// rubyEqual is the default Object#== : pointer identity for instances, and
// structural equality for the immutable value types.
func rubyEqual(a, b object.Value) bool {
Expand Down
114 changes: 114 additions & 0 deletions internal/vm/integer_bignum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm

import (
"math"
"math/big"

"github.com/go-embedded-ruby/ruby/internal/object"
)

// bigFloorDivmod returns Ruby's floored quotient and modulo of a and b (b != 0):
// the modulo takes the sign of the divisor, unlike Go's truncated QuoRem.
func bigFloorDivmod(a, b *big.Int) (*big.Int, *big.Int) {
q, r := new(big.Int), new(big.Int)
q.QuoRem(a, b, r)
if r.Sign() != 0 && (r.Sign() < 0) != (b.Sign() < 0) {
q.Sub(q, big.NewInt(1))
r.Add(r, b)
}
return q, r
}

// numCoerceDispatch runs Ruby's coerce protocol for an Integer operator whose
// right operand is neither an Integer/Bignum nor a Float: it calls arg.coerce
// (raising the canonical "X can't be coerced into Integer" TypeError when arg has
// none), then re-sends method on the returned [x, y] pair.
func (vm *VM) numCoerceDispatch(self, arg object.Value, method string) object.Value {
if vm.respondsToDynamic(arg, "coerce") {
pair := vm.send(arg, "coerce", []object.Value{self}, nil)
if arr, ok := pair.(*object.Array); ok && len(arr.Elems) == 2 {
return vm.send(arr.Elems[0], method, []object.Value{arr.Elems[1]}, nil)
}
raise("TypeError", "coerce must return [x, y]")
}
raise("TypeError", "%s can't be coerced into Integer", coerceName(arg))
return nil
}

// integerDivmod implements Integer#divmod: an Integer/Bignum operand gives a
// floored [quotient, modulo] pair of Integers; a Float operand gives an Integer
// quotient and a Float modulo (like Float#divmod); anything else runs the coerce
// protocol. Division by zero raises ZeroDivisionError.
func (vm *VM) integerDivmod(self, arg object.Value) object.Value {
if b, ok := object.BigOf(arg); ok {
if b.Sign() == 0 {
raise("ZeroDivisionError", "divided by 0")
}
a, _ := object.BigOf(self)
q, r := bigFloorDivmod(a, b)
return object.NewArray(object.NormInt(q), object.NormInt(r))
}
if bf, ok := arg.(object.Float); ok {
b := float64(bf)
if b == 0 {
raise("ZeroDivisionError", "divided by 0")
}
a, _ := toFloat(self)
q := math.Floor(a / b)
return object.NewArray(object.IntValue(int64(q)), object.Float(a-b*q))
}
return vm.numCoerceDispatch(self, arg, "divmod")
}

// integerRemainder implements Integer#remainder: the remainder truncates toward
// zero (keeping the dividend's sign), for an Integer/Bignum or Float operand.
func (vm *VM) integerRemainder(self, arg object.Value) object.Value {
if b, ok := object.BigOf(arg); ok {
if b.Sign() == 0 {
raise("ZeroDivisionError", "divided by 0")
}
a, _ := object.BigOf(self)
return object.NormInt(new(big.Int).Rem(a, b))
}
if bf, ok := arg.(object.Float); ok {
b := float64(bf)
if b == 0 {
raise("ZeroDivisionError", "divided by 0")
}
a, _ := toFloat(self)
return object.Float(a - b*math.Trunc(a/b))
}
return vm.numCoerceDispatch(self, arg, "remainder")
}

// integerGcdArg reads the operand of #gcd / #lcm / #gcdlcm as a big integer,
// raising MRI's "not an integer" TypeError for a Float or any non-integer.
func integerGcdArg(arg object.Value) *big.Int {
if b, ok := object.BigOf(arg); ok {
return b
}
raise("TypeError", "not an integer")
return nil
}

// bigGCD returns the non-negative greatest common divisor of a and b, with
// gcd(0, 0) == 0.
func bigGCD(a, b *big.Int) *big.Int {
return new(big.Int).GCD(nil, nil, new(big.Int).Abs(a), new(big.Int).Abs(b))
}

// bigLCM returns the non-negative least common multiple of a and b, or 0 when
// either is 0.
func bigLCM(a, b *big.Int) *big.Int {
if a.Sign() == 0 || b.Sign() == 0 {
return big.NewInt(0)
}
g := bigGCD(a, b)
l := new(big.Int).Quo(a, g)
l.Mul(l, b)
return l.Abs(l)
}
46 changes: 46 additions & 0 deletions internal/vm/numeric_gcdlcm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,49 @@ func TestNumericGcdlcmDivmod(t *testing.T) {
}
}
}

// TestIntegerBignumDivision covers the Integer division family — divmod,
// remainder, gcd, lcm, gcdlcm — with Bignum operands (receiver and argument),
// Float arguments, the coerce protocol and the error paths, asserted against MRI
// Ruby 4.0.6.
func TestIntegerBignumDivision(t *testing.T) {
cases := []struct{ src, want string }{
// Bignum argument and Bignum receiver, floored like MRI.
{`p 10.divmod(2**70)`, "[0, 10]\n"},
{`p (-10).divmod(2**70)`, "[-1, 1180591620717411303414]\n"},
{`p (2**70).divmod(7)`, "[168655945816773043346, 2]\n"},
{`p [10.remainder(2**70), (2**70).remainder(7)]`, "[10, 2]\n"},
{`p [10.gcd(2**70), (2**70).gcd(6), 0.gcd(0)]`, "[2, 2, 0]\n"},
{`p [(2**70).lcm(6), 12.gcdlcm(2**70)]`, "[3541774862152233910272, [4, 3541774862152233910272]]\n"},
// A Float argument gives an Integer quotient and a Float modulo/remainder.
{`p [10.divmod(3.0), 10.divmod(3.5), (-7).divmod(3.0)]`, "[[3, 1.0], [2, 3.0], [-3, 2.0]]\n"},
{`p [10.remainder(3.0), (-10).remainder(3.0)]`, "[1.0, -1.0]\n"},
// The coerce protocol handles a non-numeric argument that offers #coerce.
{`class Cx; def coerce(o); [o, 3]; end; end; p 10.divmod(Cx.new)`, "[3, 1]\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)
}
}

errs := []struct{ src, want string }{
{`10.divmod(0)`, "divided by 0"},
{`(2**70).divmod(0)`, "divided by 0"},
{`10.divmod(0.0)`, "divided by 0"},
{`(2**70).remainder(0)`, "divided by 0"},
{`10.remainder(0.0)`, "divided by 0"},
{`10.gcd(3.5)`, "not an integer"},
{`10.lcm("x")`, "not an integer"},
{`10.gcdlcm(nil)`, "not an integer"},
{`10.divmod(nil)`, "nil can't be coerced into Integer"},
{`10.divmod("x")`, "String can't be coerced into Integer"},
{`10.remainder(true)`, "true can't be coerced into Integer"},
{`class Bx; def coerce(o); 5; end; end; 10.divmod(Bx.new)`, "coerce must return [x, y]"},
}
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)
}
}
}
3 changes: 2 additions & 1 deletion internal/vm/phase6i_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ func TestBignum(t *testing.T) {

func TestBignumErrors(t *testing.T) {
cases := []struct{ name, src, want string }{
{"out_of_range_method", `(2 ** 100).gcd(2)`, "RangeError"},
// A Bignum receiver divided or modulo'd by zero still raises, even though
// #gcd et al. now accept Bignum operands (see TestIntegerBignumDivision).
{"div_zero", `(2 ** 100) / 0`, "ZeroDivisionError"},
{"mod_zero", `(2 ** 100) % 0`, "ZeroDivisionError"},
}
Expand Down
2 changes: 1 addition & 1 deletion scripts/conformance/rubyspec/FLOOR
Original file line number Diff line number Diff line change
@@ -1 +1 @@
15750
15770