diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index f620f7a6..25e9a1c7 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -4274,30 +4274,19 @@ func (vm *VM) bootstrap() { vm.cRange.define("first", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { r := self.(*object.Range) if len(args) == 0 { + // Bare #first is the begin — but a beginless range has no first element. + if object.IsNil(r.Lo) { + raise("RangeError", "cannot get the first element of beginless range") + } return r.Lo } - n := int(intArg(args[0])) + // The count is coerced with #to_int (so a Float truncates and a mock_int + // works); a negative count is an error, like Array#first. + n := int(vm.toIntCoerce(args[0])) if n < 0 { raise("ArgumentError", "negative array size") } - // An endless range generates its first n elements directly; a bounded one - // caps the count to its materialised size. - if _, isNil := r.Hi.(object.Nil); isNil { - lo, ok := r.Lo.(object.Integer) - if !ok { - raise("TypeError", "can't iterate from %s", r.Lo.Inspect()) - } - out := make([]object.Value, n) - for i := range out { - out[i] = object.IntValue(int64(lo) + int64(i)) - } - return object.NewArrayFromSlice(out) - } - elems := vm.rangeElemsV(r) - n = clampCount(int64(n), len(elems)) - out := make([]object.Value, n) - copy(out, elems[:n]) - return object.NewArrayFromSlice(out) + return object.NewArrayFromSlice(vm.rangeFirstN(r, n)) }) vm.cRange.define("end", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return self.(*object.Range).Hi @@ -4319,22 +4308,36 @@ func (vm *VM) bootstrap() { vm.cRange.define("exclude_end?", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return object.Bool(self.(*object.Range).Exclusive) }) - // include?/member?/=== treat their argument as a plain value to test for - // membership (comparison-based here). cover? additionally accepts a Range and - // answers range-in-range containment (see rangeCoverRange). - rangeCover := func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - return object.Bool(rangeCoverValue(self.(*object.Range), args[0])) + // include?/member? test discrete membership (MRI's range_include_internal: + // #<=> cover logic for linear/String endpoints, a #succ-walk with #== for + // custom Comparable ranges). === uses pure cover? logic on the argument. + // cover? additionally accepts a Range and answers range-in-range containment. + // All four require exactly one argument (MRI raises ArgumentError otherwise). + rangeArgCheck := func(args []object.Value) { + if len(args) != 1 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1)", len(args)) + } + } + rangeIncludeFn := func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + rangeArgCheck(args) + return object.Bool(vm.rangeInclude(self.(*object.Range), args[0])) } - vm.cRange.define("include?", rangeCover) - vm.cRange.define("cover?", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + vm.cRange.define("include?", rangeIncludeFn) + vm.cRange.define("cover?", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + rangeArgCheck(args) r := self.(*object.Range) if o, ok := args[0].(*object.Range); ok { - return object.Bool(rangeCoverRange(r, o)) + return object.Bool(vm.rangeCoverRange(r, o)) } - return object.Bool(rangeCoverValue(r, args[0])) + return object.Bool(vm.rangeCoverValueV(r, args[0])) + }) + // member? is a true alias of include? (Range.instance_method(:member?) == + // Range.instance_method(:include?)), so it must share the same method entry. + vm.cRange.methods["member?"] = vm.cRange.methods["include?"] + vm.cRange.define("===", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + rangeArgCheck(args) + return object.Bool(vm.rangeCoverValueV(self.(*object.Range), args[0])) }) - vm.cRange.define("member?", rangeCover) - vm.cRange.define("===", rangeCover) // Range#overlap?(other) reports whether the two ranges share any element. vm.cRange.define("overlap?", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { o, ok := args[0].(*object.Range) @@ -4349,11 +4352,13 @@ func (vm *VM) bootstrap() { if object.IsNil(r.Lo) { raise("RangeError", "cannot get the minimum of beginless range") } - elems := vm.rangeElemsV(r) - n := clampCount(vm.repeatLong(args[0]), len(elems)) - out := make([]object.Value, n) - copy(out, elems[:n]) - return object.NewArrayFromSlice(out) + n := int(vm.toIntCoerce(args[0])) + if n < 0 { + raise("ArgumentError", "negative array size") + } + // The n smallest of an ascending range are its first n — counted up + // directly, so a Bignum-bounded or endless integer range works. + return object.NewArrayFromSlice(vm.rangeFirstN(r, n)) } if blk != nil { return vm.rangeExtremeByBlock(r, blk, true) @@ -4375,6 +4380,11 @@ func (vm *VM) bootstrap() { if object.IsNil(r.Hi) { raise("RangeError", "cannot get the maximum of endless range") } + // A beginless range cannot be walked from its start, so its n largest + // are unobtainable (MRI raises RangeError rather than iterating). + if object.IsNil(r.Lo) { + raise("RangeError", "cannot get the maximum of beginless range") + } elems := vm.rangeElemsV(r) n := clampCount(vm.repeatLong(args[0]), len(elems)) out := make([]object.Value, n) @@ -4397,9 +4407,14 @@ func (vm *VM) bootstrap() { return object.NilV } if r.Exclusive { - // An Integer (or Bignum) end excludes by yielding its predecessor. + // An Integer (or Bignum) end excludes by yielding its predecessor — but + // only for a bounded range: excluding an Integer end still requires an + // Integer begin (MRI 3.x), so a beginless exclusive Integer range raises. switch r.Hi.(type) { case object.Integer, *object.Bignum: + if object.IsNil(r.Lo) { + raise("TypeError", "cannot exclude end value with non Integer begin value") + } return vm.send(r.Hi, "-", []object.Value{object.IntValue(1)}, nil) } // A numeric (Float/Rational) end, or a beginless range, has no @@ -4530,6 +4545,37 @@ func (vm *VM) bootstrap() { if len(args) > 0 { step = args[0] } + r0 := self.(*object.Range) + // A beginless range has no starting point to count from. MRI reports this + // as an ArgumentError whenever iteration is actually attempted (a block) or + // the range/step is not a plain numeric one; a numeric beginless range asked + // only for its enumerator (no block) is allowed through. + if object.IsNil(r0.Lo) { + if vm.linearObjectP(r0.Hi) && isNumericValue(step) { + if blk != nil { + raise("ArgumentError", "#step iteration for beginless ranges is meaningless") + } + } else { + raise("ArgumentError", "#step for non-numeric beginless ranges is meaningless") + } + } + // A zero numeric step never advances. For a numeric range that is an error: + // without a block MRI raises eagerly when the Enumerator is built, and with + // a block the numeric walkers below raise it — so only the no-block case is + // handled here. For a non-numeric bounded range (Time, custom) a zero step + // simply yields nothing. + if isZeroNumeric(step) { + if isNumericValue(r0.Lo) || isNumericValue(r0.Hi) { + if blk == nil { + raise("ArgumentError", "step can't be 0") + } + } else if !object.IsNil(r0.Lo) && !object.IsNil(r0.Hi) { + if blk == nil { + return enumForSized(self, "step", func(*VM) object.Value { return object.NilV }, args...) + } + return r0 + } + } if blk == nil { // With a size, for the reason Integer#step has one: without it // Enumerator#size counts by walking, and (1..Float::INFINITY).step @@ -5036,7 +5082,7 @@ func (vm *VM) bootstrap() { // the sequence. Asked to count 1.step(Float::INFINITY) it never // would: it allocated 30.9 GB before a CI runner died under it. return enumForSized(self, "step", func(*VM) object.Value { - return stepSize(self, limit, step) + return stepSize(self, limit, step, false) }, args...) } if object.IsNil(limit) { @@ -8119,6 +8165,12 @@ func (vm *VM) integerBitOp(a *big.Int, arg object.Value, name string, op func(z, func (vm *VM) rangeElemsV(r *object.Range) []object.Value { switch lo := r.Lo.(type) { case object.Integer, *object.Bignum, *object.String: + // An endless integer/string range has no finite element list; MRI reports + // this as a RangeError (e.g. (1..).to_a), distinct from the TypeError a + // beginless or non-iterable begin raises below. + if object.IsNil(r.Hi) { + raise("RangeError", "cannot convert endless range to an array") + } return rangeElems(r) case object.Symbol: // A Symbol range walks like a String range — via the byte/#succ scan that @@ -8139,7 +8191,7 @@ func (vm *VM) rangeElemsV(r *object.Range) []object.Value { raise("TypeError", "can't iterate from %s", r.Lo.Inspect()) } var out []object.Value - for cur := r.Lo; ; cur = vm.send(cur, "succ", nil, nil) { + for cur := r.Lo; ; { cmp, ok := vm.send(cur, "<=>", []object.Value{r.Hi}, nil).(object.Integer) if !ok { break @@ -8152,6 +8204,13 @@ func (vm *VM) rangeElemsV(r *object.Range) []object.Value { break } out = append(out, cur) + // Once the inclusive end has been reached (#<=> == 0) MRI stops without + // asking it for a successor — so a mock end that never defines #succ, or a + // Time whose successor is a fresh object, is never sent #succ past the end. + if !r.Exclusive && int64(cmp) == 0 { + break + } + cur = vm.send(cur, "succ", nil, nil) } return out } @@ -8363,15 +8422,26 @@ func rangeEmpty(vm *VM, r *object.Range) bool { } // rangeExtremeByBlock returns the minimum (isMin) or maximum element of r using a -// comparison block, iterating the range as Enumerable#min/#max do. +// comparison block, iterating the range as Enumerable#min/#max do. A block-driven +// extreme has to materialise the range, so an unbounded range raises RangeError +// (MRI: "cannot get the minimum/maximum … with custom comparison method"). The +// block's return value is reduced to a sign the way MRI's rb_cmpint does — via +// #> and #< against 0 — so a non-Integer comparison result still works. func (vm *VM) rangeExtremeByBlock(r *object.Range, blk *Proc, isMin bool) object.Value { + if object.IsNil(r.Lo) || object.IsNil(r.Hi) { + which := "maximum" + if isMin { + which = "minimum" + } + raise("RangeError", "cannot get the %s of unbounded range with custom comparison method", which) + } elems := rangeElems(r) if len(elems) == 0 { return object.NilV } best := elems[0] for _, e := range elems[1:] { - c, _ := vm.callBlock(blk, []object.Value{e, best}).(object.Integer) + c := vm.blockCmpSign(vm.callBlock(blk, []object.Value{e, best})) if (isMin && c < 0) || (!isMin && c > 0) { best = e } @@ -8379,6 +8449,70 @@ func (vm *VM) rangeExtremeByBlock(r *object.Range, blk *Proc, isMin bool) object return best } +// blockCmpSign reduces a comparison block's result to -1/0/1 using MRI's rb_cmpint +// rules: an Integer keeps its sign; any other value is probed with #>(0) and then +// #<(0), so a custom object that answers those participates in min/max. +func (vm *VM) blockCmpSign(v object.Value) int { + if i, ok := v.(object.Integer); ok { + switch { + case i < 0: + return -1 + case i > 0: + return 1 + default: + return 0 + } + } + zero := []object.Value{object.IntValue(0)} + if vm.send(v, ">", zero, nil).Truthy() { + return 1 + } + if vm.send(v, "<", zero, nil).Truthy() { + return -1 + } + return 0 +} + +// rangeFirstN returns the first n elements of r (n already non-negative). An +// Integer/Bignum begin counts upward without materialising the range, so a huge +// or endless integer range answers quickly ((0...2**64).first(2) == [0, 1]). An +// endless String begin walks #succ; any other endless begin cannot be iterated +// (TypeError). A bounded non-integer begin materialises via rangeElemsV. +func (vm *VM) rangeFirstN(r *object.Range, n int) []object.Value { + if isIntegerValue(r.Lo) { + out := make([]object.Value, 0, n) + cur := new(big.Int).Set(bigVal(r.Lo)) + for len(out) < n { + if !object.IsNil(r.Hi) { + if hb, ok := object.BigOf(r.Hi); ok { + c := cur.Cmp(hb) + if (r.Exclusive && c >= 0) || (!r.Exclusive && c > 0) { + break + } + } else if cmp := vm.spaceship(object.NormInt(cur), r.Hi); (r.Exclusive && cmp >= 0) || (!r.Exclusive && cmp > 0) { + break + } + } + out = append(out, object.NormInt(new(big.Int).Set(cur))) + cur.Add(cur, big.NewInt(1)) + } + return out + } + if object.IsNil(r.Hi) { + if loS, ok := r.Lo.(*object.String); ok { + out := make([]object.Value, 0, n) + for cur := loS.Str(); len(out) < n; cur = succString(cur) { + out = append(out, object.NewString(cur)) + } + return out + } + raise("TypeError", "can't iterate from %s", r.Lo.Inspect()) + } + elems := vm.rangeElemsV(r) + m := clampCount(int64(n), len(elems)) + return append([]object.Value(nil), elems[:m]...) +} + // rangeInts extracts integer endpoints. ok is false when either endpoint is not // an Integer (string/float ranges are not iterable in this phase). func rangeInts(r *object.Range) (lo, hi int64, ok bool) { @@ -8451,6 +8585,37 @@ func strRangeElems(lo, hi string, exclusive bool) []object.Value { } return out } + // For ASCII endpoints, rbgo's #succ matches MRI's exactly, so the succ-walk + // follows MRI's rb_str_upto_each: yield begin, begin.succ, … stopping once the + // value would grow longer than end or reach end.succ. This is what makes + // ('a'..'ab') yield a…z, aa, ab (rather than stopping at the first value that + // sorts past end). A multibyte endpoint keeps the conservative lexical walk + // below, because rbgo's byte-wise #succ diverges from MRI's block-aware #succ + // once a character leaves its script's alnum region. + if isASCIIStr(lo) && isASCIIStr(hi) { + if strings.Compare(lo, hi) > 0 || (exclusive && lo == hi) { + return nil + } + afterEnd := succString(hi) + var out []object.Value + for cur := lo; cur != afterEnd; { + var next string + hasNext := false + if exclusive || cur != hi { + next = succString(cur) + hasNext = true + } + out = append(out, object.NewString(cur)) + if !hasNext { // current was the (included) end + break + } + cur = next + if (exclusive && cur == hi) || len(cur) > len(hi) || cur == "" { + break + } + } + return out + } var out []object.Value cur := lo for { @@ -8473,6 +8638,17 @@ func strRangeElems(lo, hi string, exclusive bool) []object.Value { return out } +// isASCIIStr reports whether every byte of s is ASCII (< 0x80), so its #succ walk +// coincides with MRI's. +func isASCIIStr(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] >= 0x80 { + return false + } + } + return true +} + func isAlnumByte(c byte) bool { return c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } @@ -8578,6 +8754,16 @@ func (vm *VM) stepBounds(args []object.Value) (limit, step object.Value) { return limit, step } +// isZeroNumeric reports whether v is a numeric value equal to zero (0, 0.0, a +// zero Bignum/Rational). A non-numeric value is never zero here. +func isZeroNumeric(v object.Value) bool { + if !isNumericValue(v) { + return false + } + f, ok := toFloat(v) + return ok && f == 0 +} + // 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. @@ -8694,16 +8880,17 @@ func stepInRange(v, hi, step float64, exclusive bool) bool { // A step of zero raises, as MRI does — asking the size is enough to get the // 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 { +func stepSize(from, limit, step object.Value, excl bool) object.Value { rejectStringStep(step) f, okF := toFloat(from) s, okS := toFloat(step) if !okF || !okS { return object.NilV } - if s == 0 { - raise("ArgumentError", "step can't be 0") - } + // A zero step is rejected eagerly by every caller (Range#step, Integer#step, + // Numeric#step) before the size Enumerator is built, so it never reaches here; + // were one to slip through, the index scan below simply yields 0 rather than + // looping, since (l-f)/0 is ±Inf/NaN and int64(that)+2 is out of [0, …). if object.IsNil(limit) { return object.Float(math.Inf(1)) // unbounded: endlessly many } @@ -8727,11 +8914,22 @@ func stepSize(from, limit, step object.Value) object.Value { } return object.IntValue(0) } - n := math.Floor((l-f)/s) + 1 - if math.IsNaN(n) || n < 0 { - return object.IntValue(0) + // The count must agree with what the walk actually yields, so it is derived + // from the same in-range predicate (stepInRange) rather than a closed form: + // the yielded terms are f, f+s, f+2s, … for a contiguous run of indices + // starting at 0, so the size is (last valid index)+1. (l-f)/s estimates that + // index; scanning down from just past it finds the largest in-range index, + // which is what makes a term landing just inside or just outside the boundary + // (e.g. 1.0 + 3*18.2 = 55.599999999999994 < 55.6) counted the same way the walk + // counts it. + est := (l - f) / s + k := int64(math.Floor(est)) + 2 + for ; k >= 0; k-- { + if stepInRange(f+float64(k)*s, l, s, excl) { + return object.IntValue(k + 1) + } } - return object.IntValue(int64(n)) + return object.IntValue(0) } // rangeStepSize is how many values a Range#step sequence yields. @@ -8741,9 +8939,6 @@ func stepSize(from, limit, step object.Value) object.Value { // answer for an endless one. func rangeStepSize(r *object.Range, step object.Value) object.Value { if object.IsNil(r.Hi) { - if s, ok := toFloat(step); ok && s == 0 { - raise("ArgumentError", "step can't be 0") - } return object.Float(math.Inf(1)) // endless, so endlessly many } if _, ok := toFloat(r.Lo); !ok { @@ -8752,16 +8947,5 @@ func rangeStepSize(r *object.Range, step object.Value) object.Value { if _, ok := toFloat(r.Hi); !ok { return object.NilV } - hi := r.Hi - if r.Exclusive { - // An excluded end is one short, which stepSize counts by moving the - // limit a whole step back rather than by subtracting one from a count - // that may not be integral. - if h, ok := toFloat(hi); ok { - if s, ok := toFloat(step); ok && s != 0 { - hi = object.Float(math.Nextafter(h, h-s)) - } - } - } - return stepSize(r.Lo, hi, step) + return stepSize(r.Lo, r.Hi, step, r.Exclusive) } diff --git a/internal/vm/first_last_test.go b/internal/vm/first_last_test.go index 38677c67..465e2125 100644 --- a/internal/vm/first_last_test.go +++ b/internal/vm/first_last_test.go @@ -51,7 +51,6 @@ func TestFirstLastErrors(t *testing.T) { {"range_last_neg", `(1..5).last(-1)`, "negative array size"}, {"endless_last", `(1..).last`, "cannot get the last element of endless range"}, {"endless_last_n", `(1..).last(2)`, "cannot get the last element of endless range"}, - {"endless_first_noninteger", `("a"..).first(2)`, "can't iterate from"}, {"range_take_neg", `(1..5).take(-1)`, "attempt to take negative size"}, {"range_drop_neg", `(1..5).drop(-1)`, "attempt to drop negative size"}, {"endless_take_noninteger", `("a"..).take(2)`, "can't iterate from"}, diff --git a/internal/vm/numeric_edges.go b/internal/vm/numeric_edges.go index c04baeec..891464b0 100644 --- a/internal/vm/numeric_edges.go +++ b/internal/vm/numeric_edges.go @@ -520,7 +520,7 @@ func (vm *VM) registerNumericEdges() { limit, step := vm.stepBounds(args) if blk == nil { return enumForSized(self, "step", func(*VM) object.Value { - return stepSize(self, limit, step) + return stepSize(self, limit, step, false) }, args...) } if object.IsNil(limit) { diff --git a/internal/vm/range_conformance_test.go b/internal/vm/range_conformance_test.go new file mode 100644 index 00000000..573ca265 --- /dev/null +++ b/internal/vm/range_conformance_test.go @@ -0,0 +1,398 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "strings" + "testing" +) + +// Every expected value below was checked byte-for-byte against MRI Ruby +// (ruby -e '...') for the ruby/spec core/range cluster: #cover?, #include?, +// #member?, #===, #step, #each, #first, #min, #max, #to_a. + +// TestRangeCoverIncludeCase covers the comparison-based membership methods, which +// now dispatch #<=> through the VM so Numeric subclasses, Time and custom +// Comparable objects order by their own comparison. +func TestRangeCoverIncludeCase(t *testing.T) { + cases := []struct{ name, src, want string }{ + // cover? uses pure #<=> on both endpoints. + {"cover_int_in", `p((1..5).cover?(2))`, "true\n"}, + {"cover_int_out_low", `p((0..6).cover?(-5))`, "false\n"}, + {"cover_int_out_high", `p((0..6).cover?(10))`, "false\n"}, + {"cover_float", `p((-1...1).cover?(10.5))`, "false\n"}, + {"cover_excl_end", `p((0.5...2.4).cover?(2.4))`, "false\n"}, + {"cover_incomparable", `p((1..10).cover?(nil))`, "false\n"}, + {"cover_endless", `p((1..).cover?(2.4))`, "true\n"}, + {"cover_beginless", `p((..10).cover?(2.4))`, "true\n"}, + {"cover_beginless_out", `p((...10.5).cover?(12.4))`, "false\n"}, + // cover? with a Range argument (range-in-range containment). + {"cover_range_in", `p((0..10).cover?(3..7))`, "true\n"}, + {"cover_range_out", `p((0..10).cover?(3..15))`, "false\n"}, + {"cover_range_low", `p((0..10).cover?(-2..7))`, "false\n"}, + {"cover_range_str", `p(('c'..'i').cover?('d'..'f'))`, "true\n"}, + {"cover_range_excl_ok", `p((0..10).cover?(0...11))`, "true\n"}, + {"cover_range_excl_no", `p((0...10).cover?(0..10))`, "false\n"}, + {"cover_range_endless_self", `p((0..).cover?(4..6))`, "true\n"}, + {"cover_range_nilnil", `p((nil..nil).cover?(4..6))`, "true\n"}, + // Generic Comparable+succ end, self inclusive vs other exclusive: covered + // when self.end.succ reaches other.end. + {"cover_range_succ_end", ` +class E + include Comparable + def initialize(n); @n=n; end + attr_reader :n + def <=>(o); @n <=> o.n; end + def succ; E.new(@n+1); end +end +p((E.new(0)..E.new(10)).cover?(E.new(4)...E.new(11)))`, "true\n"}, + + // === uses cover? logic (pure #<=>), even for a custom Comparable. + {"eqq_int", `p((1..10) === 5)`, "true\n"}, + {"eqq_nilnil", `p((nil..nil) === "x")`, "true\n"}, + {"eqq_custom", ` +class W + include Comparable + def initialize(n); @n=n; end + attr_reader :n + def <=>(o); return nil unless o.is_a?(W); @n <=> o.n; end +end +p((W.new(0)..W.new(10)) === W.new(2))`, "true\n"}, + + // include? on a Numeric subclass endpoint uses cover? logic. + {"include_numeric_subclass", ` +class Num < Numeric + def initialize(v); @v=v; end + attr_reader :v + def <=>(o); return nil unless o.is_a?(Num); @v <=> o.v; end +end +p((Num.new(0)..Num.new(6)).include?(Num.new(5)))`, "true\n"}, + // include? on String endpoints is a discrete #succ membership test. + {"include_str_succ", `p(('a'..'c').include?('b'))`, "true\n"}, + {"include_str_not_succ", `p(('a'..'c').include?('bc'))`, "false\n"}, + {"include_str_multi", `p(('a'..'ab').include?('aa'))`, "true\n"}, + {"include_str_multi_out", `p(('a'..'ab').include?('ac'))`, "false\n"}, + {"include_str_excl_end", `p(('a'...'aa').include?('aa'))`, "false\n"}, + // include? coerces its argument to String via #to_str. + {"include_to_str", ` +o = Object.new +def o.to_str; 'b'; end +p(('a'..'aa').include?(o))`, "true\n"}, + {"include_no_to_str", `p(('a'..'aa').include?(nil))`, "false\n"}, + // include? falls back to Enumerable#include? (succ + ==) for custom ranges. + {"include_custom_succ", ` +class S + def initialize(v); @v=v; end + attr_reader :v + def <=>(o); return nil unless o.is_a?(S); @v <=> o.v; end + def succ; S.new(@v+1); end + def ==(o); o.is_a?(S) && @v == o.v; end +end +p((S.new(1)..S.new(4)).include?(S.new(2)))`, "true\n"}, + {"include_custom_out", ` +class S2 + def initialize(v); @v=v; end + attr_reader :v + def <=>(o); return nil unless o.is_a?(S2); @v <=> o.v; end + def succ; S2.new(@v+1); end + def ==(o); o.is_a?(S2) && @v == o.v; end +end +p((S2.new(1)..S2.new(4)).include?(S2.new(5)))`, "false\n"}, + // (nil..nil).include? is true for a linear value, else a TypeError (below). + {"include_nilnil_numeric", `p((nil..nil).include?(1))`, "true\n"}, + // member? is a true alias of include?. + {"member_alias", `p(Range.instance_method(:member?) == Range.instance_method(:include?))`, "true\n"}, + {"member_works", `p(('a'..'c').member?('b'))`, "true\n"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestRangeFirstMinMax covers #first, #min and #max, including the n-argument +// forms (which count up rather than materialise, so a Bignum-bounded or endless +// integer range works) and the endpoint edge cases. +func TestRangeFirstMinMax(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"first_bare", `p((3..7).first)`, "3\n"}, + {"first_n", `p((3..7).first(2))`, "[3, 4]\n"}, + {"first_n_over", `p((0..2).first(4))`, "[0, 1, 2]\n"}, + {"first_n_zero", `p((0..2).first(0))`, "[]\n"}, + {"first_to_int", ` +o = Object.new +def o.to_int; 2; end +p((3..7).first(o))`, "[3, 4]\n"}, + {"first_float_trunc", `p((2..9).first(2.8))`, "[2, 3]\n"}, + {"first_endless", `p((1..).first(3))`, "[1, 2, 3]\n"}, + {"first_str_endless", `p(('a'..).first(3))`, "[\"a\", \"b\", \"c\"]\n"}, + {"first_float_end", `p((1..3.5).first(10))`, "[1, 2, 3]\n"}, + + {"min_bare", `p((1..10).min)`, "1\n"}, + {"min_empty", `p((7...7).min)`, "nil\n"}, + {"min_n", `p((1..10).min(2))`, "[1, 2]\n"}, + {"min_n_bignum", `p((0...2**64).min(2))`, "[0, 1]\n"}, + {"min_n_endless", `p((1..).min(2))`, "[1, 2]\n"}, + {"min_n_over", `p((1..3).min(10))`, "[1, 2, 3]\n"}, + {"min_n_str", `p(('f'..'l').min(2))`, "[\"f\", \"g\"]\n"}, + {"min_block", `p((1..3).min {|a,b| -3 })`, "3\n"}, + {"min_block_empty", `p((100..10).min {|a,b| a <=> b })`, "nil\n"}, + + {"max_bare", `p((1..10).max)`, "10\n"}, + {"max_excl", `p((1...10).max)`, "9\n"}, + {"max_bignum", `p((0..2**64-1).max)`, "18446744073709551615\n"}, + {"max_n", `p((1..10).max(2))`, "[10, 9]\n"}, + {"max_n_over", `p((1..3).max(10))`, "[3, 2, 1]\n"}, + {"max_beginless", `p((..1).max)`, "1\n"}, + {"max_block", `p((1..3).max {|a,b| -(a <=> b) })`, "1\n"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestRangeEachToA covers #each (which stops asking for a successor once the +// inclusive end is reached) and #to_a (ASCII multi-character String ranges walk +// the full #succ sequence; an endless range is a RangeError). +func TestRangeEachToA(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"to_a_int", `p((-2..2).to_a)`, "[-2, -1, 0, 1, 2]\n"}, + {"to_a_str", `p(('A'..'E').to_a)`, "[\"A\", \"B\", \"C\", \"D\", \"E\"]\n"}, + {"to_a_str_multi", `p(('a'..'ab').to_a.length)`, "28\n"}, + {"to_a_str_excl", `p(('a'...'c').to_a)`, "[\"a\", \"b\"]\n"}, + {"to_a_backward", `p(('D'..'A').to_a)`, "[]\n"}, + {"each_int", `(1..3).each {|i| print i}; puts`, "123\n"}, + {"each_returns_self", `r = (1..3); p(r.each {}.equal?(r))`, "true\n"}, + // #each stops at the inclusive end without calling #succ on it (a Time-like + // object whose successor is a fresh object of the same value). + {"each_succ_stop", ` +class C + include Comparable + def initialize(n); @n=n; end + attr_reader :n + def <=>(o); @n <=> o.n; end + def succ; C.new(@n+1); end +end +a = [] +(C.new(1)..C.new(3)).each {|x| a << x.n } +p(a)`, "[1, 2, 3]\n"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestRangeStep covers #step: numeric and String stepping, the analytic +// Enumerator size (which must agree with the walk exactly, including a term that +// lands just inside or outside an exclusive boundary), and the zero-step edge. +func TestRangeStep(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"step_int", `(-5..5).step(2) {|x| print x, " "}; puts`, "-5 -3 -1 1 3 5 \n"}, + {"step_float", `(-1.0..1.0).step(0.5) {|x| print x, " "}; puts`, "-1.0 -0.5 0.0 0.5 1.0 \n"}, + {"step_str", `('A'..'G').step(2) {|x| print x}; puts`, "ACEG\n"}, + {"step_returns_self", `r = (1..2); p(r.step {}.equal?(r))`, "true\n"}, + + {"size_incl", `p((-5..5).step(2).size)`, "6\n"}, + {"size_excl_boundary", `p((-5...5).step(2).size)`, "5\n"}, + {"size_excl_float", `p((-1.0...1.0).step(0.5).size)`, "4\n"}, + {"size_default_step", `p((-2...2).step.size)`, "4\n"}, + {"size_near_upper", `p((1.0...55.6).step(18.2).size)`, "4\n"}, + {"size_frac", `p((1...10).step(2).size)`, "5\n"}, + {"size_str_nil", `p(('A'..'E').step(2).size)`, "nil\n"}, + {"size_endless_inf", `p((1..).step(2).size)`, "Infinity\n"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestRangeErrors covers the raising paths: arity, TypeError for un-iterable +// ranges, RangeError for endless/beginless materialisation, and ArgumentError for +// zero-step and beginless #step. +func TestRangeErrors(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"cover_no_arg", `(1..2).cover?`, "ArgumentError"}, + {"cover_two_args", `(1..2).cover?(1, 2)`, "ArgumentError"}, + {"include_no_arg", `(1..2).include?`, "ArgumentError"}, + {"eqq_two_args", `(1..2).send(:===, 1, 2)`, "ArgumentError"}, + + {"include_str_beginless", `(..'aa').include?('a')`, "TypeError"}, + {"include_str_endless", `('aa'..).include?('a')`, "TypeError"}, + {"include_nilnil_string", `(nil..nil).include?('a')`, "TypeError"}, + {"include_custom_endless", ` +class SE + def initialize(v); @v=v; end + attr_reader :v + def <=>(o); return nil unless o.is_a?(SE); @v <=> o.v; end + def succ; SE.new(@v+1); end +end +(SE.new(0)..).include?(SE.new(5))`, "TypeError"}, + + {"to_a_endless", `eval("(1..)").to_a`, "RangeError"}, + {"to_a_beginless", `(..1).to_a`, "TypeError"}, + {"first_bare_beginless", `(..1).first`, "RangeError"}, + {"first_negative", `(0..2).first(-1)`, "ArgumentError"}, + {"first_bad_arg", `(2..3).first("1")`, "TypeError"}, + + {"min_beginless", `(..1).min`, "RangeError"}, + {"min_n_beginless", `(..1).min(2)`, "RangeError"}, + {"min_n_float_endless", `(1.0..).min(2)`, "TypeError"}, + {"min_block_endless", `(1..).min {|a, b| a }`, "RangeError"}, + {"min_n_negative", `(0..2).min(-1)`, "ArgumentError"}, + + {"max_endless", `(1..).max`, "RangeError"}, + {"max_n_endless", `(1..).max(2)`, "RangeError"}, + {"max_n_beginless", `(..1.0).max(2)`, "RangeError"}, + {"max_excl_beginless_int", `(...1).max`, "TypeError"}, + {"max_excl_float", `(1.5...3.5).max`, "TypeError"}, + {"max_block_beginless", `(..1).max {|a, b| a }`, "RangeError"}, + + {"step_zero_numeric", `(-1..1).step(0)`, "ArgumentError"}, + {"step_zero_float", `(-1..1).step(0.0) {}`, "ArgumentError"}, + {"step_beginless_iter", `(..10).step(1) { break }`, "ArgumentError"}, + {"step_beginless_nonnum", `(..10).step("a")`, "ArgumentError"}, + {"step_nilnil", `Range.new(nil, nil).step(1)`, "ArgumentError"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("src=%q: got err=%v, want containing %q", tc.src, err, tc.want) + } + }) + } +} + +// TestRangeStepZeroNonNumeric covers the one non-error zero-step path: a bounded +// non-numeric range with a zero step yields nothing rather than raising. +func TestRangeStepZeroNonNumeric(t *testing.T) { + src := ` +t = Time.at(0) +a = [] +(t..(t + 1)).step(0) {|x| a << x } +p(a)` + if got := eval(t, src); got != "[]\n" { + t.Errorf("got=%q want=%q", got, "[]\n") + } +} + +// TestRangeMinMaxBlockCmp covers blockCmpSign's reduction of a non-Integer +// comparison result to a sign via #> / #<, so a custom comparison object drives +// #min / #max. +func TestRangeMinMaxBlockCmp(t *testing.T) { + // The block returns a value whose #<=>-less sign is decided by #> and #< — here + // a plain wrapper that forwards to its integer, exercising the non-Integer path. + src := ` +class Cmp + def initialize(n); @n=n; end + def >(o); @n > o; end + def <(o); @n < o; end +end +p((1..4).min {|a, b| Cmp.new(a <=> b) })` + if got := eval(t, src); got != "1\n" { + t.Errorf("got=%q want=%q", got, "1\n") + } +} + +// TestRangeCoverageEdges exercises branches the primary tests reach only through +// ASCII / Integer inputs: blockCmpSign's Integer-zero and #>/#< result signs, the +// non-ASCII String #succ walk, a custom-#succ element overshooting the end, and +// the size Enumerator's nil paths for non-numeric step/limit. Values checked +// against MRI where the range is well-formed; the malformed ranges (which MRI +// rejects at construction but rbgo tolerates) assert rbgo's own handling. +func TestRangeCoverageEdges(t *testing.T) { + cmp := ` +class Cmp + def initialize(n); @n = n; end + def >(o); @n > o; end + def <(o); @n < o; end +end +` + cases := []struct{ name, src, want string }{ + // blockCmpSign: Integer sign branches (<0, >0, ==0). + {"blkcmp_int_zero", `p((1..3).min {|a, b| 0 })`, "1\n"}, + {"blkcmp_int_pos", `p((1..3).min {|a, b| 5 })`, "1\n"}, + {"blkcmp_int_max_pos", `p((1..3).max {|a, b| 5 })`, "3\n"}, + // blockCmpSign: non-Integer result decided by #< (negative) and #> (positive). + {"blkcmp_obj_neg", cmp + `p((1..3).min {|a, b| Cmp.new(-1) })`, "3\n"}, + {"blkcmp_obj_pos", cmp + `p((1..4).max {|a, b| Cmp.new(a <=> b) })`, "4\n"}, + // blockCmpSign: a result that is neither #>0 nor #<0 is treated as equal (0). + {"blkcmp_obj_zero", ` +class Neu + def >(o); false; end + def <(o); false; end +end +p((1..3).min {|a, b| Neu.new })`, "1\n"}, + + // strRangeElems non-ASCII #succ walk (and isASCIIStr's non-ASCII return). + {"nonascii_walk", `p(("\u{3a3}".."\u{3a9}").to_a)`, "[\"Σ\", \"Τ\", \"Υ\", \"Φ\", \"Χ\", \"Ψ\", \"Ω\"]\n"}, + {"nonascii_backward", `p(("\u{3a9}".."\u{3a3}").to_a)`, "[]\n"}, + {"nonascii_len_overshoot", `p(("a\u{3a3}".."b").to_a)`, "[\"aΣ\"]\n"}, + + // rangeElemsV #succ path: an element whose #succ overshoots the end. + {"succ_overshoot", ` +class Mul + include Comparable + def initialize(n); @n = n; end + attr_reader :n + def <=>(o); @n <=> o.n; end + def succ; Mul.new(@n * 10); end +end +p((Mul.new(1)..Mul.new(50)).to_a.map(&:n))`, "[1, 10]\n"}, + + // step Enumerator size: nil for a non-numeric step or a non-numeric limit. + {"size_nonnumeric_step", `p((1..10).step(Object.new).size)`, "nil\n"}, + {"size_nonnumeric_end", `p((1.."z").step(2).size)`, "nil\n"}, + {"size_nonnumeric_int_step_limit", `p(1.step("z", 2).size)`, "nil\n"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestRangeCoverageErrors exercises the remaining raising branches: a #to_str that +// returns a non-String (in the String-range membership test) and an endless +// Symbol range (which cannot be materialised). +func TestRangeCoverageErrors(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"to_str_non_string", ` +o = Object.new +def o.to_str; 1; end +('a'..'aa').include?(o)`, "TypeError"}, + {"symbol_endless", `(:a..).to_a`, "RangeError"}, + // A zero step with a block reaches the numeric walkers, which raise it (the + // no-block enum path raises eagerly instead — see TestRangeErrors). + {"step_zero_block_bounded", `(1..3).step(0) { |x| }`, "ArgumentError"}, + {"step_zero_block_endless_int", `(1..).step(0) { |x| break }`, "ArgumentError"}, + {"step_zero_block_endless_float", `(1.0..).step(0.0) { |x| break }`, "ArgumentError"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("src=%q: got err=%v, want containing %q", tc.src, err, tc.want) + } + }) + } +} diff --git a/internal/vm/range_edges.go b/internal/vm/range_edges.go index bd27a6b0..bb42fc91 100644 --- a/internal/vm/range_edges.go +++ b/internal/vm/range_edges.go @@ -75,21 +75,60 @@ func isIntegerValue(v object.Value) bool { return false } -// rangeCoverValue is the comparison-based membership test shared by Range#cover?, -// #include?, #member? and #=== for a plain (non-Range) argument: v is covered -// when it is not below begin and not past end. A nil bound is open on that side, -// and an incomparable value is simply not covered (MRI returns false, not error). -func rangeCoverValue(r *object.Range, v object.Value) bool { +// rangeCmpV compares a <=> b by dispatching Ruby's #<=> through the VM, so that +// custom Comparable objects, Numeric subclasses and Time all order correctly (the +// pure rangeCmp only understands built-in numerics and strings). It returns the +// comparison sign and whether the two values were comparable at all — a #<=> that +// returns nil (or any non-Integer) yields ok=false, exactly as MRI's r_less +// treats an incomparable pair. +func (vm *VM) rangeCmpV(a, b object.Value) (int, bool) { + r := vm.send(a, "<=>", []object.Value{b}, nil) + n, ok := r.(object.Integer) + if !ok { + return 0, false + } + switch { + case n < 0: + return -1, true + case n > 0: + return 1, true + default: + return 0, true + } +} + +// linearObjectP mirrors MRI's linear_object_p: a value whose position on the +// number/time line is well defined — any Numeric (built-in or a Numeric subclass) +// or a Time. Range#include? uses cover? (pure #<=>) logic when either endpoint is +// such a value, rather than walking discrete successors. +func (vm *VM) linearObjectP(v object.Value) bool { + if isNumericValue(v) { + return true + } + cls := vm.classOf(v) + if num := vm.cInteger.super; num != nil && classIsA(cls, num) { + return true + } + return classIsA(cls, vm.cTime) +} + +// rangeCoverValueV is MRI's r_cover_p — the comparison-based membership test +// shared by Range#cover?, #=== and (for linear/String endpoints) #include? on a +// plain argument. The low bound is checked as begin <=> v (so the endpoint, not +// the argument, drives coercion — matching which object receives #coerce/#<=>), +// the high bound as v <=> end. A nil bound is open on that side; an incomparable +// value is simply not covered (MRI answers false, never raising). +func (vm *VM) rangeCoverValueV(r *object.Range, v object.Value) bool { if !object.IsNil(r.Lo) { - lc, lok := rangeCmp(v, r.Lo) - if !lok || lc < 0 { + lc, lok := vm.rangeCmpV(r.Lo, v) + if !lok || lc > 0 { return false } } if object.IsNil(r.Hi) { return true } - hc, hok := rangeCmp(v, r.Hi) + hc, hok := vm.rangeCmpV(v, r.Hi) if !hok { return false } @@ -99,11 +138,11 @@ func rangeCoverValue(r *object.Range, v object.Value) bool { return hc <= 0 } -// rangeEndCmp compares two range ends the way MRI's r_less does for cover?: a nil +// rangeEndCmpV compares two range ends the way MRI's r_less does for cover?: a nil // end is +infinity, so nil vs nil compares equal and nil (self endless) vs a // finite end compares greater. The bool is false when the two ends are of -// incomparable types. -func rangeEndCmp(a, b object.Value) (int, bool) { +// incomparable types. It dispatches #<=> so generic comparable bounds work. +func (vm *VM) rangeEndCmpV(a, b object.Value) (int, bool) { aNil, bNil := object.IsNil(a), object.IsNil(b) if aNil && bNil { return 0, true @@ -111,25 +150,16 @@ func rangeEndCmp(a, b object.Value) (int, bool) { if aNil { return 1, true } - return rangeCmp(a, b) -} - -// rangeExclMax returns the greatest value an exclusive range attains (for the -// mixed-exclusivity branch of cover?): for Integer ends that is end-1. Any other -// end type (notably Float, which has no discrete predecessor) reports false so -// cover? conservatively answers false, as MRI does when Range#max raises. -func rangeExclMax(o *object.Range) (object.Value, bool) { - if hi, ok := o.Hi.(object.Integer); ok { - return object.IntValue(int64(hi) - 1), true - } - return nil, false + return vm.rangeCmpV(a, b) } // rangeCoverRange implements Range#cover? when the argument is itself a Range: it // answers whether the whole of o lies within self, mirroring MRI's // r_cover_range_p (begin containment, end comparison with exclusive-end fix-ups, -// and rejection of empty/backward/unbounded-past-self arguments). -func rangeCoverRange(self, o *object.Range) bool { +// and rejection of empty/backward/unbounded-past-self arguments). It dispatches +// #<=> so generic comparable bounds (a Numeric subclass, a Comparable object) are +// ordered by their own comparison, not just the built-in numeric/string cases. +func (vm *VM) rangeCoverRange(self, o *object.Range) bool { begNil, endNil := object.IsNil(self.Lo), object.IsNil(self.Hi) vBegNil, vEndNil := object.IsNil(o.Lo), object.IsNil(o.Hi) @@ -146,16 +176,16 @@ func rangeCoverRange(self, o *object.Range) bool { if o.Exclusive { thresh = -1 } - if c, _ := rangeCmp(o.Lo, o.Hi); c > thresh { + if c, ok := vm.rangeCmpV(o.Lo, o.Hi); ok && c > thresh { return false } } // o's begin must be a covered value of self. - if !vBegNil && !rangeCoverValue(self, o.Lo) { + if !vBegNil && !vm.rangeCoverValueV(self, o.Lo) { return false } - cmp, ok := rangeEndCmp(self.Hi, o.Hi) + cmp, ok := vm.rangeEndCmpV(self.Hi, o.Hi) if !ok { return false } @@ -165,17 +195,87 @@ func rangeCoverRange(self, o *object.Range) bool { if self.Exclusive { // self exclusive, o inclusive: self must end strictly past o return cmp > 0 } - // self inclusive, o exclusive: self may still cover o if o's greatest value - // (max, for a discrete end) does not exceed self's end. + // self inclusive, o exclusive, self.end < o.end: self still covers o when o's + // greatest value does not exceed self.end. For a discrete end that greatest + // value is o.end's predecessor, so — mirroring MRI's r_cover_range_p — self + // covers o iff self.end's successor reaches or passes o.end (self.end.succ >= + // o.end). An end without #succ (e.g. a Float) has no such neighbour, so cover + // conservatively answers false. if cmp >= 0 { return true } - max, ok := rangeExclMax(o) - if !ok { + if !vm.respondsToDynamic(self.Hi, "succ") { return false } - mc, ok := rangeCmp(self.Hi, max) - return ok && mc >= 0 + sc, ok := vm.rangeCmpV(vm.send(self.Hi, "succ", nil, nil), o.Hi) + return ok && sc >= 0 +} + +// rangeInclude implements Range#include? / #member? — MRI's range_include_internal +// with string_use_cover = 0. When either endpoint is a linear object (Numeric or +// Time), or when both endpoints are nil and the argument itself is linear, it +// falls back to the pure #<=> cover test. When both endpoints are Strings it does +// a discrete #succ-walk membership test comparing with #== (so ('a'..'ab') covers +// 'aa' but not 'ac'). Every other shape — a beginless/endless String range, a +// custom Comparable range, (nil..nil) with a non-linear argument — is iterated by +// Enumerable#include?, which walks #succ and raises TypeError when the range +// cannot be enumerated. This matches MRI's routing to rb_call_super. +func (vm *VM) rangeInclude(r *object.Range, val object.Value) bool { + beg, end := r.Lo, r.Hi + begNil, endNil := object.IsNil(beg), object.IsNil(end) + if vm.linearObjectP(beg) || vm.linearObjectP(end) || + (begNil && endNil && vm.linearObjectP(val)) { + return vm.rangeCoverValueV(r, val) + } + _, begStr := beg.(*object.String) + _, endStr := end.(*object.String) + if begStr && endStr { + return vm.strIncludeRangeP(r, val) + } + // Fall back to Enumerable#include?: walk the range's elements (via #succ) and + // compare with #==. A beginless or endless range (including (nil..nil) with a + // non-linear argument) cannot be enumerated, so — like MRI's super call, whose + // #each raises here — it is a TypeError; rangeElemsV likewise raises for a + // bounded begin that lacks #succ. + if begNil || endNil { + raise("TypeError", "can't iterate from %s", vm.classOf(beg).name) + } + for _, e := range vm.rangeElemsV(r) { + if vm.send(e, "==", []object.Value{val}, nil).Truthy() { + return true + } + } + return false +} + +// strIncludeRangeP is the discrete membership test for a String..String range +// (MRI's rb_str_include_range_p with string_use_cover = 0): the argument is +// coerced to a String via #to_str (a non-String that does not respond to #to_str +// is simply not a member; a #to_str that returns a non-String raises TypeError), +// then tested against the range's succ-walked elements with String equality. +func (vm *VM) strIncludeRangeP(r *object.Range, val object.Value) bool { + s, ok := val.(*object.String) + if !ok { + if !vm.respondsToDynamic(val, "to_str") { + return false + } + conv := vm.send(val, "to_str", nil, nil) + cs, isStr := conv.(*object.String) + if !isStr { + raise("TypeError", "can't convert %s to String (%s#to_str gives %s)", + vm.classOf(val).name, vm.classOf(val).name, vm.classOf(conv).name) + } + s = cs + } + target := s.Str() + beg := r.Lo.(*object.String).Str() + end := r.Hi.(*object.String).Str() + for _, e := range strRangeElems(beg, end, r.Exclusive) { + if e.(*object.String).Str() == target { + return true + } + } + return false } // rangeSizeVal is Range#size with MRI 3.4/4.0 semantics. An Integer begin yields diff --git a/internal/vm/range_step_string_internal_test.go b/internal/vm/range_step_string_internal_test.go index d2e1b54f..24744c1f 100644 --- a/internal/vm/range_step_string_internal_test.go +++ b/internal/vm/range_step_string_internal_test.go @@ -27,8 +27,9 @@ func TestRangeStepString(t *testing.T) { {`p (("A".."G").step(2.0) {}) rescue p $!.class`, "TypeError"}, {`p (("A".."G").step([]) {}) rescue p $!.class`, "TypeError"}, {`p (("A"..).step(2.0) {}) rescue p $!.class`, "TypeError"}, - // A zero or negative step is rejected. - {`p (("A".."G").step(0) {}) rescue p $!.class`, "ArgumentError"}, + // A zero step over a non-numeric range does not advance (and #step returns + // self), matching MRI; a negative step is still rejected here. + {`p (("A".."G").step(0) {})`, `"A".."G"`}, {`p (("A".."G").step(-1) {}) rescue p $!.class`, "ArgumentError"}, // A numeric range is unaffected (still uses the arithmetic path). {`a = []; (1..7).step(2) { |x| a << x }; p a`, `[1, 3, 5, 7]`}, diff --git a/internal/vm/step_test.go b/internal/vm/step_test.go index 6f02a1b9..221e44b3 100644 --- a/internal/vm/step_test.go +++ b/internal/vm/step_test.go @@ -41,7 +41,6 @@ func TestStep(t *testing.T) { `(1..3).step(0) { |x| }`, `(1.0..3.0).step(0.0) { |x| }`, `1.step(3, 0) { |x| }`, - `("a".."c").step(0) { |x| }`, } { if err := runErr(t, src); err == nil || !strings.Contains(err.Error(), "ArgumentError") { t.Errorf("src=%q got=%v want ArgumentError", src, err)