From 7b67b28519ecfdd25bfe56cfa4ee797d1aff55ef Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 10:34:24 +0200 Subject: [PATCH] Range: construction #<=> dispatch + #step #coerce (MRI 4.0.6 conformance) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Range construction now performs MRI's construction-time `begin <=> end` comparison — a dispatch several specs observe through a mocked `#<=>`: - `Range.new` / `Range#initialize` are strict, mirroring MRI's range_init: an unordered pair (`#<=>` nil and not `#==`) is "bad value for range"; a pair that is `#==` without its own `#<=>` (two identical Regexps, whose only comparison is Object's identity default) still builds, matching MRI's Object#<=> answering 0 for `#==` objects. - The range literal performs the comparison for its dispatch but keeps rbgo's tolerance for an unordered literal, so a discarded `(1.."z")` still builds (no spec asserts the literal raises; internal tests rely on it). This closes the "uses the range element's #<=>" count on Range#cover? / #=== (the construction call is the second `#<=>`), the each/step "first element" TypeError-after-construction cases, and Range#step's non-numeric #size case. Range#step now coerces a non-numeric step against the range begin via MRI's numeric coercion — (1..3).step(obj) with obj.coerce(1) => [1, 2] walks 1, 3 — in numericStep (only reached by Range#step; Numeric#step rejects such a step first), matching MRI where Range#step coerces but Numeric#step does not. core/range: 586 -> 591 (case_compare +1, cover +1, each +1, step +2), no regressions. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 16 ++-- internal/vm/range_edges.go | 51 ++++++++++++ internal/vm/range_residuals_wave13_test.go | 93 ++++++++++++++++++++++ internal/vm/vm.go | 2 +- 4 files changed, 153 insertions(+), 9 deletions(-) create mode 100644 internal/vm/range_residuals_wave13_test.go diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index d5b83981..9fbeb944 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -2627,10 +2627,7 @@ func (vm *VM) bootstrap() { 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") - } - r := object.NewRange(lo, hi, len(args) == 3 && args[2].Truthy()) + r := vm.newRange(lo, hi, len(args) == 3 && args[2].Truthy(), true) if recv := self.(*RClass); recv != vm.cRange { return &RObject{class: recv, ivars: map[string]object.Value{}, builtin: r} } @@ -5036,10 +5033,7 @@ func (vm *VM) bootstrap() { 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()) + self.(*RObject).builtin = vm.newRange(lo, hi, len(args) == 3 && args[2].Truthy(), true) return object.NilV }) vm.setInstanceVisibility(vm.cRange, "initialize", visPrivate) @@ -10410,6 +10404,12 @@ func (vm *VM) stepEnum(recv, begin, limit, step object.Value, excl bool, args .. // accumulated drift. step must be non-zero. func (vm *VM) numericStep(blk *Proc, loV, hiV, stepV object.Value, exclusive bool) { rejectStringStep(stepV) + // A non-numeric step on a numeric Range#step is coerced against the range's + // begin (MRI's numeric coercion), so (1..3).step(obj) with obj.coerce(1) => + // [1, 2] walks 1, 3. Integer#step / Float#step never reach here with such a + // step — their numericStepArgCheck rejects it first — so this only affects + // Range#step, matching MRI (where Range#step coerces but Numeric#step does not). + loV, stepV = vm.coerceRangeStep(loV, stepV) li, loInt := loV.(object.Integer) hi2, hiInt := hiV.(object.Integer) si, stepInt := stepV.(object.Integer) diff --git a/internal/vm/range_edges.go b/internal/vm/range_edges.go index 9686085e..4499e1e1 100644 --- a/internal/vm/range_edges.go +++ b/internal/vm/range_edges.go @@ -408,3 +408,54 @@ func rangeIsEmpty(r *object.Range) bool { c, _ := rangeCmp(r.Lo, r.Hi) return c > 0 || (c == 0 && r.Exclusive) } + +// newRange builds a Range value, performing MRI's construction-time begin <=> end +// comparison — a dispatch some specs observe through a mocked #<=>. When strict +// (as Range.new and Range#initialize are) a comparison that does not order the +// bounds is a "bad value for range" ArgumentError, matching MRI's range_init; the +// range literal (OpNewRange) is not strict — it performs the comparison for its +// dispatch but keeps rbgo's tolerance for an unordered literal, so a discarded +// (1.."z") still builds as before. Either bound nil (a beginless/endless range) +// or two Integer bounds (MRI's Fixnum fast path) skip the comparison, and any +// exception raised by #<=> propagates. +// +// The strict "does not order" test mirrors MRI's Object#<=>, which answers 0 (not +// nil) for two objects that are merely #== without defining their own #<=>: #<=> +// is consulted first and #== only when it is nil, so two identical Regexp or bare +// Object bounds — whose sole comparison is the identity default — still count as +// comparable and Range.new(//, //) builds exactly as under MRI, while an endpoint +// with a real ordering never triggers the extra #== send. +func (vm *VM) newRange(lo, hi object.Value, exclusive, strict bool) *object.Range { + if !object.IsNil(lo) && !object.IsNil(hi) { + _, loInt := lo.(object.Integer) + _, hiInt := hi.(object.Integer) + if !(loInt && hiInt) { + cmp := vm.send(lo, "<=>", []object.Value{hi}, nil) + if strict && object.IsNil(cmp) && !vm.send(lo, "==", []object.Value{hi}, nil).Truthy() { + raise("ArgumentError", "bad value for range") + } + } + } + return object.NewRange(lo, hi, exclusive) +} + +// coerceRangeStep resolves a Range#step step that is not itself a number to a +// numeric one via MRI's coercion protocol: step.coerce(begin) must return a +// two-element numeric [begin', step'] pair, which replaces the walk's begin and +// step — so (1..3).step(obj), where obj.coerce(1) returns [1, 2], walks 1, 3. A +// numeric step is returned unchanged; a non-numeric step with no #coerce is the +// TypeError MRI raises for a step it cannot convert. +func (vm *VM) coerceRangeStep(loV, stepV object.Value) (object.Value, object.Value) { + if isNumericValue(stepV) { + return loV, stepV + } + if !vm.respondsToDynamic(stepV, "coerce") { + raise("TypeError", "no implicit conversion of %s into Integer", vm.classOf(stepV).name) + } + pair := vm.send(stepV, "coerce", []object.Value{loV}, nil) + arr, ok := pair.(*object.Array) + if !ok || len(arr.Elems) != 2 { + raise("TypeError", "coerce must return [x, y]") + } + return arr.Elems[0], arr.Elems[1] +} diff --git a/internal/vm/range_residuals_wave13_test.go b/internal/vm/range_residuals_wave13_test.go new file mode 100644 index 00000000..82f67967 --- /dev/null +++ b/internal/vm/range_residuals_wave13_test.go @@ -0,0 +1,93 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "strings" + "testing" +) + +// TestRangeConstructionCompare covers vm.newRange — the construction-time +// begin <=> end comparison MRI performs and some specs observe. Verified against +// ruby 4.0.6. +// +// - Range.new / Range#initialize are strict: an unordered pair (#<=> gives nil +// and the bounds are not #==) is a "bad value for range" ArgumentError, while +// a pair that is #== but has no #<=> ordering (two Regexp literals, whose only +// comparison is Object's identity default) still builds — mirroring MRI's +// Object#<=>, which answers 0 for #== objects. +// - The range literal is not strict: it performs the comparison (a mocked #<=> +// is dispatched) but tolerates an unordered result, so a (1.."z") literal +// still builds. +// - Two Integer bounds and a nil bound skip the comparison entirely. +func TestRangeConstructionCompare(t *testing.T) { + cases := []struct{ src, want string }{ + // Strict path (Range.new): a real ordering builds. + {`p Range.new("a", "c").to_a`, `["a", "b", "c"]`}, + // Strict path: two #==-but-unordered bounds (identical Regexps) build, + // because Object#<=> answers 0 for #== objects — the #== fallback. + {`p Range.new(//, //).class`, `Range`}, + {`p Range.new(//, //).begin`, `//`}, + // Strict path: an unordered, non-#== pair is a bad value for range. + {`begin; Range.new(1, Object.new); rescue ArgumentError => e; p e.message; end`, `"bad value for range"`}, + // Range#initialize shares the strict path. + {`class MyR < Range; end +begin; MyR.new(1, Object.new); rescue ArgumentError => e; p e.message; end`, `"bad value for range"`}, + // Two Integer bounds skip the comparison (Fixnum fast path). + {`p (1..3).to_a`, `[1, 2, 3]`}, + // A nil bound skips the comparison (beginless / endless). + {`p (1..).begin`, `1`}, + {`p (..3).end`, `3`}, + // The literal is not strict: an unordered literal still builds and is usable. + {`p (1.."z").exclude_end?`, `false`}, + // The literal performs the #<=> dispatch: a mocked begin sees it. + {`class M + def initialize; @n = 0; end + def hits; @n; end + def <=>(o); @n += 1; 0; end +end +m = M.new +r = (m..m) +p m.hits`, `1`}, + // Two identical Regexp literals build (the literal tolerates the nil #<=>). + {`p (//..//).class`, `Range`}, + } + 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") + } + } +} + +// TestRangeStepCoerce covers vm.coerceRangeStep — MRI 4.0's Range#step coercion of +// a non-numeric step against the range's begin. A numeric step is used as-is; a +// step that answers #coerce is replaced by the numeric [begin', step'] pair it +// returns; a step with no #coerce, or a #coerce that returns something other than +// a two-element pair, is a TypeError. Verified against ruby 4.0.6. +func TestRangeStepCoerce(t *testing.T) { + // Numeric step: used unchanged. + if got := eval(t, `a = []; (1..3).step(2) { |x| a << x }; p a`); got != "[1, 3]\n" { + t.Errorf("numeric step: got %q", got) + } + // A #coerce-able step is coerced against begin: obj.coerce(1) => [1, 2] walks 1, 3. + if got := eval(t, `class C; def coerce(x); [x, 2]; end; end +a = []; (1..3).step(C.new) { |x| a << x }; p a`); got != "[1, 3]\n" { + t.Errorf("coerce step: got %q", got) + } + // A step with no #coerce is a TypeError. + if err := runErr(t, `(1..2).step(Object.new) { |x| x }`); err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("non-coercible step: got err=%v, want TypeError", err) + } + // A #coerce that returns a wrong-length pair is a TypeError. + if err := runErr(t, `class C1; def coerce(x); [1]; end; end +(1..3).step(C1.new) { |x| x }`); err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("coerce wrong length: got err=%v, want TypeError", err) + } + // A #coerce that returns a non-Array is a TypeError. + if err := runErr(t, `class C2; def coerce(x); 5; end; end +(1..3).step(C2.new) { |x| x }`); err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("coerce non-array: got err=%v, want TypeError", err) + } +} diff --git a/internal/vm/vm.go b/internal/vm/vm.go index e0d06c9c..298542e0 100644 --- a/internal/vm/vm.go +++ b/internal/vm/vm.go @@ -1504,7 +1504,7 @@ func (vm *VM) exec(iseq *bytecode.ISeq, self object.Value, args []object.Value, case bytecode.OpNewRange: hi := pop() lo := pop() - push(object.NewRange(lo, hi, in.A == 1)) + push(vm.newRange(lo, hi, in.A == 1, false)) case bytecode.OpPop: pop() case bytecode.OpDup: