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
101 changes: 90 additions & 11 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -4773,23 +4773,20 @@ func (vm *VM) bootstrap() {
})

vm.cInteger.define("step", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value {
if len(args) < 1 {
raise("ArgumentError", "wrong number of arguments (given 0, expected 1..2)")
}
step := object.Value(object.IntValue(1))
if len(args) > 1 {
step = args[1]
}
limit, step := vm.stepBounds(args)
if blk == nil {
// With a size, so that Enumerator#size can answer without walking
// the sequence. Asked to count 1.step(Float::INFINITY) it never
// would: it allocated 30.9 GB before a CI runner died under it.
limit := args[0]
return enumForSized(self, "step", func(*VM) object.Value {
return stepSize(self, limit, step)
}, args...)
}
vm.numericStep(blk, self, args[0], step, false)
if object.IsNil(limit) {
vm.numericStepEndless(blk, self, step)
} else {
vm.numericStep(blk, self, limit, step, false)
}
return self
})

Expand Down Expand Up @@ -8076,11 +8073,68 @@ func succString(s string) string {
return string(append([]byte{1}, b...)) // every byte overflowed
}

// stepBounds resolves the (limit, step) pair of a Numeric#step call from its
// positional and keyword (to:/by:) arguments. A limit or step may be given
// positionally or by keyword but not both; an unknown keyword, a zero step, or
// more than two positional arguments raises ArgumentError. A missing limit is
// returned as nil, meaning an unbounded (endless) walk.
func (vm *VM) stepBounds(args []object.Value) (limit, step object.Value) {
limit, step = object.NilV, object.Value(object.IntValue(1))
pos := args
kw := trailingKwHash(args)
if kw != nil {
pos = args[:len(args)-1]
}
if len(pos) > 2 {
raise("ArgumentError", "wrong number of arguments (given %d, expected 1..2)", len(pos))
}
hasLimit, hasStep := false, false
if len(pos) >= 1 {
limit, hasLimit = pos[0], true
}
if len(pos) >= 2 {
step, hasStep = pos[1], true
}
if kw != nil {
if v, ok := kw.Get(object.SymVal("to")); ok {
if hasLimit {
raise("ArgumentError", "to is given twice")
}
limit = v
}
if v, ok := kw.Get(object.SymVal("by")); ok {
if hasStep {
raise("ArgumentError", "step is given twice")
}
step = v
}
for _, k := range kw.Keys {
if k != object.SymVal("to") && k != object.SymVal("by") {
raise("ArgumentError", "unknown keyword: %s", k.Inspect())
}
}
}
if valueEqual(step, object.IntValue(0)) {
raise("ArgumentError", "step can't be 0")
}
return limit, step
}

// rejectStringStep raises ArgumentError for a String step, which MRI refuses to
// coerce even when it looks numeric ("2" / "0.1" / "1/3"); other types fall
// through to the normal numeric handling.
func rejectStringStep(step object.Value) {
if _, ok := step.(*object.String); ok {
raise("ArgumentError", "step can't be String")
}
}

