Skip to content

Commit fd48f2c

Browse files
tannevaledclaude
andauthored
Integer divmod/remainder/gcd/lcm/gcdlcm accept Bignum and Float operands (#466)
The Integer division family coerced both operands through int64, so a Bignum receiver or argument raised a spurious RangeError ("bignum too big to convert into 'long'") or a TypeError, and a Float argument to divmod/remainder was rejected outright. They now compute in math/big when either side is a Bignum: - divmod / gcdlcm are floored, matching MRI's sign-of-divisor modulo. - remainder truncates toward zero. - gcd / lcm / gcdlcm accept any Integer/Bignum, raise "not an integer" for a Float or non-integer, and treat gcd(0,0) as 0. - divmod / remainder accept a Float argument (Integer quotient, Float modulo), run the coerce protocol for a non-numeric argument that offers #coerce, and otherwise raise the canonical "X can't be coerced into Integer"; division by zero still raises ZeroDivisionError, including for a Bignum receiver. The now-unused int64 helpers (gcdInt / absInt / bigArg) are removed. Verified against ruby 4.0.6. Whole-package coverage stays at 100%; the ruby/spec floor rises 15750 -> 15770 (language+core now 15834 passing, +19). Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1 parent fd1464a commit fd48f2c

5 files changed

Lines changed: 175 additions & 57 deletions

File tree

‎internal/vm/builtins.go‎

Lines changed: 12 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -4534,14 +4534,12 @@ func (vm *VM) bootstrap() {
45344534
return object.NormInt(new(big.Int).Not(bigVal(self)))
45354535
})
45364536
vm.cInteger.define("gcd", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
4537-
return object.IntValue(gcdInt(intOf(self), intArg(args[0])))
4537+
a, _ := object.BigOf(self)
4538+
return object.NormInt(bigGCD(a, integerGcdArg(args[0])))
45384539
})
45394540
vm.cInteger.define("lcm", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
4540-
a, b := intOf(self), intArg(args[0])
4541-
if a == 0 || b == 0 {
4542-
return object.IntValue(0)
4543-
}
4544-
return object.IntValue(absInt(a / gcdInt(a, b) * b))
4541+
a, _ := object.BigOf(self)
4542+
return object.NormInt(bigLCM(a, integerGcdArg(args[0])))
45454543
})
45464544
fdiv := func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
45474545
a, _ := toFloat(self)
@@ -4608,30 +4606,16 @@ func (vm *VM) bootstrap() {
46084606
}
46094607
return object.IntValue(c)
46104608
})
4611-
vm.cInteger.define("divmod", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
4612-
a, b := intOf(self), intArg(args[0])
4613-
if b == 0 {
4614-
raise("ZeroDivisionError", "divided by 0")
4615-
}
4616-
return object.NewArray(object.IntValue(floorDiv(a, b)), object.IntValue(floorMod(a, b)))
4609+
vm.cInteger.define("divmod", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
4610+
return vm.integerDivmod(self, args[0])
46174611
})
46184612
vm.cInteger.define("gcdlcm", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
4619-
a, b := intOf(self), intArg(args[0])
4620-
g := gcdInt(a, b)
4621-
var lcm int64
4622-
if a != 0 && b != 0 {
4623-
lcm = absInt(a / g * b)
4624-
}
4625-
return object.NewArray(object.IntValue(g), object.IntValue(lcm))
4626-
})
4627-
vm.cInteger.define("remainder", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
4628-
// remainder truncates toward zero (keeping the dividend's sign), unlike %
4629-
// which floors — exactly Go's % operator.
4630-
a, b := intOf(self), intArg(args[0])
4631-
if b == 0 {
4632-
raise("ZeroDivisionError", "divided by 0")
4633-
}
4634-
return object.IntValue(a % b)
4613+
a, _ := object.BigOf(self)
4614+
b := integerGcdArg(args[0])
4615+
return object.NewArray(object.NormInt(bigGCD(a, b)), object.NormInt(bigLCM(a, b)))
4616+
})
4617+
vm.cInteger.define("remainder", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
4618+
return vm.integerRemainder(self, args[0])
46354619
})
46364620
// truncate with ndigits >= 0 leaves an Integer unchanged; with ndigits < 0 it
46374621
// truncates toward zero to the nearest 10**(-ndigits). Integer#round is defined
@@ -7636,14 +7620,6 @@ func powNumeric(_ *VM, self object.Value, args []object.Value, _ *Proc) object.V
76367620
return object.Float(math.Pow(a, b))
76377621
}
76387622

