Skip to content

Commit 193afdb

Browse files
committed
Fix recursive sequence repetition fallback
Assisted-by: Claude Code:claude-opus-5-5 Assisted-by: Codex:GPT-6
1 parent f871707 commit 193afdb

4 files changed

Lines changed: 235 additions & 55 deletions

File tree

‎crates/vm/src/protocol/sequence.rs‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,12 @@ impl PySequence<'_> {
227227

228228
// if both arguments appear to be sequences, try fallback to __iadd__
229229
if self.check() && other.sequence_unchecked().check() {
230-
let ret = vm._iadd(self.obj, other)?;
230+
let ret = vm.binary_iop1(
231+
self.obj,
232+
other,
233+
PyNumberBinaryOp::InplaceAdd,
234+
PyNumberBinaryOp::Add,
235+
)?;
231236
if let PyArithmeticValue::Implemented(ret) = PyArithmeticValue::from_object(vm, ret) {
232237
return Ok(ret);
233238
}
@@ -249,7 +254,12 @@ impl PySequence<'_> {
249254
}
250255

251256
if self.check() {
252-
let ret = vm._imul(self.obj, &n.to_pyobject(vm))?;
257+
let ret = vm.binary_iop1(
258+
self.obj,
259+
&n.to_pyobject(vm),
260+
PyNumberBinaryOp::InplaceMultiply,
261+
PyNumberBinaryOp::Multiply,
262+
)?;
253263
if let PyArithmeticValue::Implemented(ret) = PyArithmeticValue::from_object(vm, ret) {
254264
return Ok(ret);
255265
}
@@ -504,6 +514,34 @@ mod tests {
504514
}
505515
}
506516

