diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index bd9d836d..e9b375a9 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -2186,6 +2186,17 @@ func (vm *VM) bootstrap() { return vm.tryConvert(args[0], cls, meth) }} } + // Integer.sqrt(n) returns the integer square root ⌊√nāŒ‹; the argument is + // coerced via #to_int (so a Float or #to_int object works) and a negative + // value raises Math::DomainError. + vm.cInteger.smethods["sqrt"] = &Method{name: "sqrt", owner: vm.cInteger, + native: func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + n := vm.integerArg(args[0]) + if n.Sign() < 0 { + raise("Math::DomainError", "Numerical argument is out of domain - \"isqrt\"") + } + return object.NormInt(new(big.Int).Sqrt(n)) + }} vm.cArray.define("first", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { a := self.(*object.Array) if len(args) == 0 { @@ -6520,6 +6531,26 @@ func (vm *VM) arrayAssoc(a *object.Array, key object.Value, idx int) object.Valu return object.NilV } +// integerArg coerces v to a big.Int for Integer.sqrt: an Integer or Bignum is +// used directly, any other value is converted via #to_int (so a Float or a +// user #to_int object works), and a value with no (Integer-returning) #to_int +// raises TypeError. +func (vm *VM) integerArg(v object.Value) *big.Int { + if b, ok := object.BigOf(v); ok { + return b + } + if vm.respondsToDynamic(v, "to_int") { + r := vm.send(v, "to_int", nil, nil) + if b, ok := object.BigOf(r); ok { + return b + } + raise("TypeError", "can't convert %s to Integer (%s#to_int gives %s)", + vm.classOf(v).name, vm.classOf(v).name, vm.classOf(r).name) + } + raise("TypeError", "no implicit conversion of %s into Integer", classNameOf(v)) + return nil +} + // tryConvert backs Array/Hash/String/Integer.try_convert: an object that is // already a kind of target is returned unchanged; otherwise, if it responds to // the named conversion method (#to_ary/#to_hash/#to_str/#to_int), that is called diff --git a/internal/vm/integer_sqrt_internal_test.go b/internal/vm/integer_sqrt_internal_test.go new file mode 100644 index 00000000..819a5850 --- /dev/null +++ b/internal/vm/integer_sqrt_internal_test.go @@ -0,0 +1,42 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestIntegerSqrt covers Integer.sqrt: the floored integer square root, exact +// squares, a Bignum argument and result, #to_int coercion of a Float and of a +// user object, the Math::DomainError for a negative argument, and the TypeError +// for a non-coercible argument (and a #to_int returning a non-Integer). Verified +// against ruby 4.0.6. +func TestIntegerSqrt(t *testing.T) { + cases := []struct{ src, want string }{ + {`p Integer.sqrt(0)`, `0`}, + {`p Integer.sqrt(1)`, `1`}, + {`p Integer.sqrt(24)`, `4`}, + {`p Integer.sqrt(25)`, `5`}, + {`p Integer.sqrt(10)`, `3`}, + {`p Integer.sqrt(10).is_a?(Integer)`, `true`}, + // Bignum argument and result. + {`p Integer.sqrt(10**400) == 10**200`, `true`}, + {`p Integer.sqrt(2**128).class`, `Integer`}, + // #to_int coercion: a Float (truncated) and a user object. + {`p Integer.sqrt(10.0)`, `3`}, + {`p Integer.sqrt(10.9)`, `3`}, + {`class K; def to_int; 25; end; end; p Integer.sqrt(K.new)`, `5`}, + // A negative argument raises Math::DomainError. + {`begin; Integer.sqrt(-4); rescue Math::DomainError => e; p e.message; end`, + `"Numerical argument is out of domain - \"isqrt\""`}, + // A non-coercible argument, and a #to_int returning a non-Integer, raise TypeError. + {`begin; Integer.sqrt("test"); rescue TypeError => e; p e.class; end`, `TypeError`}, + {`class Bad; def to_int; "x"; end; end +begin; Integer.sqrt(Bad.new); rescue TypeError => e; p e.class; end`, `TypeError`}, + } + 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") + } + } +}