From ce84dd1a2f1d02b301687b627e034cfc53161df7 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Tue, 10 Nov 2026 22:43:57 +0500 Subject: [PATCH 1/2] [mypyc] Fix crash when iterating over bytearray Iterating over a bytearray in a for loop or a comprehension crashed with an internal error, since the item type of bytearray wasn't known. Use the iterator protocol for bytearray, like CPython. This is faster than the generic __getitem__, ignores __len__ and __getitem__ overrides in subclasses, and supports changing the length while iterating. Also use int as the item type of bytes instead of bytes, which avoids boxing and unboxing each item. --- mypyc/irbuild/builder.py | 4 +- mypyc/irbuild/for_helpers.py | 16 +++- mypyc/test-data/fixtures/ir.py | 2 + mypyc/test-data/irbuild-bytes.test | 109 +++++++++++++++++++++++++ mypyc/test-data/irbuild-lists.test | 66 +++++++-------- mypyc/test-data/irbuild-tuple.test | 66 +++++++-------- mypyc/test-data/run-bytes.test | 125 +++++++++++++++++++++++++++++ 7 files changed, 305 insertions(+), 83 deletions(-) diff --git a/mypyc/irbuild/builder.py b/mypyc/irbuild/builder.py index 389e2cec4c2b4..409fe4a0501dc 100644 --- a/mypyc/irbuild/builder.py +++ b/mypyc/irbuild/builder.py @@ -119,7 +119,6 @@ RVec, bitmap_rprimitive, bool_rprimitive, - bytes_rprimitive, c_pointer_rprimitive, c_pyssize_t_rprimitive, dict_rprimitive, @@ -1159,7 +1158,8 @@ def get_sequence_type_from_type(self, target_type: Type) -> RType: if target_type.type.fullname == "builtins.str": return str_rprimitive elif target_type.type.fullname == "builtins.bytes": - return bytes_rprimitive + # Items of bytes objects are ints + return int_rprimitive try: return self.type_to_rtype(target_type.args[0]) except IndexError: diff --git a/mypyc/irbuild/for_helpers.py b/mypyc/irbuild/for_helpers.py index a2d50e81a32e5..07ecad7357cb2 100644 --- a/mypyc/irbuild/for_helpers.py +++ b/mypyc/irbuild/for_helpers.py @@ -66,6 +66,7 @@ c_pyssize_t_rprimitive, int_rprimitive, is_bool_or_bit_rprimitive, + is_bytearray_rprimitive, is_dict_rprimitive, is_fixed_width_rtype, is_immutable_rprimitive, @@ -257,7 +258,16 @@ def can_preallocate_from_generator(builder: IRBuilder, gen: GeneratorExpr) -> bo if isinstance(rtype, RTuple): # for_loop_helper_with_index crashes for empty tuples return bool(rtype.types) - return is_sequence_rprimitive(rtype) or isinstance(rtype, RVec) + return is_indexed_sequence_rprimitive(rtype) or isinstance(rtype, RVec) + + +def is_indexed_sequence_rprimitive(rtype: RType) -> bool: + """Do we iterate over a primitive sequence by index, instead of using an iterator? + + We use an iterator for bytearray, since there is no fast unsafe item access for it, + and since overrides of __len__ and __getitem__ in a subclass must not be used. + """ + return is_sequence_rprimitive(rtype) and not is_bytearray_rprimitive(rtype) def sequence_from_generator_preallocate_helper( @@ -722,7 +732,7 @@ def make_for_loop_generator( return async_obj rtyp = builder.node_type(expr) - if is_sequence_rprimitive(rtyp) or isinstance(rtyp, RVec): + if is_indexed_sequence_rprimitive(rtyp) or isinstance(rtyp, RVec): # Special case "for x in " for concrete sequence types. expr_reg = accept_loop_state(builder, expr, reassigned) target_type = builder.get_sequence_type(expr) @@ -801,7 +811,7 @@ def make_for_loop_generator( expr.callee.fullname == "builtins.reversed" and len(expr.args) == 1 and expr.arg_kinds == [ARG_POS] - and is_sequence_rprimitive(builder.node_type(expr.args[0])) + and is_indexed_sequence_rprimitive(builder.node_type(expr.args[0])) ): # Special case "for x in reversed()". expr_reg = accept_loop_state(builder, expr.args[0], reassigned) diff --git a/mypyc/test-data/fixtures/ir.py b/mypyc/test-data/fixtures/ir.py index 768519a47f4fe..423bfcdb4c7b0 100644 --- a/mypyc/test-data/fixtures/ir.py +++ b/mypyc/test-data/fixtures/ir.py @@ -219,6 +219,8 @@ def decode(self, x: str = ..., y: str = ...) -> str: ... def join(self, x: Iterable[object]) -> bytes: ... def startswith(self, t: bytes) -> bool: ... def endswith(self, t: bytes) -> bool: ... + def append(self, x: int) -> None: ... + def clear(self) -> None: ... def __iter__(self) -> Iterator[int]: ... class memoryview: diff --git a/mypyc/test-data/irbuild-bytes.test b/mypyc/test-data/irbuild-bytes.test index 9f9d14c291b15..15fa9baa0d94f 100644 --- a/mypyc/test-data/irbuild-bytes.test +++ b/mypyc/test-data/irbuild-bytes.test @@ -399,3 +399,112 @@ def foo(b: bytes, ba: bytearray) -> None: [out] main:7: error: Argument 1 to "bytes_func" has incompatible type "bytearray"; expected "bytes" main:8: error: Argument 1 to "bytearray_func" has incompatible type "bytes"; expected "bytearray" + +[case testBytesFor] +def f(b: bytes) -> int: + t = 0 + for c in b: + t += c + return t +[out] +def f(b): + b :: bytes + t :: int + r0, r1 :: native_int + r2, r3, r4 :: bit + r5, r6, r7, r8, c, r9 :: int + r10 :: native_int +L0: + t = 0 + r0 = var_object_size b + r1 = 0 +L1: + r2 = r1 < r0 :: signed + if r2 goto L2 else goto L8 :: bool +L2: + r3 = r1 <= 4611686018427387903 :: signed + if r3 goto L3 else goto L4 :: bool +L3: + r4 = r1 >= -4611686018427387904 :: signed + if r4 goto L5 else goto L4 :: bool +L4: + r5 = CPyTagged_FromInt64(r1) + r6 = r5 + goto L6 +L5: + r7 = r1 << 1 + r6 = r7 +L6: + r8 = CPyBytes_GetItem(b, r6) + c = r8 + r9 = CPyTagged_Add(t, c) + t = r9 +L7: + r10 = r1 + 1 + r1 = r10 + goto L1 +L8: + return t + +[case testBytearrayFor] +def f(b: bytearray) -> int: + t = 0 + for c in b: + t += c + return t +[out] +def f(b): + b :: bytearray + t :: int + r0, r1 :: object + r2, c, r3 :: int + r4 :: bit +L0: + t = 0 + r0 = PyObject_GetIter(b) +L1: + r1 = PyIter_Next(r0) + if is_error(r1) goto L4 else goto L2 +L2: + r2 = unbox(int, r1) + c = r2 + r3 = CPyTagged_Add(t, c) + t = r3 +L3: + goto L1 +L4: + r4 = CPy_NoErrOccurred() +L5: + return t + +[case testBytearrayComprehension] +def f(b: bytearray) -> list[int]: + return [c + 1 for c in b] +[out] +def f(b): + b :: bytearray + r0 :: list + r1, r2 :: object + r3, c, r4 :: int + r5 :: object + r6 :: i32 + r7, r8 :: bit +L0: + r0 = PyList_New(0) + r1 = PyObject_GetIter(b) +L1: + r2 = PyIter_Next(r1) + if is_error(r2) goto L4 else goto L2 +L2: + r3 = unbox(int, r2) + c = r3 + r4 = CPyTagged_Add(c, 2) + r5 = box(int, r4) + r6 = PyList_Append(r0, r5) + r7 = r6 >= 0 :: signed +L3: + goto L1 +L4: + r8 = CPy_NoErrOccurred() +L5: + return r0 diff --git a/mypyc/test-data/irbuild-lists.test b/mypyc/test-data/irbuild-lists.test index 9587ae1c41e6a..bbcf82470dd5a 100644 --- a/mypyc/test-data/irbuild-lists.test +++ b/mypyc/test-data/irbuild-lists.test @@ -785,11 +785,9 @@ def test(): r2 :: list r3 :: native_int r4, r5, r6 :: bit - r7, r8, r9, r10 :: int - r11 :: object - r12, x, r13 :: int - r14 :: object - r15 :: native_int + r7, r8, r9, r10, x, r11 :: int + r12 :: object + r13 :: native_int a :: list L0: r0 = b'abc' @@ -815,15 +813,13 @@ L5: r8 = r9 L6: r10 = CPyBytes_GetItem(source, r8) - r11 = box(int, r10) - r12 = unbox(int, r11) - x = r12 - r13 = f2(x) - r14 = box(int, r13) - CPyList_SetItemUnsafe(r2, r3, r14) + x = r10 + r11 = f2(x) + r12 = box(int, r11) + CPyList_SetItemUnsafe(r2, r3, r12) L7: - r15 = r3 + 1 - r3 = r15 + r13 = r3 + 1 + r3 = r13 goto L1 L8: a = r2 @@ -847,11 +843,9 @@ def test(): r1 :: list r2 :: native_int r3, r4, r5 :: bit - r6, r7, r8, r9 :: int - r10 :: object - r11, x, r12 :: int - r13 :: object - r14 :: native_int + r6, r7, r8, r9, x, r10 :: int + r11 :: object + r12 :: native_int a :: list L0: r0 = b'abc' @@ -876,15 +870,13 @@ L5: r7 = r8 L6: r9 = CPyBytes_GetItem(r0, r7) - r10 = box(int, r9) - r11 = unbox(int, r10) - x = r11 - r12 = f2(x) - r13 = box(int, r12) - CPyList_SetItemUnsafe(r1, r2, r13) + x = r9 + r10 = f2(x) + r11 = box(int, r10) + CPyList_SetItemUnsafe(r1, r2, r11) L7: - r14 = r2 + 1 - r2 = r14 + r12 = r2 + 1 + r2 = r12 goto L1 L8: a = r1 @@ -914,11 +906,9 @@ def test(): r3 :: list r4 :: native_int r5, r6, r7 :: bit - r8, r9, r10, r11 :: int - r12 :: object - r13, x, r14 :: int - r15 :: object - r16 :: native_int + r8, r9, r10, r11, x, r12 :: int + r13 :: object + r14 :: native_int a :: list L0: r0 = __main__.source :: static @@ -948,15 +938,13 @@ L7: r9 = r10 L8: r11 = CPyBytes_GetItem(r0, r9) - r12 = box(int, r11) - r13 = unbox(int, r12) - x = r13 - r14 = f2(x) - r15 = box(int, r14) - CPyList_SetItemUnsafe(r3, r4, r15) + x = r11 + r12 = f2(x) + r13 = box(int, r12) + CPyList_SetItemUnsafe(r3, r4, r13) L9: - r16 = r4 + 1 - r4 = r16 + r14 = r4 + 1 + r4 = r14 goto L3 L10: a = r3 diff --git a/mypyc/test-data/irbuild-tuple.test b/mypyc/test-data/irbuild-tuple.test index 56a57b04a6b07..652b7ae9b33b4 100644 --- a/mypyc/test-data/irbuild-tuple.test +++ b/mypyc/test-data/irbuild-tuple.test @@ -548,11 +548,9 @@ def test(): r2 :: tuple r3 :: native_int r4, r5, r6 :: bit - r7, r8, r9, r10 :: int - r11 :: object - r12, x, r13 :: int - r14 :: object - r15 :: native_int + r7, r8, r9, r10, x, r11 :: int + r12 :: object + r13 :: native_int a :: tuple L0: r0 = b'abc' @@ -578,15 +576,13 @@ L5: r8 = r9 L6: r10 = CPyBytes_GetItem(source, r8) - r11 = box(int, r10) - r12 = unbox(int, r11) - x = r12 - r13 = f2(x) - r14 = box(int, r13) - CPySequenceTuple_SetItemUnsafe(r2, r3, r14) + x = r10 + r11 = f2(x) + r12 = box(int, r11) + CPySequenceTuple_SetItemUnsafe(r2, r3, r12) L7: - r15 = r3 + 1 - r3 = r15 + r13 = r3 + 1 + r3 = r13 goto L1 L8: a = r2 @@ -610,11 +606,9 @@ def test(): r1 :: tuple r2 :: native_int r3, r4, r5 :: bit - r6, r7, r8, r9 :: int - r10 :: object - r11, x, r12 :: int - r13 :: object - r14 :: native_int + r6, r7, r8, r9, x, r10 :: int + r11 :: object + r12 :: native_int a :: tuple L0: r0 = b'abc' @@ -639,15 +633,13 @@ L5: r7 = r8 L6: r9 = CPyBytes_GetItem(r0, r7) - r10 = box(int, r9) - r11 = unbox(int, r10) - x = r11 - r12 = f2(x) - r13 = box(int, r12) - CPySequenceTuple_SetItemUnsafe(r1, r2, r13) + x = r9 + r10 = f2(x) + r11 = box(int, r10) + CPySequenceTuple_SetItemUnsafe(r1, r2, r11) L7: - r14 = r2 + 1 - r2 = r14 + r12 = r2 + 1 + r2 = r12 goto L1 L8: a = r1 @@ -677,11 +669,9 @@ def test(): r3 :: tuple r4 :: native_int r5, r6, r7 :: bit - r8, r9, r10, r11 :: int - r12 :: object - r13, x, r14 :: int - r15 :: object - r16 :: native_int + r8, r9, r10, r11, x, r12 :: int + r13 :: object + r14 :: native_int a :: tuple L0: r0 = __main__.source :: static @@ -711,15 +701,13 @@ L7: r9 = r10 L8: r11 = CPyBytes_GetItem(r0, r9) - r12 = box(int, r11) - r13 = unbox(int, r12) - x = r13 - r14 = f2(x) - r15 = box(int, r14) - CPySequenceTuple_SetItemUnsafe(r3, r4, r15) + x = r11 + r12 = f2(x) + r13 = box(int, r12) + CPySequenceTuple_SetItemUnsafe(r3, r4, r13) L9: - r16 = r4 + 1 - r4 = r16 + r14 = r4 + 1 + r4 = r14 goto L3 L10: a = r3 diff --git a/mypyc/test-data/run-bytes.test b/mypyc/test-data/run-bytes.test index c26ae9142bd0d..10a374d35973f 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -567,6 +567,131 @@ def test_bytearray_indexing() -> None: with assertRaises(ValueError, "byte must be in range(0, 256)"): b2[0] = 256 +[case testBytesIteration] +from typing import Iterator + +def loop(b: bytes) -> list[int]: + a = [] + for c in b: + a.append(c) + return a + +def comprehension(b: bytes) -> list[int]: + return [c for c in b] + +def test_bytes() -> None: + for b in [b'', b'a', b'\x00\x80\xff', bytes(range(256))]: + assert loop(b) == list(b) + assert comprehension(b) == list(b) + +def test_bytes_subclass() -> None: + from bytessub import BytesSubclass + b = BytesSubclass(b'ab') + assert loop(b) == [97, 98] + assert comprehension(b) == [97, 98] + +[file bytessub.py] +class BytesSubclass(bytes): + pass + +[case testBytearrayIteration] +from typing import Iterator + +def loop(b: bytearray) -> list[int]: + a = [] + for c in b: + a.append(c) + return a + +def comprehension(b: bytearray) -> list[int]: + return [c + 1 for c in b] + +def gen_expr(b: bytearray) -> tuple[int, ...]: + return tuple(c * 2 for c in b) + +def set_comprehension(b: bytearray) -> set[int]: + return {c for c in b} + +def enum(b: bytearray) -> list[tuple[int, int]]: + return [(i, c) for i, c in enumerate(b)] + +def zipped(b: bytearray, s: str) -> list[tuple[int, str]]: + return [(c, x) for c, x in zip(b, s)] + +def generator(b: bytearray) -> Iterator[int]: + for c in b: + yield c + +def test_basic() -> None: + for b in [bytearray(), bytearray(b'a'), bytearray(b'\x00\x80\xff'), bytearray(range(256))]: + assert loop(b) == list(b) + assert comprehension(b) == [c + 1 for c in list(b)] + assert gen_expr(b) == tuple(c * 2 for c in list(b)) + assert set_comprehension(b) == set(list(b)) + assert enum(b) == list(enumerate(list(b))) + assert zipped(b, 'xyz') == list(zip(list(b), 'xyz')) + assert list(generator(b)) == list(b) + +def grow(b: bytearray) -> list[int]: + a = [] + for c in b: + if len(b) < 5: + b.append(c + 10) + a.append(c) + return a + +def grow_comprehension(b: bytearray) -> list[int]: + return [append_if_short(b, c) for c in b] + +def append_if_short(b: bytearray, c: int) -> int: + if len(b) < 5: + b.append(c + 10) + return c + +def shrink(b: bytearray) -> list[int]: + a = [] + for c in b: + b.clear() + a.append(c) + return a + +def shrink_comprehension(b: bytearray) -> list[int]: + return [clear(b, c) for c in b] + +def clear(b: bytearray, c: int) -> int: + b.clear() + return c + +def test_modify_while_iterating() -> None: + assert grow(bytearray(b'\x01\x02')) == [1, 2, 11, 12, 21] + assert grow_comprehension(bytearray(b'\x01\x02')) == [1, 2, 11, 12, 21] + assert shrink(bytearray(b'\x01\x02')) == [1] + assert shrink_comprehension(bytearray(b'\x01\x02')) == [1] + +def test_subclass() -> None: + from bytearraysub import ByteArrayOverride, ByteArrayIterOverride + # Like CPython, ignore __len__ and __getitem__ overrides + b = ByteArrayOverride(b'ab') + assert loop(b) == [97, 98] + assert comprehension(b) == [98, 99] + b2 = ByteArrayIterOverride(b'ab') + assert loop(b2) == [42] + assert comprehension(b2) == [43] + +[file bytearraysub.py] +from typing import Iterator + +class ByteArrayOverride(bytearray): + def __len__(self) -> int: + return 1 + + def __getitem__(self, i: object) -> int: # type: ignore[override] + return 99 + +class ByteArrayIterOverride(bytearray): + def __iter__(self) -> Iterator[int]: + yield 42 + [case testBytesJoin] from typing import Any from testutil import assertRaises From c6208e5002017207dcb90d7ad4f4d100f2926058 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Tue, 10 Nov 2026 23:59:57 +0500 Subject: [PATCH 2/2] Only run the bytes for loop IR test on 64-bit platforms --- mypyc/test-data/irbuild-bytes.test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypyc/test-data/irbuild-bytes.test b/mypyc/test-data/irbuild-bytes.test index 15fa9baa0d94f..a00a913e1a4b6 100644 --- a/mypyc/test-data/irbuild-bytes.test +++ b/mypyc/test-data/irbuild-bytes.test @@ -400,7 +400,7 @@ def foo(b: bytes, ba: bytearray) -> None: main:7: error: Argument 1 to "bytes_func" has incompatible type "bytearray"; expected "bytes" main:8: error: Argument 1 to "bytearray_func" has incompatible type "bytes"; expected "bytearray" -[case testBytesFor] +[case testBytesFor_64bit] def f(b: bytes) -> int: t = 0 for c in b: