Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions internal/object/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
6 changes: 6 additions & 0 deletions internal/vm/arith.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,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.
Expand Down
136 changes: 111 additions & 25 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -4371,6 +4371,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]))
Expand Down Expand Up @@ -4474,8 +4496,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)
Expand Down Expand Up @@ -4616,40 +4644,51 @@ 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
// every step-th element of the begin..end succ-walk. An endless String
// 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.
Expand All @@ -4660,6 +4699,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
Expand Down Expand Up @@ -8253,7 +8303,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; ; {
Expand All @@ -8280,6 +8332,40 @@ 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 {
// 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
}
} 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)))
Expand Down
21 changes: 21 additions & 0 deletions internal/vm/enumerator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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 {
Expand Down
39 changes: 36 additions & 3 deletions internal/vm/prelude.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -1028,6 +1035,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
Expand Down
Loading