7639-
// absInt is the absolute value of an int64.
7640-
func absInt(n int64) int64 {
7641-
if n < 0 {
7642-
return -n
7643-
}
7644-
return n
7645-
}
7646-
76477623
// stringLineSegs splits the receiver into line segments for String#lines /
76487624
// #each_line, honouring the optional record separator (default "\n"; nil = the
76497625
// whole string; "" = paragraph mode) and a chomp: keyword that strips the
@@ -7979,16 +7955,6 @@ func bigVal(v object.Value) *big.Int {
79797955
return b
79807956
}
79817957

7982-
// bigArg returns an integer argument as a *big.Int, raising TypeError when the
7983-
// argument is not an Integer/Bignum (as Ruby's bitwise operators do).
7984-
func bigArg(v object.Value) *big.Int {
7985-
if b, ok := object.BigOf(v); ok {
7986-
return b
7987-
}
7988-
raise("TypeError", "%s can't be coerced into Integer", classNameOf(v))
7989-
return nil
7990-
}
7991-
79927958
// integerBitOp applies a bitwise operator (&, |, ^) to an Integer receiver. An
79937959
// Integer or Bignum right operand is combined directly; any other operand except
79947960
// a Float runs Ruby's coerce protocol — rhs.coerce(self) yields a [x, y] pair and
@@ -8124,15 +8090,6 @@ func (vm *VM) integerShiftBig(a, m *big.Int) object.Value {
81248090
return nil
81258091
}
81268092

