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
69 changes: 65 additions & 4 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -4490,11 +4490,11 @@ func (vm *VM) bootstrap() {
})
// Bitwise / shift operators (arbitrary precision via big.Int, so a left shift
// promotes to a Bignum and bitwise ops work on Bignums too).
vm.cInteger.define("<<", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return shiftInt(bigVal(self), intArg(args[0]))
vm.cInteger.define("<<", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return vm.integerShift(bigVal(self), args[0], false)
})
vm.cInteger.define(">>", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return shiftInt(bigVal(self), -intArg(args[0]))
vm.cInteger.define(">>", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return vm.integerShift(bigVal(self), args[0], true)
})
vm.cInteger.define("&", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return object.NormInt(new(big.Int).And(bigVal(self), bigArg(args[0])))
Expand Down Expand Up @@ -7973,6 +7973,67 @@ func shiftInt(a *big.Int, n int64) object.Value {
return object.NormInt(new(big.Int).Rsh(a, uint(-n)))
}

// integerShift implements Integer#<< (right=false) and Integer#>> (right=true).
// The common case — a machine-int shift amount — takes the fast path straight to
// shiftInt; otherwise the amount is coerced via #to_int and a shift amount that
// does not fit a machine int is handled degenerately (see integerShiftBig).
func (vm *VM) integerShift(a *big.Int, arg object.Value, right bool) object.Value {
if i, ok := arg.(object.Integer); ok {
n := int64(i)
if right {
n = -n
}
return shiftInt(a, n)
}
m := vm.shiftCount(arg)
if right {
m = new(big.Int).Neg(m)
}
return vm.integerShiftBig(a, m)
}

// shiftCount coerces a shift argument to an integer count: an Integer or Bignum
// directly, otherwise via #to_int (which must return an Integer). It matches
// MRI's TypeErrors for a non-integer that has no #to_int and for a #to_int that
// returns a non-integer.
func (vm *VM) shiftCount(arg object.Value) *big.Int {
if z, ok := object.BigOf(arg); ok {
return z
}
if vm.respondsToDynamic(arg, "to_int") {
r := vm.send(arg, "to_int", nil, nil)
if z, ok := object.BigOf(r); ok {
return z
}
raise("TypeError", "can't convert %s to Integer (%s#to_int gives %s)",
vm.classOf(arg).name, vm.classOf(arg).name, vm.classOf(r).name)
}
raise("TypeError", "no implicit conversion of %s into Integer", vm.classOf(arg).name)
return nil
}

// integerShiftBig applies a shift by an amount m that (once its sign is folded in)
// may be a Bignum. A machine-int amount still goes through shiftInt; a Bignum
// amount is degenerate: a huge right shift collapses to 0 (or -1 for a negative
// receiver), a huge left shift of zero stays 0, and any other huge left shift
// would exceed addressable memory, so it raises RangeError as MRI does.
func (vm *VM) integerShiftBig(a, m *big.Int) object.Value {
if m.IsInt64() {
return shiftInt(a, m.Int64())
}
if m.Sign() < 0 {
if a.Sign() < 0 {
return object.IntValue(-1)
}
return object.IntValue(0)
}
if a.Sign() == 0 {
return object.IntValue(0)
}
raise("RangeError", "shift width too big")
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)
Expand Down
49 changes: 49 additions & 0 deletions internal/vm/integer_shift_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm

import "testing"

// TestIntegerShift covers Integer#<< and Integer#>> for shift amounts that a
// machine int cannot hold and for a #to_int-coercible argument, alongside the
// ordinary small/Bignum shifts. A shift amount beyond a machine int is
// degenerate: a huge right shift collapses to 0 (or -1 for a negative receiver),
// a huge left shift of zero stays 0, and any other huge left shift raises
// RangeError. Verified against ruby 4.0.6.
func TestIntegerShift(t *testing.T) {
cases := []struct{ src, want string }{
// Ordinary shifts still work, promoting to Bignum as needed.
{`p 5 << 2`, `20`},
{`p 20 >> 2`, `5`},
{`p (2**64) << 4`, `295147905179352825856`},
{`p (2**70) >> 1`, `590295810358705651712`},
// A huge negative shift amount (right shift by a Bignum): 0, or -1 for a
// negative receiver.
{`p 5 << -(2**64)`, `0`},
{`p (-5) << -(2**64)`, `-1`},
{`p 5 >> (2**64)`, `0`},
{`p (-5) >> (2**64)`, `-1`},
{`p (2**100) >> (2**64)`, `0`},
// A huge positive left shift of zero stays zero.
{`p 0 << (2**64)`, `0`},
{`p 0 >> -(2**64)`, `0`},
// Any other huge positive left shift raises RangeError (would exceed
// addressable memory).
{`begin; 1 << (2**67); rescue RangeError => e; p e.class; end`, `RangeError`},
{`begin; (-1) << (2**67); rescue RangeError => e; p e.class; end`, `RangeError`},
{`begin; 3 >> -(2**67); rescue RangeError => e; p e.class; end`, `RangeError`},
// A non-Integer argument is coerced with #to_int.
{`class I; def to_int; 3; end; end; p 5 << I.new`, `40`},
{`class I; def to_int; 3; end; end; p 160 >> I.new`, `20`},
// A missing #to_int, or one returning a non-Integer, raises TypeError.
{`begin; 5 << Object.new; rescue TypeError => e; p e.message; end`, `"no implicit conversion of Object into Integer"`},
{`class B; def to_int; "x"; end; end; begin; 5 << B.new; rescue TypeError => e; p e.message; end`, `"can't convert B to Integer (B#to_int gives String)"`},
}
for _, c := range cases {
if got := eval(t, c.src); got != c.want+"\n" {
t.Errorf("src=%q got=%q want=%q", c.src, got, c.want+"\n")
}
}
}