From c8468392359ac507d935488accb8beed9438abf7 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 21 Aug 2026 10:52:13 +0200 Subject: [PATCH] Numeric#step: support keyword (to:/by:) and mixed arguments Integer#step and Float#step only accepted positional (limit, step) arguments, so the keyword form 1.step(by: 2, to: 10) and the mixed form 1.step(10, by: 2) raised "can't iterate from 1" (the keyword Hash was taken as the limit). numeric/step_spec went 104 -> 119. A shared stepBounds helper resolves (limit, step) from the positional and to:/by: keyword arguments, applying MRI's rules: a limit or step may be given positionally or by keyword but not both, an unknown keyword or more than two positional arguments is an ArgumentError, and a missing limit means an unbounded (endless) walk. Both step methods now route a nil limit to numericStepEndless and share the sized-Enumerator size. Also aligned three edges with MRI: a String step raises ArgumentError (not a silent numeric parse) at iteration and from #size (rejectStringStep in numericStep/numericStepEndless/stepSize); an infinite step yields the start value exactly once instead of looping; and stepSize reports an unbounded (nil-limit) sequence as infinite and the both-infinite / infinite-step cases the way MRI counts them (1 or 0). A bare step with no limit is now the unbounded walk MRI performs, not an ArgumentError; two tests that had encoded the old behaviour are updated. Remaining step_spec failures are Enumerator::ArithmeticSequence (a separate unimplemented class) and a pre-existing VM limitation where a block passed to a lambda is not delivered to its body, which the shared example harness relies on. Verified against ruby 4.0.6; numeric/step_spec 104 -> 119, whole-suite coverage gate stays at 100.0%, full language+core sweep shows no regressions. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 101 +++++++++++++++++-- internal/vm/integer_float_residuals_test.go | 7 +- internal/vm/numeric_edges.go | 16 +-- internal/vm/numeric_step_kw_internal_test.go | 60 +++++++++++ internal/vm/step_test.go | 6 +- 5 files changed, 165 insertions(+), 25 deletions(-) create mode 100644 internal/vm/numeric_step_kw_internal_test.go diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index e9b375a9..2f33a2fd 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -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 }) @@ -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) @@ -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) { @@ -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 { @@ -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. diff --git a/internal/vm/integer_float_residuals_test.go b/internal/vm/integer_float_residuals_test.go index 2b64f762..bc1be5d2 100644 --- a/internal/vm/integer_float_residuals_test.go +++ b/internal/vm/integer_float_residuals_test.go @@ -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) diff --git a/internal/vm/numeric_edges.go b/internal/vm/numeric_edges.go index ed23fccc..a1b2a88e 100644 --- a/internal/vm/numeric_edges.go +++ b/internal/vm/numeric_edges.go @@ -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 }) } diff --git a/internal/vm/numeric_step_kw_internal_test.go b/internal/vm/numeric_step_kw_internal_test.go new file mode 100644 index 00000000..52a92091 --- /dev/null +++ b/internal/vm/numeric_step_kw_internal_test.go @@ -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") + } + } +} diff --git a/internal/vm/step_test.go b/internal/vm/step_test.go index 4ca8778a..6f02a1b9 100644 --- a/internal/vm/step_test.go +++ b/internal/vm/step_test.go @@ -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") {