// numericStep drives Range#step / Integer#step: it yields lo, lo+step, … toward
// hi (inclusive unless exclusive). All-integer operands keep an integer walk
// (exact); any float operand switches to an index-based float walk that avoids
// accumulated drift. step must be non-zero.
func (vm *VM) numericStep(blk *Proc, loV, hiV, stepV object.Value, exclusive bool) {
rejectStringStep(stepV)
li, loInt := loV.(object.Integer)
hi2, hiInt := hiV.(object.Integer)
si, stepInt := stepV.(object.Integer)
Expand All @@ -8104,6 +8158,15 @@ func (vm *VM) numericStep(blk *Proc, loV, hiV, stepV object.Value, exclusive boo
if step == 0 {
raise("ArgumentError", "step can't be 0")
}
if math.IsInf(step, 0) {
// An infinite step yields only the start value (once), when it lies on the
// correct side of the limit — the next term would be another Infinity, so
// walking lo+i*step would loop forever otherwise.
if stepInRange(lo, hi, step, exclusive) {
vm.callBlock(blk, []object.Value{object.Float(lo)})
}
return
}
for i := 0; ; i++ {
v := lo + float64(i)*step
if !stepInRange(v, hi, step, exclusive) {
Expand All @@ -8120,6 +8183,7 @@ func (vm *VM) numericStep(blk *Proc, loV, hiV, stepV object.Value, exclusive boo
// float error does not drift). A non-numeric begin raises the same TypeError as
// the bounded path.
func (vm *VM) numericStepEndless(blk *Proc, loV, stepV object.Value) {
rejectStringStep(stepV)
li, loInt := loV.(object.Integer)
si, stepInt := stepV.(object.Integer)
if loInt && stepInt {
Expand Down Expand Up @@ -8173,15 +8237,30 @@ func stepInRange(v, hi, step float64, exclusive bool) bool {
// error, not only running the sequence. An argument that is not a number has no
// size to give and reports the nil MRI reports for an unknown one.
func stepSize(from, limit, step object.Value) object.Value {
rejectStringStep(step)
f, okF := toFloat(from)
l, okL := toFloat(limit)
s, okS := toFloat(step)
if !okF || !okL || !okS {
if !okF || !okS {
return object.NilV
}
if s == 0 {
raise("ArgumentError", "step can't be 0")
}
if object.IsNil(limit) {
return object.Float(math.Inf(1)) // unbounded: endlessly many
}
l, okL := toFloat(limit)
if !okL {
return object.NilV
}
if math.IsInf(s, 0) {
// An infinite step yields at most the start value: just it when it lies on
// the correct side of the limit, nothing when it is already past it.
if (s > 0 && f <= l) || (s < 0 && f >= l) {
return object.IntValue(1)
}
return object.IntValue(0)
}
if math.IsInf(l, 0) {
// Travelling towards an end that never comes yields for ever; away from
// it yields nothing at all.
Expand Down
7 changes: 4 additions & 3 deletions internal/vm/integer_float_residuals_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,10 @@ func TestFloatStep(t *testing.T) {
}
}

// No limit argument raises ArgumentError; a zero step raises ArgumentError.
if err := runErr(t, `1.0.step { |x| }`); err == nil || !strings.Contains(err.Error(), "given 0") {
t.Errorf("step (no args) err=%v, want ArgumentError", err)
// A bare Float#step (no limit) is an unbounded walk of step 1.0, matching MRI
// (the block must break out); a zero step raises ArgumentError.
if got := eval(t, `r = []; 1.0.step { |x| r << x; break if x >= 3.0 }; p r`); got != "[1.0, 2.0, 3.0]\n" {
t.Errorf("bare Float#step got=%q, want unbounded walk", got)
}
if err := runErr(t, `1.0.step(3.0, 0) { |x| }`); err == nil || !strings.Contains(err.Error(), "step can't be 0") {
t.Errorf("step(3.0,0) err=%v, want step can't be 0", err)
Expand Down
16 changes: 8 additions & 8 deletions internal/vm/numeric_edges.go
Original file line number Diff line number Diff line change
Expand Up @@ -503,17 +503,17 @@ func (vm *VM) registerNumericEdges() {
// Float#step — mirrors Integer#step: an enumerator without a block, otherwise
// walking [self, limit] by step (default 1), yielding Floats via numericStep.
vm.cFloat.define("step", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value {
if len(args) < 1 {
raise("ArgumentError", "wrong number of arguments (given 0, expected 1..2)")
}
limit, step := vm.stepBounds(args)
if blk == nil {
return enumFor(self, "step", args...)
return enumForSized(self, "step", func(*VM) object.Value {
return stepSize(self, limit, step)
}, args...)
}
step := object.Value(object.IntValue(1))
if len(args) > 1 {
step = args[1]
if object.IsNil(limit) {
vm.numericStepEndless(blk, self, step)
} else {
vm.numericStep(blk, self, limit, step, false)
}
vm.numericStep(blk, self, args[0], step, false)
return self
})
}
Expand Down
60 changes: 60 additions & 0 deletions internal/vm/numeric_step_kw_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm

import "testing"

// TestNumericStepKeyword covers the keyword (to:/by:) and mixed argument forms of
// Integer#step and Float#step, an unbounded (endless) walk when no limit is
// given, the combinatorial Enumerator#size (including the Float::INFINITY edges),
// an infinite step yielding the start once, and the ArgumentError validation
// (zero step, a String step, a limit or step given both positionally and by
// keyword, an unknown keyword). Verified against ruby 4.0.6.
func TestNumericStepKeyword(t *testing.T) {
cases := []struct{ src, want string }{
// Keyword forms.
{`p 1.step(by: 2, to: 10).to_a`, `[1, 3, 5, 7, 9]`},
{`p 1.step(to: 5).to_a`, `[1, 2, 3, 4, 5]`},
{`p 10.step(by: -2, to: 1).to_a`, `[10, 8, 6, 4, 2]`},
{`p 1.5.step(by: 0.5, to: 3).to_a`, `[1.5, 2.0, 2.5, 3.0]`},
// Mixed positional limit + keyword step.
{`p 1.step(10, by: 3).to_a`, `[1, 4, 7, 10]`},
// Endless (no limit): the block breaks out; the enumerator is infinite.
{`r = []; 1.step(by: 2) { |x| r << x; break if x >= 5 }; p r`, `[1, 3, 5]`},
{`p 1.step(by: 2).first(3)`, `[1, 3, 5]`},
{`p 1.5.step(by: 0.5).first(3)`, `[1.5, 2.0, 2.5]`},
// Bare step (no args) defaults to an unbounded step of 1.
{`r = []; 1.step { |x| r << x; break if x >= 4 }; p r`, `[1, 2, 3, 4]`},
// Enumerator#size, including the Float::INFINITY edges.
{`p 1.step(by: 2, to: 10).size`, `5`},
{`p 1.step(by: 42).size`, `Infinity`},
{`p 1.step(to: Float::INFINITY, by: 42).size`, `Infinity`},
{`p 1.step(to: -Float::INFINITY, by: -42).size`, `Infinity`},
{`p 1.step(to: Float::INFINITY, by: Float::INFINITY).size`, `1`},
{`p 1.step(to: -Float::INFINITY, by: -Float::INFINITY).size`, `1`},
{`p 1.step(to: 10, by: Float::INFINITY).size`, `1`},
{`p 1.step(to: -10, by: Float::INFINITY).size`, `0`},
{`p 1.step(to: Float::INFINITY, by: -42).size`, `0`},
// An unreachable limit (walking the wrong way) has size 0.
{`p 1.step(to: -5).size`, `0`},
{`p 1.step(to: -5, by: -1).size`, `7`},
// An infinite step yields the start value exactly once.
{`r = []; (1.0/0).step(1.0/0, 1.0/0) { |x| r << x }; p r`, `[Infinity]`},
// Validation: zero step, a String step, doubled limit/step, unknown keyword.
{`begin; 1.step(5, by: 0) {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
{`begin; 1.step(2, by: 0.0) {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
{`begin; 1.step(5, "2") {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
{`begin; 1.step(5, "2").size; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
{`begin; 1.step(5, 1, to: 5) {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
{`begin; 1.step(5, 1, by: 5) {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
{`begin; 1.step(foo: 1) {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
{`begin; 1.step(1, 2, 3) {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`},
}
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")
}
}
}
6 changes: 3 additions & 3 deletions internal/vm/step_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ func TestStep(t *testing.T) {
t.Errorf("src=%q got=%q want=%q", c.src, got, c.want)
}
}
// step can't be 0 (integer and float walks) raises ArgumentError; missing the
// Integer#step limit raises too; a String range with a 0 step raises the same.
// step can't be 0 (integer and float walks) raises ArgumentError; a String
// range with a 0 step raises the same. (A bare Integer#step with no limit is
// an unbounded walk, not an error — see TestNumericStepKeyword.)
for _, src := range []string{
`(1..3).step(0) { |x| }`,
`(1.0..3.0).step(0.0) { |x| }`,
`1.step(3, 0) { |x| }`,
`1.step`,
`("a".."c").step(0) { |x| }`,
} {
if err := runErr(t, src); err == nil || !strings.Contains(err.Error(), "ArgumentError") {
Expand Down