From a45064e02349a9baee70af93c54a354ddc129443 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 16:21:56 +0500 Subject: [PATCH 1/3] [mypyc] Fix comprehensions over lists that are modified while iterating A comprehension over a list, such as [f(x) for x in a], preallocates the result using the initial length of the list, but the loop checks the current length of the list on each iteration. If the list grew during the loop (e.g. in f, or in another thread), items were written past the end of the result (heap overflow). If it shrank, the result had NULL items at the end, which caused crashes later. This affected list comprehensions, list(), tuple(), sorted() and str.join() with a generator expression argument, and vec comprehensions. Keep the preallocation, but append items that don't fit in the preallocated result, and reduce the length of the result after the loop if the list shrank. This matches CPython, which includes all items it sees. A tuple can't be resized, so tuple() over a list now builds a list first, like other generator sources. --- mypyc/irbuild/for_helpers.py | 116 +++++++++++++++++++++++--- mypyc/irbuild/specialize.py | 5 +- mypyc/irbuild/vec.py | 12 +++ mypyc/lib-rt/CPy.h | 7 ++ mypyc/primitives/list_ops.py | 9 ++ mypyc/test-data/irbuild-basic.test | 70 +++++++++------- mypyc/test-data/irbuild-lists.test | 118 +++++++++++++++++---------- mypyc/test-data/irbuild-tuple.test | 63 ++++++++------ mypyc/test-data/irbuild-vec-i64.test | 62 ++++++++------ mypyc/test-data/refcount.test | 53 +++++++----- mypyc/test-data/run-lists.test | 106 ++++++++++++++++++++++++ mypyc/test-data/run-vecs-i64.test | 22 +++++ mypyc/test-data/run-vecs-nested.test | 19 +++++ mypyc/test-data/run-vecs-t.test | 25 ++++++ 14 files changed, 532 insertions(+), 155 deletions(-) diff --git a/mypyc/irbuild/for_helpers.py b/mypyc/irbuild/for_helpers.py index a2d50e81a32e5..e35abf704ec3b 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, @@ -84,7 +85,13 @@ from mypyc.irbuild.context import FuncInfo from mypyc.irbuild.env_class import add_vars_to_env, finalize_env_class, setup_env_class from mypyc.irbuild.targets import AssignmentTargetRegister, AssignmentTargetTuple -from mypyc.irbuild.vec import vec_append, vec_create, vec_get_item_unsafe, vec_init_item_unsafe +from mypyc.irbuild.vec import ( + vec_append, + vec_create, + vec_get_item_unsafe, + vec_init_item_unsafe, + vec_set_len_unsafe, +) from mypyc.primitives.dict_ops import ( dict_check_size_op, dict_item_iter_op, @@ -101,6 +108,7 @@ list_get_item_int64_op, list_get_item_unsafe_op, new_list_set_item_op, + new_list_set_size_op, ) from mypyc.primitives.misc_ops import stop_async_iteration_op from mypyc.primitives.registry import CFunctionDescription @@ -196,11 +204,12 @@ def for_loop_helper_with_index( body_insts: Callable[[Value], None], line: int, length: Value, -) -> None: +) -> Register: """Generate IR for a sequence iteration. This function only works for sequence type. Compared to for_loop_helper, - it would feed iteration index to body_insts. + it would feed iteration index to body_insts. Return the index register, + which holds the number of iterations after the loop. Args: index: the loop index Lvalue @@ -244,12 +253,17 @@ def for_loop_helper_with_index( builder.pop_loop_stack() builder.activate_block(exit_block) + return for_gen.index_target -def can_preallocate_from_generator(builder: IRBuilder, gen: GeneratorExpr) -> bool: +def can_preallocate_from_generator( + builder: IRBuilder, gen: GeneratorExpr, *, resizable: bool = False +) -> bool: """Can a sequence be built from a generator expression with a preallocated length? This requires a single loop without conditions over a sequence of known length. + If the length of the sequence can change during iteration (e.g. a list), the + built sequence must be resizable, since the preallocated length can be wrong. """ if not (len(gen.sequences) == 1 and len(gen.indices) == 1 and len(gen.condlists[0]) == 0): return False @@ -257,15 +271,32 @@ 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) + if not resizable and sequence_length_can_change(builder, gen.sequences[0]): + return False return is_sequence_rprimitive(rtype) or isinstance(rtype, RVec) +def sequence_length_can_change(builder: IRBuilder, expr: Expression) -> bool: + """Can the length of a sequence change while we iterate over it? + + A list can be modified in the loop body, or by another thread. This isn't + possible if the length is known at compile time, since the list is then + created by the expression (e.g. a list display), and nothing else refers to it. + """ + rtype = builder.node_type(expr) + if not (is_list_rprimitive(rtype) or is_bytearray_rprimitive(rtype)): + return False + return get_expr_length(builder, expr) is None + + def sequence_from_generator_preallocate_helper( builder: IRBuilder, gen: GeneratorExpr, empty_op_llbuilder: Callable[[Value, int], Value], set_item_op: Callable[[Value, Value, Value, int], None], after_first_init: GenFunc | None = None, + append_op: Callable[[Value, Value, int], Value] | None = None, + set_size_op: Callable[[Value, Value, int], Value] | None = None, ) -> Value | None: """Generate a new tuple or list from a simple generator expression. @@ -290,8 +321,19 @@ def sequence_from_generator_preallocate_helper( implementation. after_first_init: Optional function that generates instructions to run after the sequence has been evaluated (see comprehension_helper). + append_op: Optional function that appends an item to a sequence. It's called + with Self and New Value, and returns the resulting sequence (which can be + a new value, e.g. for vecs). + set_size_op: Optional function that reduces the length of a sequence, dropping + uninitialized items at the end. It's called with Self and New Length, and + returns the resulting sequence. + + If the length of the original sequence can change during iteration (e.g. it's a + list), append_op and set_size_op are required, since the preallocated length can + be wrong. If they aren't given, return None for such sequences. """ - if can_preallocate_from_generator(builder, gen): + resizable = append_op is not None and set_size_op is not None + if can_preallocate_from_generator(builder, gen, resizable=resizable): line = gen.line sequence_expr = gen.sequences[0] rtype = builder.node_type(sequence_expr) @@ -334,16 +376,48 @@ def sequence_from_generator_preallocate_helper( target_op = empty_op_llbuilder(length, line) - def set_item(item_index: Value) -> None: + if not sequence_length_can_change(builder, sequence_expr): + + def set_item(item_index: Value) -> None: + with builder.enter_borrow_scope(line): + e = builder.accept(gen.left_expr) + set_item_op(target_op, item_index, e, line) + + for_loop_helper_with_index( + builder, gen.indices[0], sequence_expr, sequence, set_item, line, length + ) + return target_op + + # The original sequence can grow or shrink while we iterate over it (e.g. if + # it's modified in the loop body). Like CPython, we include all items that + # we see, so the preallocated length can be wrong. + assert append_op is not None and set_size_op is not None + target = builder.ensure_register(target_op) + + def update_target(value: Value) -> None: + if value is not target: + builder.assign(target, value, line) + + def set_or_append_item(item_index: Value) -> None: with builder.enter_borrow_scope(line): e = builder.accept(gen.left_expr) - set_item_op(target_op, item_index, e, line) - - for_loop_helper_with_index( - builder, gen.indices[0], sequence_expr, sequence, set_item, line, length + set_block, append_block, next_block = BasicBlock(), BasicBlock(), BasicBlock() + fits = builder.binary_op(item_index, length, "<", line) + builder.add_bool_branch(fits, set_block, append_block) + builder.activate_block(set_block) + set_item_op(target, item_index, e, line) + builder.goto(next_block) + builder.activate_block(append_block) + update_target(append_op(target, e, line)) + builder.goto_and_activate(next_block) + + index = for_loop_helper_with_index( + builder, gen.indices[0], sequence_expr, sequence, set_or_append_item, line, length ) - - return target_op + # If the sequence shrank, drop the items at the end that we didn't set. After the + # loop, the index is the number of items we set or appended. + update_target(set_size_op(target, index, line)) + return target return None @@ -362,6 +436,14 @@ def translate_list_comprehension( def set_item(x: Value, y: Value, z: Value, line: int) -> None: builder.call_c(new_list_set_item_op, [x, y, z], line) + def append(x: Value, y: Value, line: int) -> Value: + builder.primitive_op(list_append_op, [x, y], line) + return x + + def set_size(x: Value, y: Value, line: int) -> Value: + builder.call_c(new_list_set_size_op, [x, y], line) + return x + # Try simplest list comprehension, otherwise fall back to general one val = sequence_from_generator_preallocate_helper( builder, @@ -369,6 +451,8 @@ def set_item(x: Value, y: Value, z: Value, line: int) -> None: empty_op_llbuilder=builder.builder.new_list_op_with_length, set_item_op=set_item, after_first_init=after_first_init, + append_op=append, + set_size_op=set_size, ) if val is not None: return val @@ -494,6 +578,12 @@ def translate_vec_comprehension( def set_item(x: Value, y: Value, z: Value, line: int) -> None: vec_init_item_unsafe(builder.builder, x, y, z, line) + def append(x: Value, y: Value, line: int) -> Value: + return vec_append(builder.builder, x, y, line) + + def set_size(x: Value, y: Value, line: int) -> Value: + return vec_set_len_unsafe(builder.builder, x, y, line) + # Try simplest comprehension, otherwise fall back to general one val = sequence_from_generator_preallocate_helper( builder, @@ -502,6 +592,8 @@ def set_item(x: Value, y: Value, z: Value, line: int) -> None: builder.builder, vec_type, length, line, capacity=capacity ), set_item_op=set_item, + append_op=append, + set_size_op=set_size, ) if val is not None: return val diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index c7cc8d4959932..b39485366293e 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -476,9 +476,10 @@ def translate_tuple_from_generator_call( """Special case for simplest tuple creation from a generator. For example: - tuple(f(x) for x in some_list/some_tuple/some_str/some_bytes) + tuple(f(x) for x in some_tuple/some_str/some_bytes) 'translate_safe_generator_call()' would take care of other cases - if this fails. + if this fails. This includes lists, since a tuple can't be resized if + the list is modified during iteration. """ if ( len(expr.args) == 1 diff --git a/mypyc/irbuild/vec.py b/mypyc/irbuild/vec.py index 8dffc12a22130..cf606c7434437 100644 --- a/mypyc/irbuild/vec.py +++ b/mypyc/irbuild/vec.py @@ -242,6 +242,18 @@ def vec_len_native(builder: LowLevelIRBuilder, val: Value) -> Value: return builder.get_element(val, "len") +def vec_set_len_unsafe( + builder: LowLevelIRBuilder, vecobj: Value, length: Value, line: int +) -> Value: + """Return with a reduced length (steal ). + + Items at or after the new length must not have been initialized, so that + they don't need to be freed (vec_create initializes them to NULL if needed). + """ + length = as_platform_int(builder, length, line) + return builder.add(SetElement(vecobj, "len", length, line)) + + def vec_items(builder: LowLevelIRBuilder, vecobj: Value) -> Value: """Return pointer to first item in vec. diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 65cc8f038e508..0cff756366406 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -930,6 +930,13 @@ PyObject *CPyList_GetItemBorrow(PyObject *list, CPyTagged index); PyObject *CPyList_GetItemShortBorrow(PyObject *list, CPyTagged index); PyObject *CPyList_GetItemInt64Borrow(PyObject *list, int64_t index); void CPyList_SetItemUnsafe(PyObject *list, Py_ssize_t index, PyObject *value); + +// Reduce the size of a list that is being built using CPyList_SetItemUnsafe. +// Items at or after the new size must not have been set. +static inline void CPyList_SetSizeUnsafe(PyObject *list, Py_ssize_t size) { + Py_SET_SIZE(list, size); +} + PyObject *CPyList_Build(Py_ssize_t len, ...); PyObject *CPyList_PopLast(PyObject *obj); PyObject *CPyList_Pop(PyObject *obj, CPyTagged index); diff --git a/mypyc/primitives/list_ops.py b/mypyc/primitives/list_ops.py index f5548e88592f1..d0586fd7001c9 100644 --- a/mypyc/primitives/list_ops.py +++ b/mypyc/primitives/list_ops.py @@ -195,6 +195,15 @@ steals=[False, False, True], ) +# Reduce the size of a list built using new_list_set_item_op. Items at or after +# the new size must not have been set. +new_list_set_size_op = custom_op( + arg_types=[list_rprimitive, c_pyssize_t_rprimitive], + return_type=void_rtype, + c_function_name="CPyList_SetSizeUnsafe", + error_kind=ERR_NEVER, +) + # list.append(obj) list_append_op = method_op( name="append", diff --git a/mypyc/test-data/irbuild-basic.test b/mypyc/test-data/irbuild-basic.test index c1e902887da9b..4477db9393eeb 100644 --- a/mypyc/test-data/irbuild-basic.test +++ b/mypyc/test-data/irbuild-basic.test @@ -2058,14 +2058,17 @@ def f(l): r4 :: tuple[int, int, int] r5, x, r6, y, r7, z :: int r8, r9 :: native_int - r10 :: list - r11, r12 :: native_int - r13 :: bit - r14 :: object - r15 :: tuple[int, int, int] - r16, x_2, r17, y_2, r18, z_2, r19, r20 :: int - r21 :: object - r22 :: native_int + r10, r11 :: list + r12, r13 :: native_int + r14 :: bit + r15 :: object + r16 :: tuple[int, int, int] + r17, x_2, r18, y_2, r19, z_2, r20, r21 :: int + r22 :: bit + r23, r24 :: object + r25 :: i32 + r26 :: bit + r27 :: native_int L0: r0 = 0 L1: @@ -2088,30 +2091,41 @@ L3: L4: r9 = var_object_size l r10 = PyList_New(r9) - r11 = 0 + r11 = r10 + r12 = 0 L5: - r12 = var_object_size l - r13 = r11 < r12 :: signed - if r13 goto L6 else goto L8 :: bool + r13 = var_object_size l + r14 = r12 < r13 :: signed + if r14 goto L6 else goto L11 :: bool L6: - r14 = list_get_item_unsafe l, r11 - r15 = unbox(tuple[int, int, int], r14) - r16 = r15[0] - x_2 = r16 - r17 = r15[1] - y_2 = r17 - r18 = r15[2] - z_2 = r18 - r19 = CPyTagged_Add(x_2, y_2) - r20 = CPyTagged_Add(r19, z_2) - r21 = box(int, r20) - CPyList_SetItemUnsafe(r10, r11, r21) + r15 = list_get_item_unsafe l, r12 + r16 = unbox(tuple[int, int, int], r15) + r17 = r16[0] + x_2 = r17 + r18 = r16[1] + y_2 = r18 + r19 = r16[2] + z_2 = r19 + r20 = CPyTagged_Add(x_2, y_2) + r21 = CPyTagged_Add(r20, z_2) + r22 = r12 < r9 :: signed + if r22 goto L7 else goto L8 :: bool L7: - r22 = r11 + 1 - r11 = r22 - goto L5 + r23 = box(int, r21) + CPyList_SetItemUnsafe(r11, r12, r23) + goto L9 L8: - return r10 + r24 = box(int, r21) + r25 = PyList_Append(r11, r24) + r26 = r25 >= 0 :: signed +L9: +L10: + r27 = r12 + 1 + r12 = r27 + goto L5 +L11: + CPyList_SetSizeUnsafe(r11, r12) + return r11 [case testProperty_withgil] class PropertyHolder: diff --git a/mypyc/test-data/irbuild-lists.test b/mypyc/test-data/irbuild-lists.test index 44ce501756308..92192f3ff76ee 100644 --- a/mypyc/test-data/irbuild-lists.test +++ b/mypyc/test-data/irbuild-lists.test @@ -387,64 +387,92 @@ def f(source: List[int]) -> None: def f(source): source :: list r0 :: native_int - r1 :: list - r2, r3 :: native_int - r4 :: bit - r5 :: object - r6, x, r7 :: int - r8 :: object - r9 :: native_int + r1, r2 :: list + r3, r4 :: native_int + r5 :: bit + r6 :: object + r7, x, r8 :: int + r9 :: bit + r10, r11 :: object + r12 :: i32 + r13 :: bit + r14 :: native_int a :: list - r10 :: native_int - r11 :: list - r12, r13 :: native_int - r14 :: bit - r15 :: object - r16, x_2, r17 :: int - r18 :: object - r19 :: native_int + r15 :: native_int + r16, r17 :: list + r18, r19 :: native_int + r20 :: bit + r21 :: object + r22, x_2, r23 :: int + r24 :: bit + r25, r26 :: object + r27 :: i32 + r28 :: bit + r29 :: native_int b :: list L0: r0 = var_object_size source r1 = PyList_New(r0) - r2 = 0 + r2 = r1 + r3 = 0 L1: - r3 = var_object_size source - r4 = r2 < r3 :: signed - if r4 goto L2 else goto L4 :: bool + r4 = var_object_size source + r5 = r3 < r4 :: signed + if r5 goto L2 else goto L7 :: bool L2: - r5 = list_get_item_unsafe source, r2 - r6 = unbox(int, r5) - x = r6 - r7 = CPyTagged_Add(x, 2) - r8 = box(int, r7) - CPyList_SetItemUnsafe(r1, r2, r8) + r6 = list_get_item_unsafe source, r3 + r7 = unbox(int, r6) + x = r7 + r8 = CPyTagged_Add(x, 2) + r9 = r3 < r0 :: signed + if r9 goto L3 else goto L4 :: bool L3: - r9 = r2 + 1 - r2 = r9 - goto L1 + r10 = box(int, r8) + CPyList_SetItemUnsafe(r2, r3, r10) + goto L5 L4: - a = r1 - r10 = var_object_size source - r11 = PyList_New(r10) - r12 = 0 + r11 = box(int, r8) + r12 = PyList_Append(r2, r11) + r13 = r12 >= 0 :: signed L5: - r13 = var_object_size source - r14 = r12 < r13 :: signed - if r14 goto L6 else goto L8 :: bool L6: - r15 = list_get_item_unsafe source, r12 - r16 = unbox(int, r15) - x_2 = r16 - r17 = CPyTagged_Add(x_2, 2) - r18 = box(int, r17) - CPyList_SetItemUnsafe(r11, r12, r18) + r14 = r3 + 1 + r3 = r14 + goto L1 L7: - r19 = r12 + 1 - r12 = r19 - goto L5 + CPyList_SetSizeUnsafe(r2, r3) + a = r2 + r15 = var_object_size source + r16 = PyList_New(r15) + r17 = r16 + r18 = 0 L8: - b = r11 + r19 = var_object_size source + r20 = r18 < r19 :: signed + if r20 goto L9 else goto L14 :: bool +L9: + r21 = list_get_item_unsafe source, r18 + r22 = unbox(int, r21) + x_2 = r22 + r23 = CPyTagged_Add(x_2, 2) + r24 = r18 < r15 :: signed + if r24 goto L10 else goto L11 :: bool +L10: + r25 = box(int, r23) + CPyList_SetItemUnsafe(r17, r18, r25) + goto L12 +L11: + r26 = box(int, r23) + r27 = PyList_Append(r17, r26) + r28 = r27 >= 0 :: signed +L12: +L13: + r29 = r18 + 1 + r18 = r29 + goto L8 +L14: + CPyList_SetSizeUnsafe(r17, r18) + b = r17 return 1 [case testListFromGeneratorExpr] diff --git a/mypyc/test-data/irbuild-tuple.test b/mypyc/test-data/irbuild-tuple.test index 2cb6fac30b22e..b5a4261f015c1 100644 --- a/mypyc/test-data/irbuild-tuple.test +++ b/mypyc/test-data/irbuild-tuple.test @@ -302,15 +302,18 @@ def test(): r4 :: ptr source :: list r5 :: native_int - r6 :: tuple - r7, r8 :: native_int - r9 :: bit - r10 :: object - r11, x :: int - r12 :: bool - r13 :: object - r14 :: native_int - a :: tuple + r6, r7 :: list + r8, r9 :: native_int + r10 :: bit + r11 :: object + r12, x :: int + r13 :: bool + r14 :: bit + r15, r16 :: object + r17 :: i32 + r18 :: bit + r19 :: native_int + r20, a :: tuple L0: r0 = PyList_New(3) r1 = object 1 @@ -323,25 +326,37 @@ L0: keep_alive r0 source = r0 r5 = var_object_size source - r6 = PyTuple_New(r5) - r7 = 0 + r6 = PyList_New(r5) + r7 = r6 + r8 = 0 L1: - r8 = var_object_size source - r9 = r7 < r8 :: signed - if r9 goto L2 else goto L4 :: bool + r9 = var_object_size source + r10 = r8 < r9 :: signed + if r10 goto L2 else goto L7 :: bool L2: - r10 = list_get_item_unsafe source, r7 - r11 = unbox(int, r10) - x = r11 - r12 = f(x) - r13 = box(bool, r12) - CPySequenceTuple_SetItemUnsafe(r6, r7, r13) + r11 = list_get_item_unsafe source, r8 + r12 = unbox(int, r11) + x = r12 + r13 = f(x) + r14 = r8 < r5 :: signed + if r14 goto L3 else goto L4 :: bool L3: - r14 = r7 + 1 - r7 = r14 - goto L1 + r15 = box(bool, r13) + CPyList_SetItemUnsafe(r7, r8, r15) + goto L5 L4: - a = r6 + r16 = box(bool, r13) + r17 = PyList_Append(r7, r16) + r18 = r17 >= 0 :: signed +L5: +L6: + r19 = r8 + 1 + r8 = r19 + goto L1 +L7: + CPyList_SetSizeUnsafe(r7, r8) + r20 = PyList_AsTuple(r7) + a = r20 return 1 [case testTupleBuiltFromStr] diff --git a/mypyc/test-data/irbuild-vec-i64.test b/mypyc/test-data/irbuild-vec-i64.test index d9f96ea0ef3ea..f8bb583025586 100644 --- a/mypyc/test-data/irbuild-vec-i64.test +++ b/mypyc/test-data/irbuild-vec-i64.test @@ -345,39 +345,53 @@ def f(n, l): n :: i64 l :: list r0 :: native_int - r1 :: vec[i64] - r2, r3 :: native_int - r4 :: bit - r5 :: object - r6, x, r7 :: i64 - r8 :: ptr - r9 :: native_int + r1, r2 :: vec[i64] + r3, r4 :: native_int + r5 :: bit + r6 :: object + r7, x, r8 :: i64 + r9 :: bit r10 :: ptr r11 :: native_int + r12 :: ptr + r13 :: vec[i64] + r14 :: native_int + r15 :: vec[i64] L0: r0 = var_object_size l r1 = VecI64Api.alloc(r0, r0) - r2 = 0 + r2 = r1 + r3 = 0 L1: - r3 = var_object_size l - r4 = r2 < r3 :: signed - if r4 goto L2 else goto L4 :: bool + r4 = var_object_size l + r5 = r3 < r4 :: signed + if r5 goto L2 else goto L7 :: bool L2: - r5 = CPyList_GetItemInt64(l, r2) - r6 = unbox(i64, r5) - x = r6 - r7 = x + 1 - r8 = r1.items - r9 = r2 * 8 - r10 = r8 + r9 - set_mem r10, r7 :: i64* - keep_alive r1 + r6 = CPyList_GetItemInt64(l, r3) + r7 = unbox(i64, r6) + x = r7 + r8 = x + 1 + r9 = r3 < r0 :: signed + if r9 goto L3 else goto L4 :: bool L3: - r11 = r2 + 1 - r2 = r11 - goto L1 + r10 = r2.items + r11 = r3 * 8 + r12 = r10 + r11 + set_mem r12, r8 :: i64* + keep_alive r2 + goto L5 L4: - return r1 + r13 = VecI64Api.append(r2, r8) + r2 = r13 +L5: +L6: + r14 = r3 + 1 + r3 = r14 + goto L1 +L7: + r15 = set_element r2, len, r3 + r2 = r15 + return r2 [case testVecI64FastComprehensionFromVec_64bit] from librt.vecs import vec diff --git a/mypyc/test-data/refcount.test b/mypyc/test-data/refcount.test index a6b92ab33d7dc..532bf919da86b 100644 --- a/mypyc/test-data/refcount.test +++ b/mypyc/test-data/refcount.test @@ -2862,34 +2862,47 @@ L0: def f(a): a :: list r0 :: native_int - r1 :: list - r2, r3 :: native_int - r4 :: bit - r5 :: object - r6, x :: __main__.C - r7 :: str - r8 :: native_int + r1, r2 :: list + r3, r4 :: native_int + r5 :: bit + r6 :: object + r7, x :: __main__.C + r8 :: str + r9 :: bit + r10 :: i32 + r11 :: bit + r12 :: native_int L0: r0 = var_object_size a r1 = PyList_New(r0) - r2 = 0 + r2 = r1 + r3 = 0 L1: - r3 = var_object_size a - r4 = r2 < r3 :: signed - if r4 goto L2 else goto L4 :: bool + r4 = var_object_size a + r5 = r3 < r4 :: signed + if r5 goto L2 else goto L6 :: bool L2: - r5 = list_get_item_unsafe a, r2 - r6 = cast(__main__.C, r5) - x = r6 - r7 = x.s + r6 = list_get_item_unsafe a, r3 + r7 = cast(__main__.C, r6) + x = r7 + r8 = x.s dec_ref x - CPyList_SetItemUnsafe(r1, r2, r7) + r9 = r3 < r0 :: signed + if r9 goto L3 else goto L4 :: bool L3: - r8 = r2 + 1 - r2 = r8 - goto L1 + CPyList_SetItemUnsafe(r2, r3, r8) + goto L5 L4: - return r1 + r10 = PyList_Append(r2, r8) + dec_ref r8 + r11 = r10 >= 0 :: signed +L5: + r12 = r3 + 1 + r3 = r12 + goto L1 +L6: + CPyList_SetSizeUnsafe(r2, r3) + return r2 [case testBorrowedFinalInSetComprehension_withgil] from typing import Final diff --git a/mypyc/test-data/run-lists.test b/mypyc/test-data/run-lists.test index ccb24de3514f9..d536df5440173 100644 --- a/mypyc/test-data/run-lists.test +++ b/mypyc/test-data/run-lists.test @@ -598,6 +598,112 @@ def test_from_gen_unknown_length() -> None: empty: list[int] = [] assert list(x for x in empty) == [] +[case testListBuiltFromModifiedList] +import asyncio +from typing import List + +from testutil import assertRaises + +def grow(a: List[str], x: str) -> str: + if len(a) < 6: + a.append(x + "!") + return x + +def shrink(a: List[str], x: str) -> str: + a.pop() + return x + +def clear(a: List[str], x: str) -> str: + a.clear() + return x + +def replace(a: List[str], x: str) -> str: + if x == "a": + a.clear() + a.extend(["p", "q", "r", "s", "t"]) + return x + +def fail(a: List[str], x: str) -> str: + if len(a) > 3: + raise ValueError(x) + a.append(x) + return x + +GROWN = ["a", "b", "a!", "b!", "a!!", "b!!"] + +def test_list_comprehension() -> None: + a = ["a", "b"] + assert [grow(a, x) for x in a] == GROWN + a = ["a", "b", "c", "d"] + assert [shrink(a, x) for x in a] == ["a", "b"] + a = ["a", "b", "c", "d"] + assert [clear(a, x) for x in a] == ["a"] + a = ["a", "b"] + assert [replace(a, x) for x in a] == ["a", "q", "r", "s", "t"] + a = ["a", "b"] + assert [x + "?" for x in a] == ["a?", "b?"] + a = ["a", "b"] + with assertRaises(ValueError, "a"): + [fail(a, x) for x in a] + +def test_list_from_generator() -> None: + a = ["a", "b"] + assert list(grow(a, x) for x in a) == GROWN + a = ["a", "b", "c", "d"] + assert list(shrink(a, x) for x in a) == ["a", "b"] + a = ["a", "b"] + assert list(x + "?" for x in a) == ["a?", "b?"] + +def test_tuple_from_generator() -> None: + a = ["a", "b"] + assert tuple(grow(a, x) for x in a) == tuple(GROWN) + a = ["a", "b", "c", "d"] + assert tuple(shrink(a, x) for x in a) == ("a", "b") + a = ["a", "b"] + assert tuple(x + "?" for x in a) == ("a?", "b?") + +def test_sorted_from_generator() -> None: + a = ["b", "a"] + assert sorted(grow(a, x) for x in a) == ["a", "a!", "a!!", "b", "b!", "b!!"] + a = ["d", "c", "b", "a"] + assert sorted(shrink(a, x) for x in a) == ["c", "d"] + a = ["b", "a"] + assert sorted(x + "?" for x in a) == ["a?", "b?"] + +def test_join_from_generator() -> None: + a = ["a", "b"] + assert ",".join(grow(a, x) for x in a) == "a,b,a!,b!,a!!,b!!" + a = ["a", "b", "c", "d"] + assert ",".join(shrink(a, x) for x in a) == "a,b" + a = ["a", "b"] + assert ",".join(x + "?" for x in a) == "a?,b?" + +async def async_grow(a: List[str], x: str) -> str: + await asyncio.sleep(0) + return grow(a, x) + +async def async_shrink(a: List[str], x: str) -> str: + await asyncio.sleep(0) + return shrink(a, x) + +async def async_grow_comprehension(a: List[str]) -> List[str]: + return [await async_grow(a, x) for x in a] + +async def async_shrink_comprehension(a: List[str]) -> List[str]: + return [await async_shrink(a, x) for x in a] + +def test_async_comprehension() -> None: + assert asyncio.run(async_grow_comprehension(["a", "b"])) == GROWN + assert asyncio.run(async_shrink_comprehension(["a", "b", "c", "d"])) == ["a", "b"] + +[file asyncio/__init__.pyi] +from typing import Any, Awaitable, TypeVar +T = TypeVar("T") +async def sleep(t: float) -> None: ... +def run(x: Awaitable[T]) -> T: ... + +[typing fixtures/typing-full.pyi] + [case testNext] from typing import List diff --git a/mypyc/test-data/run-vecs-i64.test b/mypyc/test-data/run-vecs-i64.test index b8a74c96d6fb9..cfa05aaa4e87a 100644 --- a/mypyc/test-data/run-vecs-i64.test +++ b/mypyc/test-data/run-vecs-i64.test @@ -249,6 +249,28 @@ def test_construct_from_list_comprehension() -> None: for j in range(i): assert v[j] == j * j + 5 +def grow_list(a: list[i64], x: i64) -> i64: + if len(a) < 6: + a.append(x + 10) + return x + +def shrink_list(a: list[i64], x: i64) -> i64: + a.pop() + return x + +def test_construct_from_modified_list_comprehension() -> None: + a: list[i64] = [1, 2] + assert vec[i64]([grow_list(a, x) for x in a]) == vec[i64]([1, 2, 11, 12, 21, 22]) + a = [1, 2, 3, 4] + assert vec[i64]([shrink_list(a, x) for x in a]) == vec[i64]([1, 2]) + a = [1, 2, 3, 4] + v = vec[i64]([shrink_list(a, x) for x in a], capacity=10) + assert v == vec[i64]([1, 2]) + v = append(v, 5) + assert v == vec[i64]([1, 2, 5]) + a = [1, 2] + assert vec[i64]([x + 1 for x in a]) == vec[i64]([2, 3]) + def test_construct_from_range() -> None: v = vec[i64](range(0)) assert v == vec[i64]() diff --git a/mypyc/test-data/run-vecs-nested.test b/mypyc/test-data/run-vecs-nested.test index 98a53e6e0bb6e..4b1de97502aac 100644 --- a/mypyc/test-data/run-vecs-nested.test +++ b/mypyc/test-data/run-vecs-nested.test @@ -127,6 +127,25 @@ def test_equality_different_types() -> None: assert vec[vec[str]]() != vec[vec[bytes]]() assert vec[vec[str]]() != vec[vec[i64]]() +def grow_list(a: list[str], x: str) -> vec[str]: + if len(a) < 6: + a.append(x + "!") + return vec[str]([x]) + +def shrink_list(a: list[str], x: str) -> vec[str]: + a.pop() + return vec[str]([x]) + +def test_construct_from_modified_list_comprehension() -> None: + a = ["a", "b"] + v = vec[vec[str]]([grow_list(a, x) for x in a]) + assert v == vec[vec[str]](vec[str]([x]) for x in ["a", "b", "a!", "b!", "a!!", "b!!"]) + a = ["a", "b", "c", "d"] + v = vec[vec[str]]([shrink_list(a, x) for x in a]) + assert v == vec[vec[str]]([vec[str](["a"]), vec[str](["b"])]) + v = append(v, vec[str](["x"])) + assert v == vec[vec[str]]([vec[str](["a"]), vec[str](["b"]), vec[str](["x"])]) + def test_slicing() -> None: v = vec[vec[str]](vec[str]([str(i)]) for i in range(5)) assert v[1:4] == vec[vec[str]]([v[1], v[2], v[3]]) diff --git a/mypyc/test-data/run-vecs-t.test b/mypyc/test-data/run-vecs-t.test index 50d1adbd51306..cc2e9850d4f4e 100644 --- a/mypyc/test-data/run-vecs-t.test +++ b/mypyc/test-data/run-vecs-t.test @@ -160,6 +160,31 @@ def test_construct_from_list_comprehension() -> None: for j in range(i): assert v[j] == str(j * j + 5) +def grow_list(a: list[str], x: str) -> str: + if len(a) < 6: + a.append(x + "!") + return x + +def shrink_list(a: list[str], x: str) -> str: + a.pop() + return x + +def test_construct_from_modified_list_comprehension() -> None: + a = ["a", "b"] + assert vec[str]([grow_list(a, x) for x in a]) == vec[str](["a", "b", "a!", "b!", "a!!", "b!!"]) + a = ["a", "b", "c", "d"] + assert vec[str]([shrink_list(a, x) for x in a]) == vec[str](["a", "b"]) + a = ["a", "b", "c", "d"] + v = vec[str]([shrink_list(a, x) for x in a], capacity=10) + assert v == vec[str](["a", "b"]) + v = append(v, "x") + assert v == vec[str](["a", "b", "x"]) + a = ["a"] + v = vec[str]([grow_list(a, x) for x in a], capacity=3) + assert v == vec[str](["a", "a!", "a!!", "a!!!", "a!!!!", "a!!!!!"]) + a = ["a", "b"] + assert vec[str]([x + "?" for x in a]) == vec[str](["a?", "b?"]) + def test_construct_from_list() -> None: a: list[str] = [] assert vec[str](a) == vec[str]() From d4a03fee7ed8704e910393b1d4e1fbe887f7df77 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 16:50:16 +0500 Subject: [PATCH 2/3] [mypyc] Preallocate tuples built from generators over lists again The previous commit made tuple() build a list first and then convert it to a tuple, since a preallocated tuple can't be resized if the list is modified during iteration. This made it up to about 2x slower. Instead, preallocate the tuple as before, but if an item doesn't fit, move the items to a larger tuple (the capacity is doubled). After the loop, move the items to a tuple of the correct size if the length changed. If the list isn't modified, the only extra cost is one comparison per item. --- mypyc/irbuild/for_helpers.py | 19 ++++++------ mypyc/irbuild/specialize.py | 22 +++++++++++--- mypyc/lib-rt/CPy.h | 3 ++ mypyc/lib-rt/tuple_ops.c | 49 ++++++++++++++++++++++++++++++ mypyc/primitives/tuple_ops.py | 21 +++++++++++++ mypyc/test-data/irbuild-tuple.test | 27 ++++++++-------- mypyc/test-data/run-lists.test | 28 +++++++++++++++++ 7 files changed, 141 insertions(+), 28 deletions(-) diff --git a/mypyc/irbuild/for_helpers.py b/mypyc/irbuild/for_helpers.py index e35abf704ec3b..967368a446d91 100644 --- a/mypyc/irbuild/for_helpers.py +++ b/mypyc/irbuild/for_helpers.py @@ -295,7 +295,7 @@ def sequence_from_generator_preallocate_helper( empty_op_llbuilder: Callable[[Value, int], Value], set_item_op: Callable[[Value, Value, Value, int], None], after_first_init: GenFunc | None = None, - append_op: Callable[[Value, Value, int], Value] | None = None, + append_op: Callable[[Value, Value, Value, int], Value] | None = None, set_size_op: Callable[[Value, Value, int], Value] | None = None, ) -> Value | None: """Generate a new tuple or list from a simple generator expression. @@ -321,9 +321,10 @@ def sequence_from_generator_preallocate_helper( implementation. after_first_init: Optional function that generates instructions to run after the sequence has been evaluated (see comprehension_helper). - append_op: Optional function that appends an item to a sequence. It's called - with Self and New Value, and returns the resulting sequence (which can be - a new value, e.g. for vecs). + append_op: Optional function that appends an item to a sequence, when the + target position is at or after the preallocated length. It's called with + Self, Target position and New Value, and returns the resulting sequence + (which can be a new value, e.g. for vecs and tuples). set_size_op: Optional function that reduces the length of a sequence, dropping uninitialized items at the end. It's called with Self and New Length, and returns the resulting sequence. @@ -408,7 +409,7 @@ def set_or_append_item(item_index: Value) -> None: set_item_op(target, item_index, e, line) builder.goto(next_block) builder.activate_block(append_block) - update_target(append_op(target, e, line)) + update_target(append_op(target, item_index, e, line)) builder.goto_and_activate(next_block) index = for_loop_helper_with_index( @@ -436,8 +437,8 @@ def translate_list_comprehension( def set_item(x: Value, y: Value, z: Value, line: int) -> None: builder.call_c(new_list_set_item_op, [x, y, z], line) - def append(x: Value, y: Value, line: int) -> Value: - builder.primitive_op(list_append_op, [x, y], line) + def append(x: Value, y: Value, z: Value, line: int) -> Value: + builder.primitive_op(list_append_op, [x, z], line) return x def set_size(x: Value, y: Value, line: int) -> Value: @@ -578,8 +579,8 @@ def translate_vec_comprehension( def set_item(x: Value, y: Value, z: Value, line: int) -> None: vec_init_item_unsafe(builder.builder, x, y, z, line) - def append(x: Value, y: Value, line: int) -> Value: - return vec_append(builder.builder, x, y, line) + def append(x: Value, y: Value, z: Value, line: int) -> Value: + return vec_append(builder.builder, x, z, line) def set_size(x: Value, y: Value, line: int) -> Value: return vec_set_len_unsafe(builder.builder, x, y, line) diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index b39485366293e..edb55273c16bb 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -175,7 +175,12 @@ str_get_item_unsafe_as_int_op, str_range_check_op, ) -from mypyc.primitives.tuple_ops import isinstance_tuple, new_tuple_set_item_op +from mypyc.primitives.tuple_ops import ( + isinstance_tuple, + new_tuple_set_item_grow_op, + new_tuple_set_item_op, + new_tuple_set_size_op, +) # Specializers are attempted before compiling the arguments to the # function. Specializers can return None to indicate that they failed @@ -476,28 +481,35 @@ def translate_tuple_from_generator_call( """Special case for simplest tuple creation from a generator. For example: - tuple(f(x) for x in some_tuple/some_str/some_bytes) + tuple(f(x) for x in some_list/some_tuple/some_str/some_bytes) 'translate_safe_generator_call()' would take care of other cases - if this fails. This includes lists, since a tuple can't be resized if - the list is modified during iteration. + if this fails. """ if ( len(expr.args) == 1 and expr.arg_kinds[0] == ARG_POS and isinstance(expr.args[0], GeneratorExpr) - and can_preallocate_from_generator(builder, expr.args[0]) + and can_preallocate_from_generator(builder, expr.args[0], resizable=True) ): gen = expr.args[0] def set_item(x: Value, y: Value, z: Value, line: int) -> None: builder.call_c(new_tuple_set_item_op, [x, y, z], line) + def set_item_grow(x: Value, y: Value, z: Value, line: int) -> Value: + return builder.call_c(new_tuple_set_item_grow_op, [x, y, z], line) + + def set_size(x: Value, y: Value, line: int) -> Value: + return builder.call_c(new_tuple_set_size_op, [x, y], line) + with comprehension_scope(builder, gen): return sequence_from_generator_preallocate_helper( builder, gen, empty_op_llbuilder=builder.builder.new_tuple_with_length, set_item_op=set_item, + append_op=set_item_grow, + set_size_op=set_size, ) return None diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 0cff756366406..0814f2fb53d4b 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -1106,6 +1106,9 @@ static inline void CPySequenceTuple_SetItemUnsafe(PyObject *tuple, Py_ssize_t in PyTuple_SET_ITEM(tuple, index, value); } +PyObject *CPySequenceTuple_SetItemGrow(PyObject *tuple, Py_ssize_t index, PyObject *value); +PyObject *CPySequenceTuple_SetSize(PyObject *tuple, Py_ssize_t size); + // Exception operations diff --git a/mypyc/lib-rt/tuple_ops.c b/mypyc/lib-rt/tuple_ops.c index 3d4442e61b1b0..a65614ac201ba 100644 --- a/mypyc/lib-rt/tuple_ops.c +++ b/mypyc/lib-rt/tuple_ops.c @@ -40,3 +40,52 @@ PyObject *CPySequenceTuple_GetSlice(PyObject *obj, CPyTagged start, CPyTagged en } return CPyObject_GetSlice(obj, start, end); } + +// Move the first n items of a tuple being built into a new tuple of the given size. +// Steals the reference to the original tuple. +static PyObject *CPyTuple_MoveItems(PyObject *tuple, Py_ssize_t n, Py_ssize_t size) { + PyObject *result = PyTuple_New(size); + if (result == NULL) { + Py_DECREF(tuple); + return NULL; + } + for (Py_ssize_t i = 0; i < n; i++) { + PyTuple_SET_ITEM(result, i, PyTuple_GET_ITEM(tuple, i)); + PyTuple_SET_ITEM(tuple, i, NULL); + } + Py_DECREF(tuple); + return result; +} + +// Set an item of a tuple that is being built using CPySequenceTuple_SetItemUnsafe, and +// grow the tuple if the index is out of range. Items before the index must have been +// set, and items at or after it must not have been set (so the index is at most the +// size of the tuple). Steals the tuple and the value, +// and returns the resulting tuple, which may be a new object. +PyObject *CPySequenceTuple_SetItemGrow(PyObject *tuple, Py_ssize_t index, PyObject *value) { + Py_ssize_t size = PyTuple_GET_SIZE(tuple); + if (index >= size) { + Py_ssize_t new_size = size < 4 ? 8 : size * 2; + if (new_size <= index) { + new_size = index + 1; + } + tuple = CPyTuple_MoveItems(tuple, size, new_size); + if (tuple == NULL) { + Py_DECREF(value); + return NULL; + } + } + PyTuple_SET_ITEM(tuple, index, value); + return tuple; +} + +// Set the size of a tuple that is being built using CPySequenceTuple_SetItemUnsafe or +// CPySequenceTuple_SetItemGrow. Items before the size must have been set, and items at +// or after it must not have been set. Steals the tuple and returns the resulting tuple, +// which may be a new object. +PyObject *CPySequenceTuple_SetSize(PyObject *tuple, Py_ssize_t size) { + if (size == PyTuple_GET_SIZE(tuple)) { + return tuple; + } + return CPyTuple_MoveItems(tuple, size, size); +} diff --git a/mypyc/primitives/tuple_ops.py b/mypyc/primitives/tuple_ops.py index ab23f8c441f5b..e393259e68085 100644 --- a/mypyc/primitives/tuple_ops.py +++ b/mypyc/primitives/tuple_ops.py @@ -72,6 +72,27 @@ steals=[False, False, True], ) +# Like new_tuple_set_item_op, but grow the tuple if the index is out of range. +# Items before the index must have been set. Returns the resulting tuple. +new_tuple_set_item_grow_op = custom_op( + arg_types=[tuple_rprimitive, c_pyssize_t_rprimitive, object_rprimitive], + return_type=tuple_rprimitive, + c_function_name="CPySequenceTuple_SetItemGrow", + error_kind=ERR_MAGIC, + steals=[True, False, True], +) + +# Set the size of a tuple built using new_tuple_set_item_op or new_tuple_set_item_grow_op. +# Items before the new size must have been set, and items after it must not have been set. +# Returns the resulting tuple. +new_tuple_set_size_op = custom_op( + arg_types=[tuple_rprimitive, c_pyssize_t_rprimitive], + return_type=tuple_rprimitive, + c_function_name="CPySequenceTuple_SetSize", + error_kind=ERR_MAGIC, + steals=[True, False], +) + # Construct tuple from a list. list_tuple_op = function_op( name="builtins.tuple", diff --git a/mypyc/test-data/irbuild-tuple.test b/mypyc/test-data/irbuild-tuple.test index b5a4261f015c1..503fdf08d0c4f 100644 --- a/mypyc/test-data/irbuild-tuple.test +++ b/mypyc/test-data/irbuild-tuple.test @@ -302,7 +302,7 @@ def test(): r4 :: ptr source :: list r5 :: native_int - r6, r7 :: list + r6, r7 :: tuple r8, r9 :: native_int r10 :: bit r11 :: object @@ -310,10 +310,9 @@ def test(): r13 :: bool r14 :: bit r15, r16 :: object - r17 :: i32 - r18 :: bit - r19 :: native_int - r20, a :: tuple + r17 :: tuple + r18 :: native_int + r19, a :: tuple L0: r0 = PyList_New(3) r1 = object 1 @@ -326,7 +325,7 @@ L0: keep_alive r0 source = r0 r5 = var_object_size source - r6 = PyList_New(r5) + r6 = PyTuple_New(r5) r7 = r6 r8 = 0 L1: @@ -342,21 +341,21 @@ L2: if r14 goto L3 else goto L4 :: bool L3: r15 = box(bool, r13) - CPyList_SetItemUnsafe(r7, r8, r15) + CPySequenceTuple_SetItemUnsafe(r7, r8, r15) goto L5 L4: r16 = box(bool, r13) - r17 = PyList_Append(r7, r16) - r18 = r17 >= 0 :: signed + r17 = CPySequenceTuple_SetItemGrow(r7, r8, r16) + r7 = r17 L5: L6: - r19 = r8 + 1 - r8 = r19 + r18 = r8 + 1 + r8 = r18 goto L1 L7: - CPyList_SetSizeUnsafe(r7, r8) - r20 = PyList_AsTuple(r7) - a = r20 + r19 = CPySequenceTuple_SetSize(r7, r8) + r7 = r19 + a = r7 return 1 [case testTupleBuiltFromStr] diff --git a/mypyc/test-data/run-lists.test b/mypyc/test-data/run-lists.test index d536df5440173..3f90507847d2a 100644 --- a/mypyc/test-data/run-lists.test +++ b/mypyc/test-data/run-lists.test @@ -661,6 +661,34 @@ def test_tuple_from_generator() -> None: assert tuple(shrink(a, x) for x in a) == ("a", "b") a = ["a", "b"] assert tuple(x + "?" for x in a) == ("a?", "b?") + a = ["a", "b", "c", "d"] + assert tuple(clear(a, x) for x in a) == ("a",) + a = ["a", "b"] + assert tuple(replace(a, x) for x in a) == ("a", "q", "r", "s", "t") + a = ["a", "b"] + with assertRaises(ValueError, "a"): + tuple(fail(a, x) for x in a) + +def grow_many(a: List[int], x: int) -> int: + if len(a) < 1000: + a.append(x + 1) + return x * 2 + +def grow_many_reference(a: List[int]) -> List[int]: + result = [] + i = 0 + while i < len(a): + result.append(grow_many(a, a[i])) + i += 1 + return result + +def test_tuple_from_generator_grow_many() -> None: + # The tuple is resized several times + for n in range(5): + expected = tuple(grow_many_reference(list(range(n)))) + assert len(expected) == (1000 if n else 0) + a = list(range(n)) + assert tuple(grow_many(a, x) for x in a) == expected, n def test_sorted_from_generator() -> None: a = ["b", "a"] From 64caa1c6546877ddfee492d55821541f7b1a9bff Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Fri, 13 Nov 2026 01:59:00 +0500 Subject: [PATCH 3/3] Fix compiler crash with await in vec comprehensions over lists SetElement didn't include the item in its sources, so the generator spill transform didn't see the use of the loop index register, which is used as the new vec length after the loop, and didn't move it to the generator frame. This caused a KeyError in codegen. --- mypyc/ir/ops.py | 4 +-- mypyc/test-data/run-async.test | 47 +++++++++++++++++++++++++++++++++ mypyc/transform/ir_transform.py | 1 + 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/mypyc/ir/ops.py b/mypyc/ir/ops.py index 9776aef98b205..0dbbeab4c95ae 100644 --- a/mypyc/ir/ops.py +++ b/mypyc/ir/ops.py @@ -1796,10 +1796,10 @@ def __init__(self, src: Value, field: str, item: Value, line: int = -1) -> None: self.field = field def sources(self) -> list[Value]: - return [self.src] + return [self.src, self.item] def set_sources(self, new: list[Value]) -> None: - (self.src,) = new + self.src, self.item = new def stolen(self) -> list[Value]: return [self.src] diff --git a/mypyc/test-data/run-async.test b/mypyc/test-data/run-async.test index 133b97d18b7ca..be8e50f83d3c9 100644 --- a/mypyc/test-data/run-async.test +++ b/mypyc/test-data/run-async.test @@ -3002,3 +3002,50 @@ with assertRaises(TypeError, "unbound method C.c() needs an argument"): C.__dict__["c"].__call__() assert run(C.__dict__["m"](C())) == 1 assert run(C.__dict__["c"](C)) == "C" + +[case testRunAsyncListComprehensionWithAwait_librt] +import asyncio +from typing import List + +from mypy_extensions import i64 +from librt.vecs import vec + +async def ident(x: str) -> str: + await asyncio.sleep(0) + return x + +async def ident_int(x: int) -> int: + await asyncio.sleep(0) + return x + +async def grow(a: List[str], x: str) -> str: + await asyncio.sleep(0) + if len(a) < 4: + a.append(x + "!") + return x + +async def shrink(a: List[str], x: str) -> str: + await asyncio.sleep(0) + a.pop() + return x + +async def test_list() -> None: + a = ["a", "b"] + assert [await ident(x) for x in a] == ["a", "b"] + assert [await grow(a, x) for x in a] == ["a", "b", "a!", "b!"] + a = ["a", "b", "c", "d"] + assert [await shrink(a, x) for x in a] == ["a", "b"] + +async def test_vec() -> None: + a = ["a", "b"] + assert vec[str]([await ident(x) for x in a]) == vec[str](["a", "b"]) + assert vec[str]([await grow(a, x) for x in a]) == vec[str](["a", "b", "a!", "b!"]) + a = ["a", "b", "c", "d"] + assert vec[str]([await shrink(a, x) for x in a]) == vec[str](["a", "b"]) + n = [1, 2, 3] + assert vec[i64]([await ident_int(x) for x in n]) == vec[i64]([1, 2, 3]) + +[file asyncio/__init__.pyi] +async def sleep(delay: float) -> None: ... + +[typing fixtures/typing-full.pyi] diff --git a/mypyc/transform/ir_transform.py b/mypyc/transform/ir_transform.py index 0ae48b7c80d7a..2a66ddfd7b6d8 100644 --- a/mypyc/transform/ir_transform.py +++ b/mypyc/transform/ir_transform.py @@ -367,6 +367,7 @@ def visit_get_element_ptr(self, op: GetElementPtr) -> None: def visit_set_element(self, op: SetElement) -> None: op.src = self.fix_op(op.src) + op.item = self.fix_op(op.item) def visit_load_address(self, op: LoadAddress) -> None: if isinstance(op.src, LoadStatic):