From 32bb37c6ad21a150169e201764728362c896017e Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 17:20:22 +0200 Subject: [PATCH 1/4] Range: value-based ==/eql?/hash and nil..nil inspect (MRI 4.0.6) Range#== / #eql? / #hash now compare by endpoint value (dispatching #== /#eql? and mixing the two bounds + exclude_end? into the hash) rather than by object identity, so custom Comparable endpoints, Range subclasses and endless ranges compare and hash like MRI. Range#inspect renders (nil..nil) as "nil..nil" while keeping (1..) and (..1) unchanged, matching MRI's range_inspect rule (to_s is unchanged). Co-Authored-By: Claude Opus 4.8 --- internal/object/object.go | 30 ++++++++++++++++----- internal/vm/prelude.rb | 26 ++++++++++++++++++ internal/vm/prelude_frozen_gen.go | 45 ++++++++++++++++++++++++++++--- 3 files changed, 91 insertions(+), 10 deletions(-) diff --git a/internal/object/object.go b/internal/object/object.go index dd100d2a..e5097323 100644 --- a/internal/object/object.go +++ b/internal/object/object.go @@ -1208,17 +1208,33 @@ func (r *Range) sep() string { } return ".." } -func (r *Range) ToS() string { return rangeEnd(r.Lo, false) + r.sep() + rangeEnd(r.Hi, false) } -func (r *Range) Inspect() string { return rangeEnd(r.Lo, true) + r.sep() + rangeEnd(r.Hi, true) } +func (r *Range) ToS() string { return rangeEnd(r.Lo) + r.sep() + rangeEnd(r.Hi) } + +// Inspect mirrors MRI's range_inspect: a nil bound normally renders empty, but +// when BOTH bounds are nil each is shown as "nil" — so (nil..nil).inspect is +// "nil..nil" while (1..).inspect stays "1.." and (..1).inspect stays "..1". The +// rule (per MRI) is: show begin when begin is non-nil OR end is nil; show end +// when begin is nil OR end is non-nil. +func (r *Range) Inspect() string { + _, begNil := r.Lo.(Nil) + _, endNil := r.Hi.(Nil) + beg, end := "", "" + if !begNil || endNil { + beg = r.Lo.Inspect() + } + if begNil || !endNil { + end = r.Hi.Inspect() + } + return beg + r.sep() + end +} -// rangeEnd renders one endpoint, or "" for a nil (beginless/endless) bound. -func rangeEnd(v Value, inspect bool) string { +// rangeEnd renders one endpoint for #to_s, or "" for a nil (beginless/endless) +// bound — MRI's range_to_s applies rb_obj_as_string (i.e. #to_s) to each bound, +// so nil.to_s = "" and (nil..nil).to_s = "..". +func rangeEnd(v Value) string { if _, ok := v.(Nil); ok { return "" } - if inspect { - return v.Inspect() - } return v.ToS() } func (r *Range) Truthy() bool { return true } diff --git a/internal/vm/prelude.rb b/internal/vm/prelude.rb index 6419c4c9..d460f7b3 100644 --- a/internal/vm/prelude.rb +++ b/internal/vm/prelude.rb @@ -1028,6 +1028,32 @@ def deconstruct class Range include Enumerable + + # Range#== is true when other is a Range (or subclass) with == begin, == end + # and the same exclude_end? flag, dispatching #== on the endpoints so that + # custom Comparable endpoints and Range subclasses compare by value (MRI's + # range_eq). Range#eql? is the same test but compares endpoints with #eql? + # (so 0..1 is not eql? to 0..1.0, though it is ==). + def ==(other) + return true if equal?(other) + return false unless other.is_a?(Range) + self.begin == other.begin && self.end == other.end && + exclude_end? == other.exclude_end? + end + + def eql?(other) + return true if equal?(other) + return false unless other.is_a?(Range) + self.begin.eql?(other.begin) && self.end.eql?(other.end) && + exclude_end? == other.exclude_end? + end + + # Range#hash mixes the two endpoints and the exclusive flag so that equal + # ranges (same begin, end and exclude_end?) hash alike and an inclusive range + # differs from its exclusive twin. + def hash + [self.begin, self.end, exclude_end?].hash + end end # Hash is Enumerable too: Hash#each yields a [key, value] pair, so map/find/count diff --git a/internal/vm/prelude_frozen_gen.go b/internal/vm/prelude_frozen_gen.go index 6b7a4ae4..2a777cdb 100644 --- a/internal/vm/prelude_frozen_gen.go +++ b/internal/vm/prelude_frozen_gen.go @@ -2597,14 +2597,53 @@ func embeddedPrelude() *bytecode.ISeq { }, &bytecode.ISeq{ Name: "", - Insns: []bytecode.Instr{{Op: 5}, {Op: 33}, {Op: 30, A: 1, B: 1}, {Op: 53}}, - Names: []string{"Enumerable", "include"}, + Insns: []bytecode.Instr{{Op: 5}, {Op: 33}, {Op: 30, A: 1, B: 1}, {Op: 9}, {Op: 44, A: 2}, {Op: 9}, {Op: 44, A: 3, B: 1}, {Op: 9}, {Op: 44, A: 4, B: 2}, {Op: 53}}, + Names: []string{"Enumerable", "include", "==", "eql?", "hash"}, NumRequired: 0, SplatIndex: -1, KwRestSlot: -1, BlockSlot: -1, NumLocals: 0, - Super: "", + Children: []*bytecode.ISeq{ + &bytecode.ISeq{ + Name: "==", + Insns: []bytecode.Instr{{Op: 5}, {Op: 11}, {Op: 30, B: 1}, {Op: 28, A: 7}, {Op: 3}, {Op: 53}, {Op: 26, A: 8}, {Op: 2}, {Op: 9}, {Op: 11}, {Op: 33, A: 1}, {Op: 30, A: 2, B: 1, Flags: 1}, {Op: 25}, {Op: 28, A: 17}, {Op: 4}, {Op: 53}, {Op: 26, A: 18}, {Op: 2}, {Op: 9}, {Op: 5}, {Op: 30, A: 3}, {Op: 11}, {Op: 30, A: 3, Flags: 1}, {Op: 22}, {Op: 10}, {Op: 28, A: 32}, {Op: 9}, {Op: 5}, {Op: 30, A: 4}, {Op: 11}, {Op: 30, A: 4, Flags: 1}, {Op: 22}, {Op: 10}, {Op: 28, A: 40}, {Op: 9}, {Op: 5}, {Op: 30, A: 5}, {Op: 11}, {Op: 30, A: 5, Flags: 1}, {Op: 22}, {Op: 53}}, + Names: []string{"equal?", "Range", "is_a?", "begin", "end", "exclude_end?"}, + Params: []string{"other"}, + NumRequired: 1, + SplatIndex: -1, + KwRestSlot: -1, + BlockSlot: -1, + NumLocals: 1, + Locals: []string{"other"}, + Super: "", + }, + &bytecode.ISeq{ + Name: "eql?", + Insns: []bytecode.Instr{{Op: 5}, {Op: 11}, {Op: 30, B: 1}, {Op: 28, A: 7}, {Op: 3}, {Op: 53}, {Op: 26, A: 8}, {Op: 2}, {Op: 9}, {Op: 11}, {Op: 33, A: 1}, {Op: 30, A: 2, B: 1, Flags: 1}, {Op: 25}, {Op: 28, A: 17}, {Op: 4}, {Op: 53}, {Op: 26, A: 18}, {Op: 2}, {Op: 9}, {Op: 5}, {Op: 30, A: 3}, {Op: 11}, {Op: 30, A: 3, Flags: 1}, {Op: 30, A: 4, B: 1, Flags: 1}, {Op: 10}, {Op: 28, A: 32}, {Op: 9}, {Op: 5}, {Op: 30, A: 5}, {Op: 11}, {Op: 30, A: 5, Flags: 1}, {Op: 30, A: 4, B: 1, Flags: 1}, {Op: 10}, {Op: 28, A: 40}, {Op: 9}, {Op: 5}, {Op: 30, A: 6}, {Op: 11}, {Op: 30, A: 6, Flags: 1}, {Op: 22}, {Op: 53}}, + Names: []string{"equal?", "Range", "is_a?", "begin", "eql?", "end", "exclude_end?"}, + Params: []string{"other"}, + NumRequired: 1, + SplatIndex: -1, + KwRestSlot: -1, + BlockSlot: -1, + NumLocals: 1, + Locals: []string{"other"}, + Super: "", + }, + &bytecode.ISeq{ + Name: "hash", + Insns: []bytecode.Instr{{Op: 5}, {Op: 30}, {Op: 5}, {Op: 30, A: 1}, {Op: 5}, {Op: 30, A: 2}, {Op: 6, A: 3}, {Op: 30, A: 3, Flags: 1}, {Op: 53}}, + Names: []string{"begin", "end", "exclude_end?", "hash"}, + NumRequired: 0, + SplatIndex: -1, + KwRestSlot: -1, + BlockSlot: -1, + NumLocals: 0, + Super: "", + }, + }, + Super: "", }, &bytecode.ISeq{ Name: "", From 5624a356d49db7792b149eb66ff7be2c8b4d54cf Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 17:38:50 +0200 Subject: [PATCH 2/4] Range/Comparable: initialize, count, String #+ step, entries alias, cmpint == MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Range#initialize: private native initializer behind Range.new — arity 2..3, comparable-endpoints check, FrozenError on an already-constructed (frozen) Range, fills a Range.allocate'd instance. - Range#count returns Float::INFINITY for any unbounded range (nil begin or end), even a String/Float bound whose #size is nil. - Range#step: a non-Integer step over a String range advances by #+ (MRI 4.0), e.g. ("A".."AAA").step("A") => "A","AA","AAA"; an incompatible step raises TypeError via String#+. - Range#entries is now a true alias of #to_a (shared method object). - rangeElemsV names the offending endpoint's class ("can't iterate from NilClass") rather than its value, matching MRI (fixes Range#to_set message). - Comparable#== follows rb_cmpint: nil is unequal, a zero (incl. 0.0) result is equal, and a non-nil non-comparison result (a String) raises ArgumentError. Adds internal/vm/range_comparable_residuals_test.go. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 111 ++++++-- internal/vm/prelude.rb | 13 +- internal/vm/prelude_frozen_gen.go | 8 +- .../vm/range_comparable_residuals_test.go | 245 ++++++++++++++++++ internal/vm/range_edges.go | 8 +- 5 files changed, 353 insertions(+), 32 deletions(-) create mode 100644 internal/vm/range_comparable_residuals_test.go diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 8395e8f2..33daf9e1 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -4359,6 +4359,28 @@ func (vm *VM) bootstrap() { // 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?"] + // Range#initialize(begin, end, exclude_end = false) is the private initializer + // behind Range.new. On an already-constructed Range — a raw *object.Range + // literal / Range.new result, which is frozen — it raises FrozenError; on a + // freshly Range.allocate'd instance (an unfrozen RObject) it fills in the + // bounds. It enforces arity 2..3 (ArgumentError otherwise) and the same + // comparable-endpoints check as Range.new (a nil #<=> — e.g. two plain + // Objects — is an ArgumentError "bad value for range"). + vm.cRange.define("initialize", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + if _, raw := self.(*object.Range); raw || isFrozen(self) { + vm.raiseFrozen(self) + } + if len(args) < 2 || len(args) > 3 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 2..3)", len(args)) + } + lo, hi := args[0], args[1] + if !object.IsNil(lo) && !object.IsNil(hi) && object.IsNil(vm.send(lo, "<=>", []object.Value{hi}, nil)) { + raise("ArgumentError", "bad value for range") + } + self.(*RObject).builtin = object.NewRange(lo, hi, len(args) == 3 && args[2].Truthy()) + return object.NilV + }) + vm.setInstanceVisibility(vm.cRange, "initialize", visPrivate) 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])) @@ -4462,8 +4484,14 @@ func (vm *VM) bootstrap() { }) vm.cRange.define("count", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { // Bare count is the range size; with a block or argument it counts - // matching elements (Enumerable#count). + // matching elements (Enumerable#count). An unbounded range (a nil begin + // or end) holds infinitely many elements, so MRI's range_count returns + // Float::INFINITY — even for a String/Float bound whose #size is nil. if blk == nil && len(args) == 0 { + r := self.(*object.Range) + if object.IsNil(r.Lo) || object.IsNil(r.Hi) { + return object.Float(math.Inf(1)) + } return rangeSizeFn(vm, self, args, blk) } arr := vm.send(self, "to_a", nil, nil).(*object.Array) @@ -4616,28 +4644,32 @@ func (vm *VM) bootstrap() { // range (e.g. "A"..) walks forever — the caller's block breaks out. _, hiIsStr := r.Hi.(*object.String) if loS, ok := r.Lo.(*object.String); ok && (object.IsNil(r.Hi) || hiIsStr) { - n, isInt := step.(object.Integer) - if !isInt { - raise("TypeError", "no implicit conversion of %s into Integer", vm.classOf(step).name) - } - switch { - case n == 0: - raise("ArgumentError", "step can't be 0") - case n < 0: - raise("ArgumentError", "step can't be negative") - } - if object.IsNil(r.Hi) { - for cur := loS.Str(); ; { - vm.callBlock(blk, []object.Value{object.NewString(cur)}) - for k := int64(0); k < int64(n); k++ { - cur = succString(cur) + if n, isInt := step.(object.Integer); isInt { + switch { + case n == 0: + raise("ArgumentError", "step can't be 0") + case n < 0: + raise("ArgumentError", "step can't be negative") + } + if object.IsNil(r.Hi) { + for cur := loS.Str(); ; { + vm.callBlock(blk, []object.Value{object.NewString(cur)}) + for k := int64(0); k < int64(n); k++ { + cur = succString(cur) + } } } + elems := strRangeElems(loS.Str(), r.Hi.(*object.String).Str(), r.Exclusive) + for i := 0; i < len(elems); i += int(n) { + vm.callBlock(blk, []object.Value{elems[i]}) + } + return r } - elems := strRangeElems(loS.Str(), r.Hi.(*object.String).Str(), r.Exclusive) - for i := 0; i < len(elems); i += int(n) { - vm.callBlock(blk, []object.Value{elems[i]}) - } + // MRI 4.0 (3.4+): a non-Integer step advances String elements by #+ + // rather than #succ — ("A".."AAA").step("A") yields "A","AA","AAA". An + // incompatible step (a Float, an Array, …) makes String#+ raise + // TypeError, exactly as MRI does when it tries begin + step. + vm.rangeStepByPlus(blk, r, step) return r } // An endless numeric range (m..) steps forever; the block breaks out. @@ -8241,7 +8273,9 @@ func (vm *VM) rangeElemsV(r *object.Range) []object.Value { return out } if !vm.respondsToDynamic(r.Lo, "succ") { - raise("TypeError", "can't iterate from %s", r.Lo.Inspect()) + // MRI names the offending endpoint's class (e.g. "can't iterate from + // NilClass" for a beginless range, "can't iterate from Float"), not its value. + raise("TypeError", "can't iterate from %s", vm.classOf(r.Lo).name) } var out []object.Value for cur := r.Lo; ; { @@ -8268,6 +8302,41 @@ func (vm *VM) rangeElemsV(r *object.Range) []object.Value { return out } +// rangeStepByPlus walks a bounded or endless range forward by repeatedly adding +// step with #+, yielding each value that has not passed end under #<=> (MRI +// 4.0's non-Integer String#step, e.g. ("A".."AAA").step("A")). An endless range +// walks until the block breaks; a bounded range stops once the next value would +// pass end (inclusive stops after the value equal to end, exclusive before it). +// begin + step dispatches String#+ (or the element's own #+), which raises +// TypeError for an incompatible step exactly as MRI does. +func (vm *VM) rangeStepByPlus(blk *Proc, r *object.Range, step object.Value) { + cur := r.Lo + if object.IsNil(r.Hi) { + for { + vm.callBlock(blk, []object.Value{cur}) + cur = vm.send(cur, "+", []object.Value{step}, nil) + } + } + for { + c, ok := vm.rangeCmpV(cur, r.Hi) + if !ok { + return + } + if r.Exclusive { + if c >= 0 { + return + } + } else if c > 0 { + return + } + vm.callBlock(blk, []object.Value{cur}) + if !r.Exclusive && c == 0 { + return + } + cur = vm.send(cur, "+", []object.Value{step}, nil) + } +} + func shiftInt(a *big.Int, n int64) object.Value { if n >= 0 { return object.NormInt(new(big.Int).Lsh(a, uint(n))) diff --git a/internal/vm/prelude.rb b/internal/vm/prelude.rb index d460f7b3..b5696631 100644 --- a/internal/vm/prelude.rb +++ b/internal/vm/prelude.rb @@ -44,10 +44,17 @@ def >=(other) __compare(other) >= 0 end - # Comparable#== is deliberately lenient: an incomparable pair (`<=>` returning - # nil) is simply unequal rather than an error, matching MRI. + # Comparable#== is lenient about an incomparable pair — a `<=>` returning nil + # is simply unequal (false), not an error. A non-nil result is reduced to a + # sign the way MRI's rb_cmpint does: zero (including 0.0) means equal, and a + # non-zero result is validated with #> / #< against 0, which raises the same + # ArgumentError the ordering operators do for a bogus result such as a String. def ==(other) - (self <=> other) == 0 + cmp = (self <=> other) + return false if cmp.nil? + return true if cmp == 0 + cmp > 0 || cmp < 0 + false end def between?(min, max) diff --git a/internal/vm/prelude_frozen_gen.go b/internal/vm/prelude_frozen_gen.go index 2a777cdb..b5bf94a8 100644 --- a/internal/vm/prelude_frozen_gen.go +++ b/internal/vm/prelude_frozen_gen.go @@ -117,18 +117,18 @@ func embeddedPrelude() *bytecode.ISeq { }, &bytecode.ISeq{ Name: "==", - Insns: []bytecode.Instr{{Op: 5}, {Op: 11}, {Op: 30, B: 1}, {Op: 1}, {Op: 22}, {Op: 53}}, + Insns: []bytecode.Instr{{Op: 5}, {Op: 11}, {Op: 30, B: 1}, {Op: 12, A: 1}, {Op: 9}, {Op: 11, A: 1}, {Op: 30, A: 1, Flags: 1}, {Op: 28, A: 11}, {Op: 4}, {Op: 53}, {Op: 26, A: 12}, {Op: 2}, {Op: 9}, {Op: 11, A: 1}, {Op: 1}, {Op: 22}, {Op: 28, A: 20}, {Op: 3}, {Op: 53}, {Op: 26, A: 21}, {Op: 2}, {Op: 9}, {Op: 11, A: 1}, {Op: 1}, {Op: 19}, {Op: 10}, {Op: 27, A: 31}, {Op: 9}, {Op: 11, A: 1}, {Op: 1}, {Op: 18}, {Op: 9}, {Op: 4}, {Op: 53}}, Consts: []object.Value{ object.IntValue(0), }, - Names: []string{"<=>"}, + Names: []string{"<=>", "nil?"}, Params: []string{"other"}, NumRequired: 1, SplatIndex: -1, KwRestSlot: -1, BlockSlot: -1, - NumLocals: 1, - Locals: []string{"other"}, + NumLocals: 2, + Locals: []string{"other", "cmp"}, Super: "", }, &bytecode.ISeq{ diff --git a/internal/vm/range_comparable_residuals_test.go b/internal/vm/range_comparable_residuals_test.go new file mode 100644 index 00000000..700620e8 --- /dev/null +++ b/internal/vm/range_comparable_residuals_test.go @@ -0,0 +1,245 @@ +// 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 verified byte-for-byte against MRI Ruby 4.0.6 +// (ruby -e '...') for the ruby/spec core/range and core/comparable residuals: +// value-based Range#== / #eql? / #hash, the (nil..nil) #inspect rule, Range's +// private #initialize (arity / frozen / bad-value), Range#count over unbounded +// ranges, the MRI-4.0 non-Integer String#step (#+ walk), and Comparable#== +// under an rb_cmpint-style non-nil, non-zero #<=> result. + +// TestRangeEqualEqlHash covers Range#==, #eql? and #hash, which now compare by +// endpoint value (dispatching #== / #eql?) rather than object identity. +func TestRangeEqualEqlHash(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"eq_same", `p((0..2) == (0..2))`, "true\n"}, + {"eq_int_float", `p((0..1) == (0..1.0))`, "true\n"}, + {"eq_excl_differs", `p((0..1) == (0...1))`, "false\n"}, + {"eq_not_range", `p((1..10) == 1)`, "false\n"}, + {"eq_endless", `p((1..) == (1..))`, "true\n"}, + {"eq_endless_excl", `p((1..) == (1...))`, "false\n"}, + {"eq_beginless", `p((...10) == (...10))`, "true\n"}, + {"eql_true", `p((0..2).eql?(0..2))`, "true\n"}, + {"eql_int_float", `p((0..1).eql?(0..1.0))`, "false\n"}, + {"eql_not_range", `p((1..10).eql?('a'))`, "false\n"}, + // A Range subclass with equal endpoints is == and eql? to a plain Range. + {"eq_subclass", ` +class MyR < Range; end +p(Range.new(1, 2) == MyR.new(1, 2))`, "true\n"}, + // Custom endpoints compare by their own #== (here: same @v). The ruby/spec + // custom-endpoint case invokes it as a message send (a.send(:==, b)), which + // dispatches Range#== rather than the primitive == fast path. + {"eq_custom_endpoints", ` +class Pt + include Comparable + def initialize(v); @v = v; end + attr_reader :v + def <=>(o); @v <=> o.v; end + def ==(o); o.is_a?(Pt) && @v == o.v; end +end +a = Pt.new(1)..Pt.new(3) +b = Range.new(Pt.new(1), Pt.new(3)) +p(a.send(:==, b))`, "true\n"}, + // Equal ranges hash alike; an inclusive range differs from its exclusive twin. + {"hash_equal", `p((0..1).hash == (0..1).hash)`, "true\n"}, + {"hash_excl_differs", `p((0..10).hash == (0...10).hash)`, "false\n"}, + {"hash_is_integer", `p((0..1).hash.is_a?(Integer))`, "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) + } + }) + } +} + +// TestRangeInspectToS covers the (nil..nil) #inspect special case (both bounds +// render as "nil") while #to_s and the one-sided unbounded forms stay bare. +func TestRangeInspectToS(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"inspect_nilnil", `p((..nil).inspect)`, "\"nil..nil\"\n"}, + {"inspect_endless", `p((1..).inspect)`, "\"1..\"\n"}, + {"inspect_beginless", `p((..1).inspect)`, "\"..1\"\n"}, + {"inspect_beginless_excl", `p((...1).inspect)`, "\"...1\"\n"}, + {"inspect_bounded", `p((1..5).inspect)`, "\"1..5\"\n"}, + {"inspect_str", `p(('A'..'Z').inspect)`, "\"\\\"A\\\"..\\\"Z\\\"\"\n"}, + {"to_s_nilnil", `p((nil..nil).to_s)`, "\"..\"\n"}, + {"to_s_endless", `p((1..).to_s)`, "\"1..\"\n"}, + {"to_s_bounded", `p((1..5).to_s)`, "\"1..5\"\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) + } + }) + } +} + +// TestRangeInitialize covers the private Range#initialize: it fills in a freshly +// allocated Range, is listed as a private instance method, enforces arity 2..3 +// and comparable endpoints, and refuses to reinitialise a frozen (constructed) +// Range. +func TestRangeInitialize(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"is_private", `p(Range.private_instance_methods(false).include?(:initialize))`, "true\n"}, + {"allocate_init_two", ` +r = Range.allocate +r.send(:initialize, 0, 2) +p(r.to_a)`, "[0, 1, 2]\n"}, + {"allocate_init_three", ` +r = Range.allocate +r.send(:initialize, 0, 2, true) +p(r.to_a)`, "[0, 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) + } + }) + } + errCases := []struct{ name, src, class string }{ + {"init_too_few", `Range.allocate.send(:initialize, 1)`, "ArgumentError"}, + {"init_too_many", `Range.allocate.send(:initialize, 1, 2, 3, 4)`, "ArgumentError"}, + {"init_bad_value", `Range.allocate.send(:initialize, Object.new, Object.new)`, "ArgumentError"}, + {"init_frozen", `(0..1).send(:initialize, 1, 3)`, "FrozenError"}, + {"init_frozen_three", `(0..1).send(:initialize, 1, 3, true)`, "FrozenError"}, + } + for _, tc := range errCases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.class) { + t.Errorf("src=%q: got err=%v, want %s", tc.src, err, tc.class) + } + }) + } +} + +// TestRangeCountAndEntries covers Range#count over unbounded ranges (Infinity) +// and the true-alias Range#entries. +func TestRangeCountAndEntries(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"count_endless_int", `p((7..).count)`, "Infinity\n"}, + {"count_endless_str", `p(('a'...).count)`, "Infinity\n"}, + {"count_beginless_str", `p((...'a').count)`, "Infinity\n"}, + {"count_beginless_float", `p((..10.0).count)`, "Infinity\n"}, + {"count_nilnil", `p((nil..nil).count)`, "Infinity\n"}, + {"count_bounded", `p((1..4).count)`, "4\n"}, + {"count_with_block", `p((1..4).count(&:even?))`, "2\n"}, + {"entries_alias", `p(Range.instance_method(:entries) == Range.instance_method(:to_a))`, "true\n"}, + {"entries_value", `p((1..3).entries)`, "[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) + } + }) + } +} + +// TestRangeStepStringPlus covers MRI 4.0's non-Integer String#step, which +// advances by #+ (not #succ) and raises TypeError for an incompatible step. +func TestRangeStepStringPlus(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"step_plus_inclusive", ` +a = [] +("A".."AAA").step("A") { |x| a << x } +p(a)`, "[\"A\", \"AA\", \"AAA\"]\n"}, + {"step_plus_exclusive", ` +a = [] +("A"..."AAA").step("A") { |x| a << x } +p(a)`, "[\"A\", \"AA\"]\n"}, + {"step_plus_endless", ` +a = [] +("A"..).step("A") { |x| break if x > "AAA"; a << x } +p(a)`, "[\"A\", \"AA\", \"AAA\"]\n"}, + // The existing Integer-step (via #succ) path still works. + {"step_int_succ", ` +a = [] +("A".."G").step(2) { |x| a << x } +p(a)`, "[\"A\", \"C\", \"E\", \"G\"]\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) + } + }) + } + errCases := []struct{ name, src, class string }{ + {"step_float", `("A".."G").step(2.0) { }`, "TypeError"}, + {"step_array", `("A".."G").step([]) { }`, "TypeError"}, + // A beginless String range cannot be materialised: MRI names the class. + {"to_a_beginless", `(..'a').to_a`, "NilClass"}, + } + for _, tc := range errCases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.class) { + t.Errorf("src=%q: got err=%v, want %s", tc.src, err, tc.class) + } + }) + } +} + +// TestComparableEqualCmpint covers Comparable#== under the rb_cmpint rule: nil is +// unequal, a zero (including 0.0) result is equal, and a non-nil, non-comparison +// result (a String) raises ArgumentError. +func TestComparableEqualCmpint(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"eq_zero", ` +class C0 + include Comparable + def <=>(o); 0; end +end +p(C0.new == C0.new)`, "true\n"}, + {"eq_zero_float", ` +class Cf + include Comparable + def <=>(o); 0.0; end +end +p(Cf.new == Cf.new)`, "true\n"}, + {"eq_nonzero", ` +class Cn + include Comparable + def <=>(o); 1; end +end +p(Cn.new == Cn.new)`, "false\n"}, + {"eq_nil", ` +class Cnil + include Comparable + def <=>(o); nil; end +end +p(Cnil.new == Cnil.new)`, "false\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) + } + }) + } + t.Run("eq_bad_cmp_raises", func(t *testing.T) { + src := ` +class Cbad + include Comparable + def <=>(o); "abc"; end +end +Cbad.new == Cbad.new` + err := runErr(t, src) + if err == nil || !strings.Contains(err.Error(), "ArgumentError") { + t.Errorf("got err=%v, want ArgumentError", err) + } + }) +} diff --git a/internal/vm/range_edges.go b/internal/vm/range_edges.go index bb42fc91..1aa69b30 100644 --- a/internal/vm/range_edges.go +++ b/internal/vm/range_edges.go @@ -60,10 +60,10 @@ func (vm *VM) registerRangeEdges() { return r }) - // entries is a straight alias of to_a. - vm.cRange.define("entries", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return object.NewArrayFromSlice(rangeElems(self.(*object.Range))) - }) + // entries is a true alias of to_a (Range.instance_method(:entries) == + // Range.instance_method(:to_a)), so it shares the same method object rather + // than wrapping a second implementation. + aliasBuiltin(vm.cRange, "entries", "to_a") } // isIntegerValue reports whether v is an Integer or Bignum (an exact integer). From f52d0e4ec6bdcdf12a4383669d36d17ac0dfaed9 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 18:53:20 +0200 Subject: [PATCH 3/4] Range: reverse_each descent, ArithmeticSequence step/%, MRI inspect - Range#reverse_each: supports beginless Integer ranges (descends from the end forever; bounded via take), Symbol and generic #succ ranges (via rangeElemsV), and its Enumerator #size names the END's class for a non-countable begin, returns Infinity for a beginless Integer end (MRI 4.0). - Range#step without a block returns an Enumerator::ArithmeticSequence for a numeric range (Numeric begin, or beginless with Numeric end) and a plain Enumerator for a String range, matching MRI 2.6+. - Range#% is Range#step's alias, producing an ArithmeticSequence whose #inspect reads ((1..10).%(2)); the % operator on a Range now dispatches the method. - Enumerator::ArithmeticSequence#inspect/#to_s follow MRI: ((b..e).step(s)) / ((b..e).%(s)) for a Range receiver, (b.step(e, s)) for a Numeric receiver. - Updated range_edges_test.go and step_test.go, which encoded pre-4.0 behavior (beginless reverse_each raising; blockless numeric step returning a plain Enumerator), to the MRI 4.0.6 results. Co-Authored-By: Claude Opus 4.8 --- internal/vm/arith.go | 6 ++ internal/vm/builtins.go | 26 +++++- internal/vm/enumerator.go | 21 +++++ .../vm/range_comparable_residuals_test.go | 88 +++++++++++++++++++ internal/vm/range_edges.go | 60 ++++++++++--- internal/vm/range_edges_test.go | 10 ++- internal/vm/step_test.go | 5 +- 7 files changed, 198 insertions(+), 18 deletions(-) diff --git a/internal/vm/arith.go b/internal/vm/arith.go index 13333ead..4cfe5c54 100644 --- a/internal/vm/arith.go +++ b/internal/vm/arith.go @@ -340,6 +340,12 @@ func (vm *VM) binaryOp(op bytecode.Op, a, b object.Value) object.Value { if _, isEnum := a.(*Enumerator); isEnum && op == bytecode.OpAdd { return vm.send(a, arithOpName(op), []object.Value{b}, nil) } + // A Range dispatches its % operator (Range#% is Range#step, producing an + // Enumerator::ArithmeticSequence) as a method rather than the numeric + // modulo path, which would reject the Range receiver. + if _, isRange := a.(*object.Range); isRange && op == bytecode.OpMod { + return vm.send(a, "%", []object.Value{b}, nil) + } // A URI dispatches its arithmetic operator (only + is defined, resolving a // reference) as a method, so the binding's merge — which needs the VM to // wrap the result — runs with a live VM rather than the VM-less binary path. diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 33daf9e1..627dc807 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -4632,11 +4632,18 @@ func (vm *VM) bootstrap() { 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 - // never finishes walking. + // never finishes walking. A numeric range (a Numeric begin, or a + // beginless range with a Numeric end) with a numeric step returns an + // Enumerator::ArithmeticSequence — exposing #begin/#end/#step — exactly + // like MRI; a non-numeric range (a String range) stays a plain + // Enumerator. r := self.(*object.Range) - return enumForSized(self, "step", func(*VM) object.Value { - return rangeStepSize(r, step) - }, args...) + size := func(*VM) object.Value { return rangeStepSize(r, step) } + numericRange := isNumericValue(r.Lo) || (object.IsNil(r.Lo) && isNumericValue(r.Hi)) + if numericRange && isNumericValue(step) { + return vm.arithSeq(self, r.Lo, r.Hi, step, r.Exclusive, size, args...) + } + return enumForSized(self, "step", size, args...) } r := self.(*object.Range) // A String range steps by #succ: MRI requires an Integer step and yields @@ -4680,6 +4687,17 @@ func (vm *VM) bootstrap() { vm.numericStep(blk, r.Lo, r.Hi, step, r.Exclusive) return r }) + // Range#%(step) is MRI's alias for Range#step, so it shares the iteration and + // (no-block) ArithmeticSequence machinery — the only difference is that the + // sequence remembers it was built by #% so its #inspect reads + // "((1..10).%(2))" rather than "((1..10).step(2))". + vm.cRange.define("%", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { + res := vm.send(self, "step", args, blk) + if e, ok := res.(*Enumerator); ok && e.isArithSeq { + e.asMethod = "%" + } + return res + }) // Integer methods. // intOf coerces a receiver to int64; a Bignum is genuinely out of range for diff --git a/internal/vm/enumerator.go b/internal/vm/enumerator.go index 0ff562f3..d2fb5f4f 100644 --- a/internal/vm/enumerator.go +++ b/internal/vm/enumerator.go @@ -51,6 +51,9 @@ type Enumerator struct { asEnd object.Value asStep object.Value asExcl bool + // asMethod is the constructing method name shown by ArithmeticSequence#inspect + // for a Range receiver ("step" or "%"); "" defaults to "step". + asMethod string // isChain marks an Enumerator::Chain: #each iterates chainParts in turn, and // entered[i] records whether part i has been iterated (so #rewind can rewind, // in reverse, exactly the parts that were entered). @@ -180,6 +183,24 @@ func (vm *VM) registerEnumerator() { vm.cArithSeq.define("exclude_end?", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return object.Bool(self.(*Enumerator).asExcl) }) + // #inspect / #to_s mirror MRI's arith_seq_inspect: a Range receiver reads + // ((begin..end).step(step)) — or .%(step) when built by Range#% — while a + // Numeric receiver reads (begin.step(end, step)). A nil begin/end (an + // unbounded sequence) renders empty on that side, as Range#inspect does. + arithSeqInspect := func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + e := self.(*Enumerator) + if _, isRange := e.recv.(*object.Range); isRange { + meth := e.asMethod + if meth == "" { + meth = "step" + } + rng := object.NewRange(e.asBegin, e.asEnd, e.asExcl) + return object.NewString("((" + rng.Inspect() + ")." + meth + "(" + e.asStep.Inspect() + "))") + } + return object.NewString("(" + e.asBegin.Inspect() + ".step(" + e.asEnd.Inspect() + ", " + e.asStep.Inspect() + "))") + } + vm.cArithSeq.define("inspect", arithSeqInspect) + vm.cArithSeq.define("to_s", arithSeqInspect) // #last materialises the (necessarily bounded) sequence; MRI refuses it for an // endless one rather than looping for ever. vm.cArithSeq.define("last", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { diff --git a/internal/vm/range_comparable_residuals_test.go b/internal/vm/range_comparable_residuals_test.go index 700620e8..04dcea6a 100644 --- a/internal/vm/range_comparable_residuals_test.go +++ b/internal/vm/range_comparable_residuals_test.go @@ -193,6 +193,94 @@ p(a)`, "[\"A\", \"C\", \"E\", \"G\"]\n"}, } } +// TestRangeStepArithSeqAndPercent covers Range#step without a block returning an +// Enumerator::ArithmeticSequence for a numeric range (with #begin/#end/#step and +// the MRI #inspect), a plain Enumerator for a String range, and Range#% as the +// step-alias whose sequence inspects with a percent sign. +func TestRangeStepArithSeqAndPercent(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"step_class", `p((1..10).step(2).class)`, "Enumerator::ArithmeticSequence\n"}, + {"step_beginless_class", `p((..10).step(2).class)`, "Enumerator::ArithmeticSequence\n"}, + {"step_endless_class", `p((1..).step(2).class)`, "Enumerator::ArithmeticSequence\n"}, + {"step_str_class", `p(('a'..'e').step(2).class)`, "Enumerator\n"}, + {"step_begin", `p((1..10).step(2).begin)`, "1\n"}, + {"step_end", `p((1..10).step(2).end)`, "10\n"}, + {"step_step", `p((1..10).step(2).step)`, "2\n"}, + {"step_to_a", `p((1..10).step(2).to_a)`, "[1, 3, 5, 7, 9]\n"}, + {"step_inspect", `p((1..10).step(2).inspect)`, "\"((1..10).step(2))\"\n"}, + {"pct_class", `p(((1..10) % 2).class)`, "Enumerator::ArithmeticSequence\n"}, + {"pct_begin", `p(((1..10) % 2).begin)`, "1\n"}, + {"pct_end", `p(((1..10) % 2).end)`, "10\n"}, + {"pct_step", `p(((1..10) % 2).step)`, "2\n"}, + {"pct_to_a", `p(((1..10) % 2).to_a)`, "[1, 3, 5, 7, 9]\n"}, + {"pct_inspect", `p(((1..10) % 2).inspect)`, "\"((1..10).%(2))\"\n"}, + {"numeric_step_inspect", `p(1.step(10, 2).inspect)`, "\"(1.step(10, 2))\"\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) + } + }) + } +} + +// TestRangeReverseEach covers reverse_each's descent: bounded Integer/String/ +// Symbol ranges, a beginless Integer range (descends forever, taken via an +// Enumerator), and the reverse-Enumerator #size (forward count, Infinity for a +// beginless Integer end, nil for a String begin, and a TypeError naming the +// end's class for a non-countable begin). +func TestRangeReverseEachResiduals(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"rev_int", ` +a = [] +(1..3).reverse_each { |i| a << i } +p(a)`, "[3, 2, 1]\n"}, + {"rev_int_excl", ` +a = [] +(1...3).reverse_each { |i| a << i } +p(a)`, "[2, 1]\n"}, + {"rev_str", ` +a = [] +('A'..'D').reverse_each { |i| a << i } +p(a)`, "[\"D\", \"C\", \"B\", \"A\"]\n"}, + {"rev_sym", ` +a = [] +(:A..:D).reverse_each { |i| a << i } +p(a)`, "[:D, :C, :B, :A]\n"}, + {"rev_beginless_int", `p((..5).reverse_each.take(3))`, "[5, 4, 3]\n"}, + {"rev_beginless_int_excl", `p((...5).reverse_each.take(3))`, "[4, 3, 2]\n"}, + {"rev_size_int", `p((1..3).reverse_each.size)`, "3\n"}, + {"rev_size_float_end", `p((1..3.3).reverse_each.size)`, "3\n"}, + {"rev_size_beginless_inf", `p((..3).reverse_each.size)`, "Infinity\n"}, + {"rev_size_str_nil", `p(('a'..'z').reverse_each.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) + } + }) + } + errCases := []struct{ name, src, msg string }{ + {"rev_endless", `(1..).reverse_each { |x| x }`, "can't iterate from NilClass"}, + {"rev_beginless_str", `(..'a').reverse_each { |x| x }`, "can't iterate from NilClass"}, + {"rev_size_float_begin", `(1.1..3).reverse_each.size`, "can't iterate from Integer"}, + {"rev_size_float_begin_float_end", `(1.1..3.3).reverse_each.size`, "can't iterate from Float"}, + {"rev_size_nil_float_end", `(nil..3.3).reverse_each.size`, "can't iterate from Float"}, + {"rev_size_nilnil", `(nil..nil).reverse_each.size`, "can't iterate from NilClass"}, + {"rev_time_no_succ", `(Time.now..Time.now).reverse_each { |x| x }`, "can't iterate from Time"}, + } + for _, tc := range errCases { + t.Run(tc.name, func(t *testing.T) { + err := runErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.msg) { + t.Errorf("src=%q: got err=%v, want containing %q", tc.src, err, tc.msg) + } + }) + } +} + // TestComparableEqualCmpint covers Comparable#== under the rb_cmpint rule: nil is // unequal, a zero (including 0.0) result is equal, and a non-nil, non-comparison // result (a String) raises ArgumentError. diff --git a/internal/vm/range_edges.go b/internal/vm/range_edges.go index 1aa69b30..9686085e 100644 --- a/internal/vm/range_edges.go +++ b/internal/vm/range_edges.go @@ -34,26 +34,38 @@ func (vm *VM) registerRangeEdges() { } return vm.rangeBsearch(r, blk) }) - // reverse_each yields the elements from end down to begin. rbgo materialises - // the range forward (via rangeElems) and walks the slice backwards, so it - // requires a range that can be enumerated: an endless range (nil end) or a - // begin that is neither an Integer nor a String cannot be iterated and raises - // a TypeError naming the offending class, exactly like MRI. Without a block it - // returns an Enumerator whose #size is the Range#size. + // reverse_each yields the elements from end down to begin. An endless range + // (nil end) has no greatest element to descend from, so it raises TypeError. + // A beginless range with an Integer end descends from that end forever (the + // block breaks out, e.g. via take); a beginless range whose end is not an + // Integer can't be counted down and raises naming the (nil) begin's class. + // A bounded range is materialised forward via rangeElemsV — which handles + // Integer, String, Symbol and any #succ object, and itself raises "can't + // iterate from " for a begin that cannot be enumerated — then walked + // backwards. Without a block it returns an Enumerator whose #size is the + // Range#size. vm.cRange.define("reverse_each", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) object.Value { r := self.(*object.Range) if blk == nil { - return enumForSized(self, "reverse_each", func(vm *VM) object.Value { return vm.rangeSizeVal(r) }) + return enumForSized(self, "reverse_each", func(vm *VM) object.Value { return vm.rangeReverseSizeVal(r) }) } if object.IsNil(r.Hi) { return raise("TypeError", "can't iterate from %s", vm.classOf(r.Hi).name) } - switch r.Lo.(type) { - case object.Integer, *object.String: - default: + if object.IsNil(r.Lo) { + if isIntegerValue(r.Hi) { + n := new(big.Int).Set(bigVal(r.Hi)) + if r.Exclusive { + n.Sub(n, big.NewInt(1)) + } + for { + vm.callBlock(blk, []object.Value{object.NormInt(n)}) + n = new(big.Int).Sub(n, big.NewInt(1)) + } + } return raise("TypeError", "can't iterate from %s", vm.classOf(r.Lo).name) } - elems := rangeElems(r) + elems := vm.rangeElemsV(r) for i := len(elems) - 1; i >= 0; i-- { vm.callBlock(blk, []object.Value{elems[i]}) } @@ -66,6 +78,32 @@ func (vm *VM) registerRangeEdges() { aliasBuiltin(vm.cRange, "entries", "to_a") } +// rangeReverseSizeVal is the #size of a Range#reverse_each Enumerator (MRI 4.0), +// which descends from the range's end. An Integer begin counts forward like +// Range#size (a Float or nil end still yields the whole-step count). A beginless +// range with an Integer end descends forever (Float::INFINITY). A String/Symbol +// begin has no numeric count (nil). Any other shape — a Float or nil begin, or a +// beginless range whose end is not an Integer — cannot be counted down and +// raises a TypeError naming the END's class, since reverse iteration starts from +// the end (so (1.1..3).reverse_each.size reports "can't iterate from Integer"). +func (vm *VM) rangeReverseSizeVal(r *object.Range) object.Value { + switch { + case isIntegerValue(r.Lo): + return vm.rangeSizeVal(r) + case object.IsNil(r.Lo): + if isIntegerValue(r.Hi) { + return object.Float(math.Inf(1)) + } + return raise("TypeError", "can't iterate from %s", vm.classOf(r.Hi).name) + default: + switch r.Lo.(type) { + case *object.String, object.Symbol: + return object.NilV + } + return raise("TypeError", "can't iterate from %s", vm.classOf(r.Hi).name) + } +} + // isIntegerValue reports whether v is an Integer or Bignum (an exact integer). func isIntegerValue(v object.Value) bool { switch v.(type) { diff --git a/internal/vm/range_edges_test.go b/internal/vm/range_edges_test.go index 7c4e2bcd..c9b175bd 100644 --- a/internal/vm/range_edges_test.go +++ b/internal/vm/range_edges_test.go @@ -137,6 +137,11 @@ func TestRangeReverseEach(t *testing.T) { {"enum_size", `p((1..3).reverse_each.size)`, "3\n"}, {"enum_size_excl", `p((1...3).reverse_each.size)`, "2\n"}, {"enum_size_float_end", `p((1..3.3).reverse_each.size)`, "3\n"}, + // A beginless Integer range descends from its end forever (MRI 4.0); the + // Enumerator's take bounds it. + {"beginless_int", `p((..5).reverse_each.take(3))`, "[5, 4, 3]\n"}, + {"beginless_int_excl", `p((...5).reverse_each.take(3))`, "[4, 3, 2]\n"}, + {"symbol", "a=[]\n(:A..:D).reverse_each{|i| a< Date: Mon, 31 Aug 2026 19:04:19 +0200 Subject: [PATCH 4/4] Range#step #+ walk: drop unreachable incomparable guard, cover backward case The String-only #+ walk always compares two Strings, so rangeCmpV never reports incomparability; drop the dead guard and add a backward-range test (( 'D'..'A' ).step('A') => []) covering the overshoot return. Keeps the changed function at 100% coverage. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 7 +++---- internal/vm/range_comparable_residuals_test.go | 5 +++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 627dc807..8075267e 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -8336,10 +8336,9 @@ func (vm *VM) rangeStepByPlus(blk *Proc, r *object.Range, step object.Value) { } } for { - c, ok := vm.rangeCmpV(cur, r.Hi) - if !ok { - return - } + // cur and end are both Strings on this path (String#+ keeps cur a String, or + // raises for an incompatible step), so #<=> always yields a comparison. + c, _ := vm.rangeCmpV(cur, r.Hi) if r.Exclusive { if c >= 0 { return diff --git a/internal/vm/range_comparable_residuals_test.go b/internal/vm/range_comparable_residuals_test.go index 04dcea6a..27e8f864 100644 --- a/internal/vm/range_comparable_residuals_test.go +++ b/internal/vm/range_comparable_residuals_test.go @@ -164,6 +164,11 @@ p(a)`, "[\"A\", \"AA\"]\n"}, a = [] ("A"..).step("A") { |x| break if x > "AAA"; a << x } p(a)`, "[\"A\", \"AA\", \"AAA\"]\n"}, + // A backward String range steps to nothing (begin already past end). + {"step_plus_backward", ` +a = [] +("D".."A").step("A") { |x| a << x } +p(a)`, "[]\n"}, // The existing Integer-step (via #succ) path still works. {"step_int_succ", ` a = []