diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 76bec168..fb918aa6 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -1885,11 +1885,14 @@ func (vm *VM) bootstrap() { return strEncOf(self, stringSqueeze(strOf(self), args)) }) strIndexFn := func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) < 1 || len(args) > 2 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1..2)", len(args)) + } var res object.Value if re, ok := args[0].(*Regexp); ok { // s[/re/] / s[/re/, group] res = vm.stringRegexpIndex(strOf(self), re, args[1:]) } else { - res = stringIndexEnc(strOf(self), args, self.(*object.String).IsBinary()) + res = stringIndexEnc(strOf(self), vm.coerceStrIndexArgs(args), self.(*object.String).IsBinary()) } if sub, ok := res.(*object.String); ok { // a slice keeps the receiver's encoding sub.Enc = self.(*object.String).Enc @@ -5118,6 +5121,48 @@ func (vm *VM) coerceRangeBounds(r *object.Range) *object.Range { return object.NewRange(lo, hi, r.Exclusive) } +// asRangeValue unwraps v to its underlying *object.Range: directly for a plain +// Range, or via the builtin field for an instance of a user subclass of Range +// (class R < Range; R.new(1,3) is an RObject wrapping a *object.Range). Argument +// values are not builtin-unwrapped by dispatch the way a receiver is, so String#[] +// and friends must unwrap a Range argument themselves. +func asRangeValue(v object.Value) (*object.Range, bool) { + if r, ok := v.(*object.Range); ok { + return r, true + } + if o, ok := v.(*RObject); ok { + if r, ok := o.builtin.(*object.Range); ok { + return r, true + } + } + return nil, false +} + +// coerceStrIndexArgs normalizes the argument(s) of String#[] (and, by delegation, +// Symbol#[]) to the plain values stringIndexEnc expects, applying MRI's implicit +// conversions the raw slice logic does not: a Float or #to_int object index/length +// becomes an Integer (truncated toward zero), and a Range argument — including a +// Range subclass or one with Float/#to_int bounds — becomes a *object.Range with +// Integer bounds. A lone String argument (the substring form) passes through +// untouched. Non-convertible values raise TypeError from repeatLong, matching MRI. +// The caller (strIndexFn) has already validated the 1..2 arity. +func (vm *VM) coerceStrIndexArgs(args []object.Value) []object.Value { + if len(args) == 1 { + if _, ok := args[0].(*object.String); ok { + return args // s[substr] + } + if r, ok := asRangeValue(args[0]); ok { + return []object.Value{vm.coerceRangeBounds(r)} + } + return []object.Value{object.IntValue(vm.repeatLong(args[0]))} + } + // len == 2: (index, length). + return []object.Value{ + object.IntValue(vm.repeatLong(args[0])), + object.IntValue(vm.repeatLong(args[1])), + } +} + // rngKwarg returns the object passed as the random: keyword of a shuffle/sample // call, or nil when absent (then the VM's default generator is used). func (vm *VM) rngKwarg(args []object.Value) object.Value { diff --git a/internal/vm/string_index_coerce_internal_test.go b/internal/vm/string_index_coerce_internal_test.go new file mode 100644 index 00000000..576875d6 --- /dev/null +++ b/internal/vm/string_index_coerce_internal_test.go @@ -0,0 +1,60 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestStringIndexCoerce covers String#[] applying MRI's implicit conversions to +// its index/length/range arguments: a Float index or length truncates toward +// zero, a #to_int object converts, and a Range argument may be a Range subclass +// or carry Float/#to_int bounds. A lone String argument (the substring form) and +// the plain Integer/Regexp forms are unaffected. The 2-arg (index, length) form +// with a non-convertible argument raises TypeError, as does a Range passed where +// an index is expected. Symbol#[] inherits every case by delegation. Verified +// against ruby 4.0.6. +func TestStringIndexCoerce(t *testing.T) { + cases := []struct{ src, want string }{ + // Float index / length truncate toward zero. + {`p "hello"[1.5]`, `"e"`}, + {`p "hello"[-1.9]`, `"o"`}, + {`p "hello"[1.5, 2.9]`, `"el"`}, + {`p "hello"[1.0, 3.0]`, `"ell"`}, + // #to_int object as index / length. + {`class I; def to_int; 2; end; end; p "hello"[I.new]`, `"l"`}, + {`class I; def to_int; 1; end; end; p "hello"[I.new, I.new]`, `"e"`}, + // Range with Float bounds. + {`p "hello"[1.0..3.0]`, `"ell"`}, + {`p "hello"[1.5..3.9]`, `"ell"`}, + {`p "hello"[(1.5)..]`, `"ello"`}, + {`p "hello"[..2.9]`, `"hel"`}, + {`p "hello"[1.0...3.0]`, `"el"`}, + // Range subclass argument (an RObject wrapping *object.Range). + {`class R < Range; end; p "hello"[R.new(1, 3)]`, `"ell"`}, + {`class R < Range; end; p "hello"[R.new(1, 3, true)]`, `"el"`}, + // Plain forms are unchanged. + {`p "hello"[1]`, `"e"`}, + {`p "hello"[1, 3]`, `"ell"`}, + {`p "hello"[1..3]`, `"ell"`}, + {`p "hello"["ell"]`, `"ell"`}, + {`p "hello"["xyz"]`, `nil`}, + {`p "hello"[/l+/]`, `"ll"`}, + // Non-convertible arguments raise TypeError. + {`begin; "hello"[Object.new]; rescue TypeError => e; p e.class; end`, `TypeError`}, + {`begin; "hello"["e", 2]; rescue TypeError => e; p e.class; end`, `TypeError`}, + {`begin; "hello"[(1..2), 3]; rescue TypeError => e; p e.class; end`, `TypeError`}, + // Wrong arity raises ArgumentError, for every form (1..2 args). + {`begin; "hello"[1, 2, 3]; rescue ArgumentError => e; p e.class; end`, `ArgumentError`}, + {`begin; "hello"[/l/, 0, 9]; rescue ArgumentError => e; p e.class; end`, `ArgumentError`}, + // Symbol#[] inherits the coercion by delegation. + {`p :hello[1.5]`, `"e"`}, + {`p :hello[1.0..3.0]`, `"ell"`}, + {`class I; def to_int; 2; end; end; p :hello[I.new]`, `"l"`}, + } + 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") + } + } +}