8127-
// gcdInt is the (non-negative) greatest common divisor by Euclid's algorithm.
8128-
func gcdInt(a, b int64) int64 {
8129-
a, b = absInt(a), absInt(b)
8130-
for b != 0 {
8131-
a, b = b, a%b
8132-
}
8133-
return a
8134-
}
8135-
81368093
// rubyEqual is the default Object#== : pointer identity for instances, and
81378094
// structural equality for the immutable value types.
81388095
func rubyEqual(a, b object.Value) bool {

‎internal/vm/integer_bignum.go‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
// Copyright (c) the go-embedded-ruby/ruby authors
2+
//
3+
// SPDX-License-Identifier: BSD-3-Clause
4+
5+
package vm
6+
7+
import (
8+
"math"
9+
"math/big"
10+
11+
"github.com/go-embedded-ruby/ruby/internal/object"
12+
)
13+
14+
// bigFloorDivmod returns Ruby's floored quotient and modulo of a and b (b != 0):
15+
// the modulo takes the sign of the divisor, unlike Go's truncated QuoRem.
16+
func bigFloorDivmod(a, b *big.Int) (*big.Int, *big.Int) {
17+
q, r := new(big.Int), new(big.Int)
18+
q.QuoRem(a, b, r)
19+
if r.Sign() != 0 && (r.Sign() < 0) != (b.Sign() < 0) {
20+
q.Sub(q, big.NewInt(1))
21+
r.Add(r, b)
22+
}
23+
return q, r
24+
}
25+
26+
// numCoerceDispatch runs Ruby's coerce protocol for an Integer operator whose
27+
// right operand is neither an Integer/Bignum nor a Float: it calls arg.coerce
28+
// (raising the canonical "X can't be coerced into Integer" TypeError when arg has
29+
// none), then re-sends method on the returned [x, y] pair.
30+
func (vm *VM) numCoerceDispatch(self, arg object.Value, method string) object.Value {
31+
if vm.respondsToDynamic(arg, "coerce") {
32+
pair := vm.send(arg, "coerce", []object.Value{self}, nil)
33+
if arr, ok := pair.(*object.Array); ok && len(arr.Elems) == 2 {
34+
return vm.send(arr.Elems[0], method, []object.Value{arr.Elems[1]}, nil)
35+
}
36+
raise("TypeError", "coerce must return [x, y]")
37+
}
38+
raise("TypeError", "%s can't be coerced into Integer", coerceName(arg))
39+
return nil
40+
}
41+
42+
// integerDivmod implements Integer#divmod: an Integer/Bignum operand gives a
43+
// floored [quotient, modulo] pair of Integers; a Float operand gives an Integer
44+
// quotient and a Float modulo (like Float#divmod); anything else runs the coerce
45+
// protocol. Division by zero raises ZeroDivisionError.
46+
func (vm *VM) integerDivmod(self, arg object.Value) object.Value {
47+
if b, ok := object.BigOf(arg); ok {
48+
if b.Sign() == 0 {
49+
raise("ZeroDivisionError", "divided by 0")
50+
}
51+
a, _ := object.BigOf(self)
52+
q, r := bigFloorDivmod(a, b)
53+
return object.NewArray(object.NormInt(q), object.NormInt(r))
54+
}
55+
if bf, ok := arg.(object.Float); ok {
56+
b := float64(bf)
57+
if b == 0 {
58+
raise("ZeroDivisionError", "divided by 0")
59+
}
60+
a, _ := toFloat(self)
61+
q := math.Floor(a / b)
62+
return object.NewArray(object.IntValue(int64(q)), object.Float(a-b*q))
63+
}
64+
return vm.numCoerceDispatch(self, arg, "divmod")
65+
}
66+
67+
// integerRemainder implements Integer#remainder: the remainder truncates toward
68+
// zero (keeping the dividend's sign), for an Integer/Bignum or Float operand.
69+
func (vm *VM) integerRemainder(self, arg object.Value) object.Value {
70+
if b, ok := object.BigOf(arg); ok {
71+
if b.Sign() == 0 {
72+
raise("ZeroDivisionError", "divided by 0")
73+
}
74+
a, _ := object.BigOf(self)
75+
return object.NormInt(new(big.Int).Rem(a, b))
76+
}
77+
if bf, ok := arg.(object.Float); ok {
78+
b := float64(bf)
79+
if b == 0 {
80+
raise("ZeroDivisionError", "divided by 0")
81+
}
82+
a, _ := toFloat(self)
83+
return object.Float(a - b*math.Trunc(a/b))
84+
}
85+
return vm.numCoerceDispatch(self, arg, "remainder")
86+
}
87+
88+
// integerGcdArg reads the operand of #gcd / #lcm / #gcdlcm as a big integer,
89+
// raising MRI's "not an integer" TypeError for a Float or any non-integer.
90+
func integerGcdArg(arg object.Value) *big.Int {
91+
if b, ok := object.BigOf(arg); ok {
92+
return b
93+
}
94+
raise("TypeError", "not an integer")
95+
return nil
96+
}
97+
98+
// bigGCD returns the non-negative greatest common divisor of a and b, with
99+
// gcd(0, 0) == 0.
100+
func bigGCD(a, b *big.Int) *big.Int {
101+
return new(big.Int).GCD(nil, nil, new(big.Int).Abs(a), new(big.Int).Abs(b))
102+
}
103+
104+
// bigLCM returns the non-negative least common multiple of a and b, or 0 when
105+
// either is 0.
106+
func bigLCM(a, b *big.Int) *big.Int {
107+
if a.Sign() == 0 || b.Sign() == 0 {
108+
return big.NewInt(0)
109+
}
110+
g := bigGCD(a, b)
111+
l := new(big.Int).Quo(a, g)
112+
l.Mul(l, b)
113+
return l.Abs(l)
114+
}

‎internal/vm/numeric_gcdlcm_test.go‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,49 @@ func TestNumericGcdlcmDivmod(t *testing.T) {
3939
}
4040
}
4141
}
42+
43+
// TestIntegerBignumDivision covers the Integer division family — divmod,
44+
// remainder, gcd, lcm, gcdlcm — with Bignum operands (receiver and argument),
45+
// Float arguments, the coerce protocol and the error paths, asserted against MRI
46+
// Ruby 4.0.6.
47+
func TestIntegerBignumDivision(t *testing.T) {
48+
cases := []struct{ src, want string }{
49+
// Bignum argument and Bignum receiver, floored like MRI.
50+
{`p 10.divmod(2**70)`, "[0, 10]\n"},
51+
{`p (-10).divmod(2**70)`, "[-1, 1180591620717411303414]\n"},
52+
{`p (2**70).divmod(7)`, "[168655945816773043346, 2]\n"},
53+
{`p [10.remainder(2**70), (2**70).remainder(7)]`, "[10, 2]\n"},
54+
{`p [10.gcd(2**70), (2**70).gcd(6), 0.gcd(0)]`, "[2, 2, 0]\n"},
55+
{`p [(2**70).lcm(6), 12.gcdlcm(2**70)]`, "[3541774862152233910272, [4, 3541774862152233910272]]\n"},
56+
// A Float argument gives an Integer quotient and a Float modulo/remainder.
57+
{`p [10.divmod(3.0), 10.divmod(3.5), (-7).divmod(3.0)]`, "[[3, 1.0], [2, 3.0], [-3, 2.0]]\n"},
58+
{`p [10.remainder(3.0), (-10).remainder(3.0)]`, "[1.0, -1.0]\n"},
59+
// The coerce protocol handles a non-numeric argument that offers #coerce.
60+
{`class Cx; def coerce(o); [o, 3]; end; end; p 10.divmod(Cx.new)`, "[3, 1]\n"},
61+
}
62+
for _, c := range cases {
63+
if got := eval(t, c.src); got != c.want {
64+
t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want)
65+
}
66+
}
67+
68+
errs := []struct{ src, want string }{
69+
{`10.divmod(0)`, "divided by 0"},
70+
{`(2**70).divmod(0)`, "divided by 0"},
71+
{`10.divmod(0.0)`, "divided by 0"},
72+
{`(2**70).remainder(0)`, "divided by 0"},
73+
{`10.remainder(0.0)`, "divided by 0"},
74+
{`10.gcd(3.5)`, "not an integer"},
75+
{`10.lcm("x")`, "not an integer"},
76+
{`10.gcdlcm(nil)`, "not an integer"},
77+
{`10.divmod(nil)`, "nil can't be coerced into Integer"},
78+
{`10.divmod("x")`, "String can't be coerced into Integer"},
79+
{`10.remainder(true)`, "true can't be coerced into Integer"},
80+
{`class Bx; def coerce(o); 5; end; end; 10.divmod(Bx.new)`, "coerce must return [x, y]"},
81+
}
82+
for _, c := range errs {
83+
if err := runErr(t, c.src); err == nil || !strings.Contains(err.Error(), c.want) {
84+
t.Errorf("src=%q err=%v, want substring %q", c.src, err, c.want)
85+
}
86+
}
87+
}

‎internal/vm/phase6i_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ func TestBignum(t *testing.T) {
6161

6262
func TestBignumErrors(t *testing.T) {
6363
cases := []struct{ name, src, want string }{
64-
{"out_of_range_method", `(2 ** 100).gcd(2)`, "RangeError"},
64+
// A Bignum receiver divided or modulo'd by zero still raises, even though
65+
// #gcd et al. now accept Bignum operands (see TestIntegerBignumDivision).
6566
{"div_zero", `(2 ** 100) / 0`, "ZeroDivisionError"},
6667
{"mod_zero", `(2 ** 100) % 0`, "ZeroDivisionError"},
6768
}

‎scripts/conformance/rubyspec/FLOOR‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
15750
1+
15770

0 commit comments

Comments
 (0)