517+
#[test]
518+
fn unsupported_inplace_operations_keep_sequence_errors() {
519+
Interpreter::without_stdlib(Default::default()).enter(|vm| {
520+
let range = PyRange {
521+
start: vm.ctx.new_int(0),
522+
stop: vm.ctx.new_int(3),
523+
step: vm.ctx.new_int(1),
524+
}
525+
.into_ref(&vm.ctx);
526+
let sequence = range.as_object().sequence_unchecked();
527+
for (result, message) in [
528+
(
529+
sequence.inplace_repeat(2, vm),
530+
"'range' object can't be repeated",
531+
),
532+
(
533+
sequence.inplace_concat(range.as_object(), vm),
534+
"'range' object can't be concatenated",
535+
),
536+
] {
537+
let error = result.unwrap_err();
538+
assert!(error.fast_isinstance(vm.ctx.exceptions.type_error));
539+
let actual: String = error.args().as_slice()[0].try_to_value(vm).unwrap();
540+
assert_eq!(actual, message);
541+
}
542+
});
543+
}
544+
507545
#[test]
508546
fn conversion_and_partial_result_cleanup() {
509547
Interpreter::without_stdlib(Default::default()).enter(|vm| {

‎crates/vm/src/types/slot.rs‎

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -492,16 +492,6 @@ fn sequence_contains_wrapper(
492492
contains_wrapper(seq.obj, needle, vm)
493493
}
494494

495-
#[inline(never)]
496-
fn sequence_repeat_wrapper(seq: PySequence<'_>, n: isize, vm: &VirtualMachine) -> PyResult {
497-
vm.call_special_method(seq.obj, identifier!(vm, __mul__), (n,))
498-
}
499-
500-
#[inline(never)]
501-
fn sequence_inplace_repeat_wrapper(seq: PySequence<'_>, n: isize, vm: &VirtualMachine) -> PyResult {
502-
vm.call_special_method(seq.obj, identifier!(vm, __imul__), (n,))
503-
}
504-
505495
fn repr_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> {
506496
let ret = vm.call_special_method(zelf, identifier!(vm, __repr__), ())?;
507497
ret.downcast::<PyStr>().map_err(|obj| {
@@ -1581,16 +1571,38 @@ impl PyType {
15811571
// (handled by number protocol fallback)
15821572
accessor.inherit_from_mro(self);
15831573
}
1584-
SlotAccessor::SqRepeat => {
1585-
update_sub_slot!(as_sequence, repeat, sequence_repeat_wrapper, SeqRepeat)
1586-
}
1587-
SlotAccessor::SqInplaceRepeat => {
1588-
update_sub_slot!(
1589-
as_sequence,
1590-
inplace_repeat,
1591-
sequence_inplace_repeat_wrapper,
1592-
SeqRepeat
1593-
)
1574+
SlotAccessor::SqRepeat | SlotAccessor::SqInplaceRepeat => {
1575+
// Python `__mul__`/`__rmul__`/`__imul__` overrides use the number slots and
1576+
// leave no sequence repeat, as with `sq_concat`.
1577+
let (names, field) = if matches!(accessor, SlotAccessor::SqRepeat) {
1578+
(
1579+
&[identifier!(ctx, __mul__), identifier!(ctx, __rmul__)][..],
1580+
&self.slots.as_sequence.repeat,
1581+
)
1582+
} else {
1583+
(
1584+
&[identifier!(ctx, __imul__)][..],
1585+
&self.slots.as_sequence.inplace_repeat,
1586+
)
1587+
};
1588+
let mut repeat = None;
1589+
for &name in names {
1590+
match self.lookup_slot_in_mro(name, ctx, |sf| {
1591+
if let SlotFunc::SeqRepeat(f) = sf {
1592+
Some(*f)
1593+
} else {
1594+
None
1595+
}
1596+
}) {
1597+
SlotLookupResult::NativeSlot(func) => repeat = repeat.or(Some(func)),
1598+
SlotLookupResult::PythonMethod => {
1599+
repeat = None;
1600+
break;
1601+
}
1602+
SlotLookupResult::NotFound => {}
1603+
}
1604+
}
1605+
field.store(repeat);
15941606
}
15951607
SlotAccessor::SqItem => {
15961608
update_sub_slot!(as_sequence, item, sequence_getitem_wrapper, SeqItem)

‎crates/vm/src/vm/vm_ops.rs‎

Lines changed: 45 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::{
44
Py, PyRef,
55
builtins::{PyInt, PyStr, PyStrInterned, PyStrRef, PyType, PyUtf8Str},
66
object::{AsObject, PyObject, PyObjectRef, PyResult},
7-
protocol::{PyNumberBinaryOp, PyNumberSlots, PyNumberTernaryOp, PyNumberUnaryFunc},
7+
protocol::{PyNumberBinaryOp, PyNumberSlots, PyNumberTernaryOp, PyNumberUnaryFunc, PySequence},
88
types::PyComparisonOp,
99
};
1010
use num_traits::ToPrimitive;
@@ -285,7 +285,7 @@ impl VirtualMachine {
285285
///
286286
/// - Otherwise, in-place modification is not supported. Handle it exactly as
287287
/// a non in-place operation of the same kind.
288-
fn binary_iop1(
288+
pub(crate) fn binary_iop1(
289289
&self,
290290
a: &PyObject,
291291
b: &PyObject,
@@ -492,20 +492,11 @@ impl VirtualMachine {
492492
if !result.is(&self.ctx.not_implemented) {
493493
return Ok(result);
494494
}
495-
if let Ok(seq_a) = a.try_sequence(self) {
496-
let n = b
497-
.try_index(self)?
498-
.as_bigint()
499-
.to_isize()
500-
.ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?;
501-
return seq_a.repeat(n, self);
502-
} else if let Ok(seq_b) = b.try_sequence(self) {
503-
let n = a
504-
.try_index(self)?
505-
.as_bigint()
506-
.to_isize()
507-
.ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?;
508-
return seq_b.repeat(n, self);
495+
if let Some(f) = a.sequence_unchecked().slots().repeat.load() {
496+
return self.sequence_repeat(f, a, b);
497+
}
498+
if let Some(f) = b.sequence_unchecked().slots().repeat.load() {
499+
return self.sequence_repeat(f, b, a);
509500
}
510501
Err(self.new_unsupported_bin_op_error(a, b, "*"))
511502
}
@@ -520,27 +511,48 @@ impl VirtualMachine {
520511
if !result.is(&self.ctx.not_implemented) {
521512
return Ok(result);
522513
}
523-
if let Ok(seq_a) = a.try_sequence(self) {
524-
let n = b
525-
.try_index(self)?
526-
.as_bigint()
527-
.to_isize()
528-
.ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?;
529-
return seq_a.inplace_repeat(n, self);
530-
} else if let Ok(seq_b) = b.try_sequence(self) {
531-
let n = a
532-
.try_index(self)?
533-
.as_bigint()
534-
.to_isize()
535-
.ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?;
536-
/* Note that the right hand operand should not be
537-
* mutated in this case so inplace_repeat is not
538-
* used. */
539-
return seq_b.repeat(n, self);
514+
let a_seq = a.sequence_unchecked();
515+
let a_slots = a_seq.slots();
516+
if let Some(f) = a_slots
517+
.inplace_repeat
518+
.load()
519+
.or_else(|| a_slots.repeat.load())
520+
{
521+
return self.sequence_repeat(f, a, b);
522+
}
523+
// The right operand is only tried when the left type has no sequence table at all,
524+
// and every heap type has one. It is repeated, never mutated in place.
525+
if !a_slots.has_any()
526+
&& a.class().heaptype_ext().is_none()
527+
&& let Some(f) = b.sequence_unchecked().slots().repeat.load()
528+
{
529+
return self.sequence_repeat(f, b, a);
540530
}
541531
Err(self.new_unsupported_bin_op_error(a, b, "*="))
542532
}
543533

534+
// sequence_repeat in CPython
535+
fn sequence_repeat(
536+
&self,
537+
repeat: fn(PySequence<'_>, isize, &Self) -> PyResult,
538+
seq: &PyObject,
539+
n: &PyObject,
540+
) -> PyResult {
541+
let index = n.try_index_opt(self).ok_or_else(|| {
542+
self.new_type_error(format!(
543+
"can't multiply sequence by non-int of type '{}'",
544+
n.class().slot_name()
545+
))
546+
})??;
547+
let count = index.as_bigint().to_isize().ok_or_else(|| {
548+
self.new_overflow_error(format!(
549+
"cannot fit '{}' into an index-sized integer",
550+
n.class().slot_name()
551+
))
552+
})?;
553+
repeat(seq.sequence_unchecked(), count, self)
554+
}
555+
544556
fn unary_op(
545557
&self,
546558
a: &PyObject,

‎extra_tests/snippets/operator_arithmetic.py‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from operator import imul, mul
2+
13
from testutils import assert_raises
24

35
assert -3 // 2 == -2
@@ -52,3 +54,119 @@
5254
assert_raises(TypeError, lambda: 1.5 | True)
5355
assert_raises(TypeError, lambda: 1.5 & True)
5456
assert_raises(TypeError, lambda: 1.5 ^ True)
57+
58+
59+
def check_repeat_error(error, message, operation, *args):
60+
with assert_raises(error) as caught:
61+
operation(*args)
62+
assert str(caught.exception) == message, str(caught.exception)
63+
64+
65+
class GetItemOnly:
66+
def __getitem__(self, index):
67+
raise IndexError
68+
69+
70+
# An item slot does not imply support for repetition.
71+
for value in (range(3), GetItemOnly()):
72+
name = type(value).__name__
73+
for operation, symbol in ((mul, "*"), (imul, "*=")):
74+
check_repeat_error(
75+
TypeError,
76+
f"unsupported operand type(s) for {symbol}: '{name}' and 'int'",
77+
operation,
78+
value,
79+
2,
80+
)
81+
check_repeat_error(
82+
TypeError,
83+
f"unsupported operand type(s) for *: 'int' and '{name}'",
84+
mul,
85+
2,
86+
value,
87+
)
88+
89+
90+
# Native sequence slots use the same count conversion in both directions.
91+
for value in ([1], (1,), "a", b"a", bytearray(b"a")):
92+
for operation in (mul, lambda seq, count: count * seq, imul):
93+
for count, error, message in (
94+
(1.5, TypeError, "can't multiply sequence by non-int of type 'float'"),
95+
(2**100, OverflowError, "cannot fit 'int' into an index-sized integer"),
96+
):
97+
check_repeat_error(error, message, operation, value, count)
98+
99+
100+
class RepeatIndex:
101+
def __init__(self, value):
102+
self.value = value
103+
104+
def __index__(self):
105+
return self.value
106+
107+
108+
assert RepeatIndex(2) * [1] == [1, 1]
109+
assert imul(2, [1]) == [1, 1]
110+
check_repeat_error(
111+
TypeError,
112+
"unsupported operand type(s) for *=: 'RepeatIndex' and 'list'",
113+
imul,
114+
RepeatIndex(2),
115+
[1],
116+
)
117+
check_repeat_error(
118+
OverflowError,
119+
"cannot fit 'RepeatIndex' into an index-sized integer",
120+
mul,
121+
"a",
122+
RepeatIndex(-(2**100)),
123+
)
124+
125+
126+
class DeclineRepeat(GetItemOnly):
127+
calls = []
128+
129+
def __mul__(self, other):
130+
self.calls.append("mul")
131+
return NotImplemented
132+
133+
def __rmul__(self, other):
134+
self.calls.append("rmul")
135+
return NotImplemented
136+
137+
def __imul__(self, other):
138+
self.calls.append("imul")
139+
return NotImplemented
140+
141+
142+
# Numeric fallback must not invoke the same Python method through a sequence slot.
143+
declining = DeclineRepeat()
144+
for operation, args, expected in (
145+
(mul, (declining, 2), ["mul"]),
146+
(mul, (2, declining), ["rmul"]),
147+
(imul, (declining, 2), ["imul", "mul"]),
148+
):
149+
DeclineRepeat.calls.clear()
150+
assert_raises(TypeError, operation, *args)
151+
assert DeclineRepeat.calls == expected
152+
153+
154+
class RepeatList(list):
155+
pass
156+
157+
158+
class RepeatInt(int):
159+
pass
160+
161+
162+
assert "a" * RepeatInt(2) == RepeatInt(2) * "a" == "aa"
163+
for method, operation in (
164+
("__mul__", lambda value: value * 2),
165+
("__rmul__", lambda value: 2 * value),
166+
):
167+
value = RepeatList([1])
168+
assert operation(value) == [1, 1]
169+
setattr(RepeatList, method, lambda self, other: NotImplemented)
170+
assert_raises(TypeError, operation, value)
171+
delattr(RepeatList, method)
172+
assert operation(value) == [1, 1]

0 commit comments

Comments
 (0)