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
29 changes: 16 additions & 13 deletions internal/vm/arith.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
}
72 changes: 8 additions & 64 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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])
})
Expand Down Expand Up @@ -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)
Expand Down
59 changes: 59 additions & 0 deletions internal/vm/integer_float_residuals_internal_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading