Debian Codegraph @

mypyc/irbuild/for_helpers.py

raw
1 """Helpers for generating for loops and comprehensions.
2
3 We special case certain kinds for loops such as "for x in range(...)"
4 for better efficiency. Each for loop generator class below deals one
5 such special case.
6 """
7
8 from __future__ import annotations
9
10 from collections.abc import Callable
11 from typing import ClassVar, cast
12
13 from mypy.nodes import (
14 ARG_POS,
15 CallExpr,
16 DictionaryComprehension,
17 Expression,
18 GeneratorExpr,
19 ListExpr,
20 Lvalue,
21 MemberExpr,
22 NameExpr,
23 RefExpr,
24 SetExpr,
25 StarExpr,
26 TupleExpr,
27 TypeAlias,
28 Var,
29 )
30 from mypy.types import LiteralType, TupleType, get_proper_type, get_proper_types
31 from mypyc.ir.ops import (
32 ERR_NEVER,
33 BasicBlock,
34 Branch,
35 Integer,
36 IntOp,
37 LoadAddress,
38 LoadErrorValue,
39 LoadGlobal,
40 LoadLiteral,
41 MethodCall,
42 RaiseStandardError,
43 Register,
44 TupleGet,
45 TupleSet,
46 Value,
47 )
48 from mypyc.ir.rtypes import (
49 RInstance,
50 RTuple,
51 RType,
52 RVec,
53 bool_rprimitive,
54 c_pyssize_t_rprimitive,
55 int_rprimitive,
56 is_dict_rprimitive,
57 is_fixed_width_rtype,
58 is_immutable_rprimitive,
59 is_list_rprimitive,
60 is_sequence_rprimitive,
61 is_short_int_rprimitive,
62 is_str_rprimitive,
63 is_tuple_rprimitive,
64 object_pointer_rprimitive,
65 object_rprimitive,
66 short_int_rprimitive,
67 )
68 from mypyc.irbuild.builder import IRBuilder
69 from mypyc.irbuild.constant_fold import constant_fold_expr
70 from mypyc.irbuild.prepare import GENERATOR_HELPER_NAME
71 from mypyc.irbuild.targets import AssignmentTarget, AssignmentTargetTuple
72 from mypyc.irbuild.vec import vec_append, vec_create, vec_get_item_unsafe, vec_init_item_unsafe
73 from mypyc.primitives.dict_ops import (
74 dict_check_size_op,
75 dict_item_iter_op,
76 dict_key_iter_op,
77 dict_next_item_op,
78 dict_next_key_op,
79 dict_next_value_op,
80 dict_value_iter_op,
81 )
82 from mypyc.primitives.exc_ops import no_err_occurred_op, propagate_if_error_op
83 from mypyc.primitives.generic_ops import aiter_op, anext_op, iter_op, next_op
84 from mypyc.primitives.list_ops import list_append_op, list_get_item_unsafe_op, new_list_set_item_op
85 from mypyc.primitives.misc_ops import stop_async_iteration_op
86 from mypyc.primitives.registry import CFunctionDescription
87 from mypyc.primitives.set_ops import set_add_op
88 from mypyc.primitives.str_ops import str_get_item_unsafe_op
89 from mypyc.primitives.tuple_ops import tuple_get_item_unsafe_op
90
91 GenFunc = Callable[[], None]
92
93
94 def for_loop_helper(
95 builder: IRBuilder,
96 index: Lvalue,
97 expr: Expression,
98 body_insts: GenFunc,
99 else_insts: GenFunc | None,
100 is_async: bool,
101 line: int,
102 ) -> None:
103 """Generate IR for a loop.
104
105 Args:
106 index: the loop index Lvalue
107 expr: the expression to iterate over
108 body_insts: a function that generates the body of the loop
109 else_insts: a function that generates the else block instructions
110 """
111 # Body of the loop
112 body_block = BasicBlock()
113 # Block that steps to the next item
114 step_block = BasicBlock()
115 # Block for the else clause, if we need it
116 else_block = BasicBlock()
117 # Block executed after the loop
118 exit_block = BasicBlock()
119
120 # Determine where we want to exit, if our condition check fails.
121 normal_loop_exit = else_block if else_insts is not None else exit_block
122
123 for_gen = make_for_loop_generator(
124 builder, index, expr, body_block, normal_loop_exit, line, is_async=is_async
125 )
126
127 builder.push_loop_stack(step_block, exit_block)
128 condition_block = BasicBlock()
129 builder.goto_and_activate(condition_block)
130
131 # Add loop condition check.
132 for_gen.gen_condition()
133
134 # Generate loop body.
135 builder.activate_block(body_block)
136 for_gen.begin_body()
137 body_insts()
138
139 # We generate a separate step block (which might be empty).
140 builder.goto_and_activate(step_block)
141 for_gen.gen_step()
142 # Go back to loop condition.
143 builder.goto(condition_block)
144
145 for_gen.add_cleanup(normal_loop_exit)
146 builder.pop_loop_stack()
147
148 if else_insts is not None:
149 builder.activate_block(else_block)
150 else_insts()
151 builder.goto(exit_block)
152
153 builder.activate_block(exit_block)
154
155
156 def for_loop_helper_with_index(
157 builder: IRBuilder,
158 index: Lvalue,
159 expr: Expression,
160 expr_reg: Value,
161 body_insts: Callable[[Value], None],
162 line: int,
163 length: Value,
164 ) -> None:
165 """Generate IR for a sequence iteration.
166
167 This function only works for sequence type. Compared to for_loop_helper,
168 it would feed iteration index to body_insts.
169
170 Args:
171 index: the loop index Lvalue
172 expr: the expression to iterate over
173 body_insts: a function that generates the body of the loop.
174 It needs a index as parameter.
175 """
176 assert is_sequence_rprimitive(expr_reg.type) or isinstance(expr_reg.type, RVec), (
177 expr_reg,
178 expr_reg.type,
179 )
180 target_type = builder.get_sequence_type(expr)
181
182 body_block = BasicBlock()
183 step_block = BasicBlock()
184 exit_block = BasicBlock()
185 condition_block = BasicBlock()
186
187 for_gen = ForSequence(builder, index, body_block, exit_block, line, False)
188 for_gen.init(expr_reg, target_type, reverse=False, length=length)
189
190 builder.push_loop_stack(step_block, exit_block)
191
192 if isinstance(length, Integer) and length.value > 0:
193 builder.goto(body_block)
194 builder.activate_block(condition_block)
195 else:
196 builder.goto_and_activate(condition_block)
197
198 for_gen.gen_condition()
199
200 builder.activate_block(body_block)
201 for_gen.begin_body()
202 body_insts(builder.read(for_gen.index_target, line))
203
204 builder.goto_and_activate(step_block)
205 for_gen.gen_step()
206 builder.goto(condition_block)
207
208 for_gen.add_cleanup(exit_block)
209 builder.pop_loop_stack()
210
211 builder.activate_block(exit_block)
212
213
214 def sequence_from_generator_preallocate_helper(
215 builder: IRBuilder,
216 gen: GeneratorExpr,
217 empty_op_llbuilder: Callable[[Value, int], Value],
218 set_item_op: Callable[[Value, Value, Value, int], None],
219 ) -> Value | None:
220 """Generate a new tuple or list from a simple generator expression.
221
222 Currently we only optimize for simplest generator expression, which means that
223 there is no condition list in the generator and only one original sequence with
224 one index is allowed.
225
226 e.g. (1) tuple(f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple)
227 (2) list(f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple)
228 (3) [f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple]
229
230 Args:
231 empty_op_llbuilder: A function that can generate an empty sequence op when
232 passed in length. See `new_list_op_with_length` and `new_tuple_op_with_length`
233 for detailed implementation.
234 set_item_op: A primitive that can modify an arbitrary position of a sequence.
235 The op should have three arguments:
236 - Self
237 - Target position
238 - New Value
239 See `new_list_set_item_op` and `new_tuple_set_item_op` for detailed
240 implementation.
241 """
242 if len(gen.sequences) == 1 and len(gen.indices) == 1 and len(gen.condlists[0]) == 0:
243 line = gen.line
244 sequence_expr = gen.sequences[0]
245 rtype = builder.node_type(sequence_expr)
246 if not (is_sequence_rprimitive(rtype) or isinstance(rtype, (RTuple, RVec))):
247 return None
248
249 if isinstance(rtype, RTuple):
250 # If input is RTuple, box it to tuple_rprimitive for generic iteration
251 # TODO: this can be optimized a bit better with an unrolled ForRTuple helper
252 proper_type = get_proper_type(builder.types[sequence_expr])
253 assert isinstance(proper_type, TupleType), proper_type
254
255 # the for_loop_helper_with_index crashes for empty tuples, bail out
256 if not proper_type.items:
257 return None
258
259 proper_types = get_proper_types(proper_type.items)
260
261 get_item_ops: list[LoadLiteral | TupleGet]
262 if all(isinstance(typ, LiteralType) for typ in proper_types):
263 get_item_ops = [
264 LoadLiteral(cast(LiteralType, typ).value, object_rprimitive)
265 for typ in proper_types
266 ]
267
268 else:
269 sequence = builder.accept(sequence_expr)
270 get_item_ops = [
271 (
272 LoadLiteral(typ.value, object_rprimitive)
273 if isinstance(typ, LiteralType)
274 else TupleGet(sequence, i, line)
275 )
276 for i, typ in enumerate(proper_types)
277 ]
278
279 items = list(map(builder.add, get_item_ops))
280 sequence = builder.new_tuple(items, line)
281
282 else:
283 sequence = builder.accept(sequence_expr)
284
285 length = get_expr_length_value(builder, sequence_expr, sequence, line, use_pyssize_t=True)
286
287 target_op = empty_op_llbuilder(length, line)
288
289 def set_item(item_index: Value) -> None:
290 e = builder.accept(gen.left_expr)
291 set_item_op(target_op, item_index, e, line)
292
293 for_loop_helper_with_index(
294 builder, gen.indices[0], sequence_expr, sequence, set_item, line, length
295 )
296
297 return target_op
298 return None
299
300
301 def translate_list_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value:
302 if raise_error_if_contains_unreachable_names(builder, gen):
303 return builder.none()
304
305 def set_item(x: Value, y: Value, z: Value, line: int) -> None:
306 builder.call_c(new_list_set_item_op, [x, y, z], line)
307
308 # Try simplest list comprehension, otherwise fall back to general one
309 val = sequence_from_generator_preallocate_helper(
310 builder,
311 gen,
312 empty_op_llbuilder=builder.builder.new_list_op_with_length,
313 set_item_op=set_item,
314 )
315 if val is not None:
316 return val
317
318 list_ops = builder.maybe_spill(builder.new_list_op([], gen.line))
319
320 loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))
321
322 def gen_inner_stmts() -> None:
323 e = builder.accept(gen.left_expr)
324 builder.primitive_op(list_append_op, [builder.read(list_ops, gen.line), e], gen.line)
325
326 comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)
327 return builder.read(list_ops, gen.line)
328
329
330 def raise_error_if_contains_unreachable_names(
331 builder: IRBuilder, gen: GeneratorExpr | DictionaryComprehension
332 ) -> bool:
333 """Raise a runtime error and return True if generator contains unreachable names.
334
335 False is returned if the generator can be safely transformed without crashing.
336 (It may still be unreachable!)
337 """
338 if any(isinstance(s, NameExpr) and s.node is None for s in gen.indices):
339 error = RaiseStandardError(
340 RaiseStandardError.RUNTIME_ERROR,
341 "mypyc internal error: should be unreachable",
342 gen.line,
343 )
344 builder.add(error)
345 return True
346
347 return False
348
349
350 def translate_set_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value:
351 if raise_error_if_contains_unreachable_names(builder, gen):
352 return builder.none()
353
354 set_ops = builder.maybe_spill(builder.new_set_op([], gen.line))
355 loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))
356
357 def gen_inner_stmts() -> None:
358 e = builder.accept(gen.left_expr)
359 builder.primitive_op(set_add_op, [builder.read(set_ops, gen.line), e], gen.line)
360
361 comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)
362 return builder.read(set_ops, gen.line)
363
364
365 def translate_vec_comprehension(
366 builder: IRBuilder, vec_type: RVec, gen: GeneratorExpr, *, capacity: Value | None = None
367 ) -> Value:
368 def set_item(x: Value, y: Value, z: Value, line: int) -> None:
369 vec_init_item_unsafe(builder.builder, x, y, z, line)
370
371 # Try simplest comprehension, otherwise fall back to general one
372 val = sequence_from_generator_preallocate_helper(
373 builder,
374 gen,
375 empty_op_llbuilder=lambda length, line: vec_create(
376 builder.builder, vec_type, length, line, capacity=capacity
377 ),
378 set_item_op=set_item,
379 )
380 if val is not None:
381 return val
382
383 vec = Register(vec_type)
384 builder.assign(
385 vec, vec_create(builder.builder, vec_type, 0, gen.line, capacity=capacity), gen.line
386 )
387 loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))
388
389 def gen_inner_stmts() -> None:
390 e = builder.accept(gen.left_expr)
391 builder.assign(vec, vec_append(builder.builder, vec, e, gen.line), gen.line)
392
393 comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)
394 return vec
395
396
397 def comprehension_helper(
398 builder: IRBuilder,
399 loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]],
400 gen_inner_stmts: Callable[[], None],
401 line: int,
402 ) -> None:
403 """Helper function for list comprehensions.
404
405 Args:
406 loop_params: a list of (index, expr, [conditions]) tuples defining nested loops:
407 - "index" is the Lvalue indexing that loop;
408 - "expr" is the expression for the object to be iterated over;
409 - "conditions" is a list of conditions, evaluated in order with short-circuiting,
410 that must all be true for the loop body to be executed
411 gen_inner_stmts: function to generate the IR for the body of the innermost loop
412 """
413
414 def handle_loop(loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]]) -> None:
415 """Generate IR for a loop.
416
417 Given a list of (index, expression, [conditions]) tuples, generate IR
418 for the nested loops the list defines.
419 """
420 index, expr, conds, is_async = loop_params[0]
421 for_loop_helper(
422 builder,
423 index,
424 expr,
425 lambda: loop_contents(conds, loop_params[1:]),
426 None,
427 is_async=is_async,
428 line=line,
429 )
430
431 def loop_contents(
432 conds: list[Expression],
433 remaining_loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]],
434 ) -> None:
435 """Generate the body of the loop.
436
437 Args:
438 conds: a list of conditions to be evaluated (in order, with short circuiting)
439 to gate the body of the loop
440 remaining_loop_params: the parameters for any further nested loops; if it's empty
441 we'll instead evaluate the "gen_inner_stmts" function
442 """
443 # Check conditions, in order, short circuiting them.
444 for cond in conds:
445 cond_val = builder.accept(cond)
446 cont_block, rest_block = BasicBlock(), BasicBlock()
447 # If the condition is true we'll skip the continue.
448 builder.add_bool_branch(cond_val, rest_block, cont_block)
449 builder.activate_block(cont_block)
450 builder.nonlocal_control[-1].gen_continue(builder, cond.line)
451 builder.goto_and_activate(rest_block)
452
453 if remaining_loop_params:
454 # There's another nested level, so the body of this loop is another loop.
455 return handle_loop(remaining_loop_params)
456 else:
457 # We finally reached the actual body of the generator.
458 # Generate the IR for the inner loop body.
459 gen_inner_stmts()
460
461 handle_loop(loop_params)
462
463
464 def is_range_ref(expr: RefExpr) -> bool:
465 return (
466 expr.fullname == "builtins.range"
467 or isinstance(expr.node, TypeAlias)
468 and expr.fullname == "six.moves.xrange"
469 )
470
471
472 def make_for_loop_generator(
473 builder: IRBuilder,
474 index: Lvalue,
475 expr: Expression,
476 body_block: BasicBlock,
477 loop_exit: BasicBlock,
478 line: int,
479 is_async: bool = False,
480 nested: bool = False,
481 ) -> ForGenerator:
482 """Return helper object for generating a for loop over an iterable.
483
484 If "nested" is True, this is a nested iterator such as "e" in "enumerate(e)".
485 """
486
487 # Do an async loop if needed. async is always generic
488 if is_async:
489 expr_reg = builder.accept(expr)
490 async_obj = ForAsyncIterable(builder, index, body_block, loop_exit, line, nested)
491 item_type = builder._analyze_iterable_item_type(expr)
492 item_rtype = builder.type_to_rtype(item_type)
493 async_obj.init(expr_reg, item_rtype)
494 return async_obj
495
496 rtyp = builder.node_type(expr)
497 if is_sequence_rprimitive(rtyp) or isinstance(rtyp, RVec):
498 # Special case "for x in <seq>" for concrete sequence types.
499 expr_reg = builder.accept(expr)
500 target_type = builder.get_sequence_type(expr)
501
502 for_list = ForSequence(builder, index, body_block, loop_exit, line, nested)
503 for_list.init(expr_reg, target_type, reverse=False)
504 return for_list
505
506 if is_dict_rprimitive(rtyp):
507 # Special case "for k in <dict>".
508 expr_reg = builder.accept(expr)
509 target_type = builder.get_dict_key_type(expr)
510
511 for_dict = ForDictionaryKeys(builder, index, body_block, loop_exit, line, nested)
512 for_dict.init(expr_reg, target_type)
513 return for_dict
514
515 if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr):
516 if (
517 is_range_ref(expr.callee)
518 and (
519 len(expr.args) <= 2
520 or (len(expr.args) == 3 and builder.extract_int(expr.args[2]) is not None)
521 )
522 and set(expr.arg_kinds) == {ARG_POS}
523 ):
524 # Special case "for x in range(...)".
525 # We support the 3 arg form but only for int literals, since it doesn't
526 # seem worth the hassle of supporting dynamically determining which
527 # direction of comparison to do.
528 if len(expr.args) == 1:
529 start_reg: Value = Integer(0)
530 end_reg = builder.accept(expr.args[0])
531 else:
532 start_reg = builder.accept(expr.args[0])
533 end_reg = builder.accept(expr.args[1])
534 if len(expr.args) == 3:
535 step = builder.extract_int(expr.args[2])
536 assert step is not None
537 if step == 0:
538 builder.error("range() step can't be zero", expr.args[2].line)
539 else:
540 step = 1
541
542 for_range = ForRange(builder, index, body_block, loop_exit, line, nested)
543 for_range.init(start_reg, end_reg, step)
544 return for_range
545
546 elif (
547 expr.callee.fullname == "builtins.enumerate"
548 and len(expr.args) == 1
549 and expr.arg_kinds == [ARG_POS]
550 and isinstance(index, TupleExpr)
551 and len(index.items) == 2
552 ):
553 # Special case "for i, x in enumerate(y)".
554 lvalue1 = index.items[0]
555 lvalue2 = index.items[1]
556 for_enumerate = ForEnumerate(builder, index, body_block, loop_exit, line, nested)
557 for_enumerate.init(lvalue1, lvalue2, expr.args[0])
558 return for_enumerate
559
560 elif (
561 expr.callee.fullname == "builtins.zip"
562 and len(expr.args) >= 2
563 and set(expr.arg_kinds) == {ARG_POS}
564 and isinstance(index, TupleExpr)
565 and len(index.items) == len(expr.args)
566 ):
567 # Special case "for x, y in zip(a, b)".
568 for_zip = ForZip(builder, index, body_block, loop_exit, line, nested)
569 for_zip.init(index.items, expr.args)
570 return for_zip
571
572 if (
573 expr.callee.fullname == "builtins.reversed"
574 and len(expr.args) == 1
575 and expr.arg_kinds == [ARG_POS]
576 and is_sequence_rprimitive(builder.node_type(expr.args[0]))
577 ):
578 # Special case "for x in reversed(<list>)".
579 expr_reg = builder.accept(expr.args[0])
580 target_type = builder.get_sequence_type(expr)
581
582 for_list = ForSequence(builder, index, body_block, loop_exit, line, nested)
583 for_list.init(expr_reg, target_type, reverse=True)
584 return for_list
585 if isinstance(expr, CallExpr) and isinstance(expr.callee, MemberExpr) and not expr.args:
586 # Special cases for dictionary iterator methods, like dict.items().
587 rtype = builder.node_type(expr.callee.expr)
588 if is_dict_rprimitive(rtype) and expr.callee.name in ("keys", "values", "items"):
589 expr_reg = builder.accept(expr.callee.expr)
590 for_dict_type: type[ForGenerator] | None = None
591 if expr.callee.name == "keys":
592 target_type = builder.get_dict_key_type(expr.callee.expr)
593 for_dict_type = ForDictionaryKeys
594 elif expr.callee.name == "values":
595 target_type = builder.get_dict_value_type(expr.callee.expr)
596 for_dict_type = ForDictionaryValues
597 else:
598 target_type = builder.get_dict_item_type(expr.callee.expr)
599 for_dict_type = ForDictionaryItems
600 for_dict_gen = for_dict_type(builder, index, body_block, loop_exit, line, nested)
601 for_dict_gen.init(expr_reg, target_type)
602 return for_dict_gen
603
604 iterable_expr_reg: Value | None = None
605 if isinstance(expr, SetExpr):
606 # Special case "for x in <set literal>".
607 from mypyc.irbuild.expression import precompute_set_literal
608
609 set_literal = precompute_set_literal(builder, expr)
610 if set_literal is not None:
611 iterable_expr_reg = set_literal
612
613 # Default to a generic for loop.
614 if iterable_expr_reg is None:
615 iterable_expr_reg = builder.accept(expr)
616
617 it = iterable_expr_reg.type
618 for_obj: ForNativeGenerator | ForIterable
619 if isinstance(it, RInstance) and it.class_ir.has_method(GENERATOR_HELPER_NAME):
620 # Directly call generator object methods if iterating over a native generator.
621 for_obj = ForNativeGenerator(builder, index, body_block, loop_exit, line, nested)
622 else:
623 # Generic implementation that works of arbitrary iterables.
624 for_obj = ForIterable(builder, index, body_block, loop_exit, line, nested)
625 item_type = builder._analyze_iterable_item_type(expr)
626 item_rtype = builder.type_to_rtype(item_type)
627 for_obj.init(iterable_expr_reg, item_rtype)
628 return for_obj
629
630
631 class ForGenerator:
632 """Abstract base class for generating for loops."""
633
634 def __init__(
635 self,
636 builder: IRBuilder,
637 index: Lvalue,
638 body_block: BasicBlock,
639 loop_exit: BasicBlock,
640 line: int,
641 nested: bool,
642 ) -> None:
643 self.builder = builder
644 self.index = index
645 self.body_block = body_block
646 self.line = line
647 # Some for loops need a cleanup block that we execute at exit. We
648 # create a cleanup block if needed. However, if we are generating a for
649 # loop for a nested iterator, such as "e" in "enumerate(e)", the
650 # outermost generator should generate the cleanup block -- we don't
651 # need to do it here.
652 if self.need_cleanup() and not nested:
653 # Create a new block to handle cleanup after loop exit.
654 self.loop_exit = BasicBlock()
655 else:
656 # Just use the existing loop exit block.
657 self.loop_exit = loop_exit
658
659 def need_cleanup(self) -> bool:
660 """If this returns true, we need post-loop cleanup."""
661 return False
662
663 def add_cleanup(self, exit_block: BasicBlock) -> None:
664 """Add post-loop cleanup, if needed."""
665 if self.need_cleanup():
666 self.builder.activate_block(self.loop_exit)
667 self.gen_cleanup()
668 self.builder.goto(exit_block)
669
670 def gen_condition(self) -> None:
671 """Generate check for loop exit (e.g. exhaustion of iteration)."""
672
673 def begin_body(self) -> None:
674 """Generate ops at the beginning of the body (if needed)."""
675
676 def gen_step(self) -> None:
677 """Generate stepping to the next item (if needed)."""
678
679 def gen_cleanup(self) -> None:
680 """Generate post-loop cleanup (if needed)."""
681
682 def load_len(self, expr: Value | AssignmentTarget) -> Value:
683 """A helper to get collection length, used by several subclasses."""
684 return self.builder.builder.builtin_len(
685 self.builder.read(expr, self.line), self.line, use_pyssize_t=True
686 )
687
688
689 class ForIterable(ForGenerator):
690 """Generate IR for a for loop over an arbitrary iterable (the general case)."""
691
692 def need_cleanup(self) -> bool:
693 # Create a new cleanup block for when the loop is finished.
694 return True
695
696 def init(self, expr_reg: Value, target_type: RType) -> None:
697 # Define targets to contain the expression, along with the iterator that will be used
698 # for the for-loop. If we are inside of a generator function, spill these into the
699 # environment class.
700 builder = self.builder
701 iter_reg = builder.primitive_op(iter_op, [expr_reg], self.line)
702 builder.maybe_spill(expr_reg)
703 self.iter_target = builder.maybe_spill(iter_reg)
704 self.target_type = target_type
705
706 def gen_condition(self) -> None:
707 # We call __next__ on the iterator and check to see if the return value
708 # is NULL, which signals either the end of the Iterable being traversed
709 # or an exception being raised. Note that Branch.IS_ERROR checks only
710 # for NULL (an exception does not necessarily have to be raised).
711 builder = self.builder
712 line = self.line
713 self.next_reg = builder.call_c(next_op, [builder.read(self.iter_target, line)], line)
714 builder.add(Branch(self.next_reg, self.loop_exit, self.body_block, Branch.IS_ERROR))
715
716 def begin_body(self) -> None:
717 # Assign the value obtained from __next__ to the
718 # lvalue so that it can be referenced by code in the body of the loop.
719 builder = self.builder
720 line = self.line
721 # We unbox here so that iterating with tuple unpacking generates a tuple based
722 # unpack instead of an iterator based one.
723 next_reg = builder.coerce(self.next_reg, self.target_type, line)
724 builder.assign(builder.get_assignment_target(self.index), next_reg, line)
725
726 def gen_step(self) -> None:
727 # Nothing to do here, since we get the next item as part of gen_condition().
728 pass
729
730 def gen_cleanup(self) -> None:
731 # We set the branch to go here if the conditional evaluates to true. If
732 # an exception was raised during the loop, then err_reg will be set to
733 # True. If no_err_occurred_op returns False, then the exception will be
734 # propagated using the ERR_FALSE flag.
735 self.builder.call_c(no_err_occurred_op, [], self.line)
736
737
738 class ForNativeGenerator(ForGenerator):
739 """Generate IR for a for loop over a native generator."""
740
741 def need_cleanup(self) -> bool:
742 # Create a new cleanup block for when the loop is finished.
743 return True
744
745 def init(self, expr_reg: Value, target_type: RType) -> None:
746 # Define target to contains the generator expression. It's also the iterator.
747 # If we are inside a generator function, spill these into the environment class.
748 builder = self.builder
749 self.iter_target = builder.maybe_spill(expr_reg)
750 self.target_type = target_type
751
752 def gen_condition(self) -> None:
753 builder = self.builder
754 line = self.line
755 self.return_value = Register(object_rprimitive)
756 err = builder.add(LoadErrorValue(object_rprimitive, undefines=True))
757 builder.assign(self.return_value, err, line)
758
759 # Call generated generator helper method, passing a PyObject ** as the final
760 # argument that will be used to store the return value in the return value
761 # register. We ignore the return value but the presence of a return value
762 # indicates that the generator has finished. This is faster than raising
763 # and catching StopIteration, which is the non-native way of doing this.
764 ptr = builder.add(LoadAddress(object_pointer_rprimitive, self.return_value))
765 nn = builder.none_object()
766 helper_call = MethodCall(
767 builder.read(self.iter_target, line),
768 GENERATOR_HELPER_NAME,
769 [nn, nn, nn, nn, ptr],
770 line,
771 )
772 # We provide custom handling for error values.
773 helper_call.error_kind = ERR_NEVER
774
775 self.next_reg = builder.add(helper_call)
776 builder.add(Branch(self.next_reg, self.loop_exit, self.body_block, Branch.IS_ERROR))
777
778 def begin_body(self) -> None:
779 # Assign the value obtained from the generator helper method to the
780 # lvalue so that it can be referenced by code in the body of the loop.
781 builder = self.builder
782 line = self.line
783 # We unbox here so that iterating with tuple unpacking generates a tuple based
784 # unpack instead of an iterator based one.
785 next_reg = builder.coerce(self.next_reg, self.target_type, line)
786 builder.assign(builder.get_assignment_target(self.index), next_reg, line)
787
788 def gen_step(self) -> None:
789 # Nothing to do here, since we get the next item as part of gen_condition().
790 pass
791
792 def gen_cleanup(self) -> None:
793 # If return value is NULL (it wasn't assigned to by the generator helper method),
794 # an exception was raised that we need to propagate.
795 self.builder.primitive_op(propagate_if_error_op, [self.return_value], self.line)
796
797
798 class ForAsyncIterable(ForGenerator):
799 """Generate IR for an async for loop."""
800
801 def init(self, expr_reg: Value, target_type: RType) -> None:
802 # Define targets to contain the expression, along with the
803 # iterator that will be used for the for-loop. We are inside
804 # of a generator function, so we will spill these into
805 # environment class.
806 builder = self.builder
807 iter_reg = builder.call_c(aiter_op, [expr_reg], self.line)
808 builder.maybe_spill(expr_reg)
809 self.iter_target = builder.maybe_spill(iter_reg)
810 self.target_type = target_type
811 self.stop_reg = Register(bool_rprimitive)
812
813 def gen_condition(self) -> None:
814 # This does the test and fetches the next value
815 # try:
816 # TARGET = await type(iter).__anext__(iter)
817 # stop = False
818 # except StopAsyncIteration:
819 # stop = True
820 #
821 # What a pain.
822 # There are optimizations available here if we punch through some abstractions.
823
824 from mypyc.irbuild.statement import emit_await, transform_try_except
825
826 builder = self.builder
827 line = self.line
828
829 def except_match() -> Value:
830 return builder.add(
831 LoadGlobal(stop_async_iteration_op.type, stop_async_iteration_op.src, line)
832 )
833
834 def try_body() -> None:
835 awaitable = builder.call_c(anext_op, [builder.read(self.iter_target, line)], line)
836 self.next_reg = emit_await(builder, awaitable, line)
837 builder.assign(self.stop_reg, builder.false(), line)
838
839 def except_body() -> None:
840 builder.assign(self.stop_reg, builder.true(), line)
841
842 transform_try_except(
843 builder, try_body, [((except_match, line), None, except_body)], None, line
844 )
845
846 builder.add(Branch(self.stop_reg, self.loop_exit, self.body_block, Branch.BOOL))
847
848 def begin_body(self) -> None:
849 # Assign the value obtained from await __anext__ to the
850 # lvalue so that it can be referenced by code in the body of the loop.
851 builder = self.builder
852 line = self.line
853 # We unbox here so that iterating with tuple unpacking generates a tuple based
854 # unpack instead of an iterator based one.
855 next_reg = builder.coerce(self.next_reg, self.target_type, line)
856 builder.assign(builder.get_assignment_target(self.index), next_reg, line)
857
858 def gen_step(self) -> None:
859 # Nothing to do here, since we get the next item as part of gen_condition().
860 pass
861
862
863 def unsafe_index(builder: IRBuilder, target: Value, index: Value, line: int) -> Value:
864 """Emit a potentially unsafe index into a target."""
865 # This doesn't really fit nicely into any of our data-driven frameworks
866 # since we want to use __getitem__ if we don't have an unsafe version,
867 # so we just check manually.
868 if is_list_rprimitive(target.type):
869 return builder.primitive_op(list_get_item_unsafe_op, [target, index], line)
870 elif is_tuple_rprimitive(target.type):
871 return builder.call_c(tuple_get_item_unsafe_op, [target, index], line)
872 elif is_str_rprimitive(target.type):
873 return builder.call_c(str_get_item_unsafe_op, [target, index], line)
874 elif isinstance(target.type, RVec):
875 return vec_get_item_unsafe(builder.builder, target, index, line)
876 else:
877 return builder.gen_method_call(target, "__getitem__", [index], None, line)
878
879
880 class ForSequence(ForGenerator):
881 """Generate optimized IR for a for loop over a sequence.
882
883 Supports iterating in both forward and reverse.
884 """
885
886 length_reg: Value | AssignmentTarget | None
887
888 def init(
889 self, expr_reg: Value, target_type: RType, reverse: bool, length: Value | None = None
890 ) -> None:
891 assert is_sequence_rprimitive(expr_reg.type) or isinstance(expr_reg.type, RVec), (
892 expr_reg,
893 expr_reg.type,
894 )
895 builder = self.builder
896 # Record a Value indicating the length of the sequence, if known at compile time.
897 self.length = length
898 self.reverse = reverse
899 # Define target to contain the expression, along with the index that will be used
900 # for the for-loop. If we are inside of a generator function, spill these into the
901 # environment class.
902 self.expr_target = builder.maybe_spill(expr_reg)
903 if is_immutable_rprimitive(expr_reg.type):
904 # If the expression is an immutable type, we can load the length just once.
905 self.length_reg = builder.maybe_spill(self.length or self.load_len(self.expr_target))
906 else:
907 # Otherwise, even if the length is known, we must recalculate the length
908 # at every iteration for compatibility with python semantics.
909 self.length_reg = None
910 if not reverse:
911 index_reg: Value = Integer(0, c_pyssize_t_rprimitive)
912 else:
913 if self.length_reg is not None:
914 len_val = builder.read(self.length_reg, self.line)
915 else:
916 len_val = self.load_len(self.expr_target)
917 index_reg = builder.builder.int_sub(len_val, 1)
918 self.index_target = builder.maybe_spill_assignable(index_reg)
919 self.target_type = target_type
920
921 def gen_condition(self) -> None:
922 builder = self.builder
923 line = self.line
924 if self.reverse:
925 # If we are iterating in reverse order, we obviously need
926 # to check that the index is still positive. Somewhat less
927 # obviously we still need to check against the length,
928 # since it could shrink out from under us.
929 comparison = builder.binary_op(
930 builder.read(self.index_target, line), Integer(0), ">=", line
931 )
932 second_check = BasicBlock()
933 builder.add_bool_branch(comparison, second_check, self.loop_exit)
934 builder.activate_block(second_check)
935 if self.length_reg is None:
936 # For compatibility with python semantics we recalculate the length
937 # at every iteration.
938 len_reg = self.load_len(self.expr_target)
939 else:
940 # (unless input is immutable type).
941 len_reg = builder.read(self.length_reg, line)
942 comparison = builder.binary_op(builder.read(self.index_target, line), len_reg, "<", line)
943 builder.add_bool_branch(comparison, self.body_block, self.loop_exit)
944
945 def begin_body(self) -> None:
946 builder = self.builder
947 line = self.line
948 # Read the next list item.
949 value_box = unsafe_index(
950 builder,
951 builder.read(self.expr_target, line),
952 builder.read(self.index_target, line),
953 line,
954 )
955 assert value_box
956 # We coerce to the type of list elements here so that
957 # iterating with tuple unpacking generates a tuple based
958 # unpack instead of an iterator based one.
959 builder.assign(
960 builder.get_assignment_target(self.index),
961 builder.coerce(value_box, self.target_type, line),
962 line,
963 )
964
965 def gen_step(self) -> None:
966 # Step to the next item.
967 builder = self.builder
968 line = self.line
969 step = 1 if not self.reverse else -1
970 add = builder.builder.int_add(builder.read(self.index_target, line), step)
971 builder.assign(self.index_target, add, line)
972
973
974 class ForDictionaryCommon(ForGenerator):
975 """Generate optimized IR for a for loop over dictionary keys/values.
976
977 The logic is pretty straightforward, we use PyDict_Next() API wrapped in
978 a tuple, so that we can modify only a single register. The layout of the tuple:
979 * f0: are there more items (bool)
980 * f1: current offset (int)
981 * f2: next key (object)
982 * f3: next value (object)
983 For more info see https://docs.python.org/3/c-api/dict.html#c.PyDict_Next.
984
985 Note that for subclasses we fall back to generic PyObject_GetIter() logic,
986 since they may override some iteration methods in subtly incompatible manner.
987 The fallback logic is implemented in CPy.h via dynamic type check.
988 """
989
990 dict_next_op: ClassVar[CFunctionDescription]
991 dict_iter_op: ClassVar[CFunctionDescription]
992
993 def need_cleanup(self) -> bool:
994 # Technically, a dict subclass can raise an unrelated exception
995 # in __next__(), so we need this.
996 return True
997
998 def init(self, expr_reg: Value, target_type: RType) -> None:
999 builder = self.builder
1000 self.target_type = target_type
1001
1002 # We add some variables to environment class, so they can be read across yield.
1003 self.expr_target = builder.maybe_spill(expr_reg)
1004 offset = Integer(0)
1005 self.offset_target = builder.maybe_spill_assignable(offset)
1006 self.size = builder.maybe_spill(self.load_len(self.expr_target))
1007
1008 # For dict class (not a subclass) this is the dictionary itself.
1009 iter_reg = builder.call_c(self.dict_iter_op, [expr_reg], self.line)
1010 self.iter_target = builder.maybe_spill(iter_reg)
1011
1012 def gen_condition(self) -> None:
1013 """Get next key/value pair, set new offset, and check if we should continue."""
1014 builder = self.builder
1015 line = self.line
1016 self.next_tuple = self.builder.call_c(
1017 self.dict_next_op,
1018 [builder.read(self.iter_target, line), builder.read(self.offset_target, line)],
1019 line,
1020 )
1021
1022 # Do this here instead of in gen_step() to minimize variables in environment.
1023 new_offset = builder.add(TupleGet(self.next_tuple, 1, line))
1024 builder.assign(self.offset_target, new_offset, line)
1025
1026 should_continue = builder.add(TupleGet(self.next_tuple, 0, line))
1027 builder.add(Branch(should_continue, self.body_block, self.loop_exit, Branch.BOOL))
1028
1029 def gen_step(self) -> None:
1030 """Check that dictionary didn't change size during iteration.
1031
1032 Raise RuntimeError if it is not the case to match CPython behavior.
1033 """
1034 builder = self.builder
1035 line = self.line
1036 # Technically, we don't need a new primitive for this, but it is simpler.
1037 builder.call_c(
1038 dict_check_size_op,
1039 [builder.read(self.expr_target, line), builder.read(self.size, line)],
1040 line,
1041 )
1042
1043 def gen_cleanup(self) -> None:
1044 # Same as for generic ForIterable.
1045 self.builder.call_c(no_err_occurred_op, [], self.line)
1046
1047
1048 class ForDictionaryKeys(ForDictionaryCommon):
1049 """Generate optimized IR for a for loop over dictionary keys."""
1050
1051 dict_next_op = dict_next_key_op
1052 dict_iter_op = dict_key_iter_op
1053
1054 def begin_body(self) -> None:
1055 builder = self.builder
1056 line = self.line
1057
1058 # Key is stored at the third place in the tuple.
1059 key = builder.add(TupleGet(self.next_tuple, 2, line))
1060 builder.assign(
1061 builder.get_assignment_target(self.index),
1062 builder.coerce(key, self.target_type, line),
1063 line,
1064 )
1065
1066
1067 class ForDictionaryValues(ForDictionaryCommon):
1068 """Generate optimized IR for a for loop over dictionary values."""
1069
1070 dict_next_op = dict_next_value_op
1071 dict_iter_op = dict_value_iter_op
1072
1073 def begin_body(self) -> None:
1074 builder = self.builder
1075 line = self.line
1076
1077 # Value is stored at the third place in the tuple.
1078 value = builder.add(TupleGet(self.next_tuple, 2, line))
1079 builder.assign(
1080 builder.get_assignment_target(self.index),
1081 builder.coerce(value, self.target_type, line),
1082 line,
1083 )
1084
1085
1086 class ForDictionaryItems(ForDictionaryCommon):
1087 """Generate optimized IR for a for loop over dictionary items."""
1088
1089 dict_next_op = dict_next_item_op
1090 dict_iter_op = dict_item_iter_op
1091
1092 def begin_body(self) -> None:
1093 builder = self.builder
1094 line = self.line
1095
1096 key = builder.add(TupleGet(self.next_tuple, 2, line))
1097 value = builder.add(TupleGet(self.next_tuple, 3, line))
1098
1099 # Coerce just in case e.g. key is itself a tuple to be unpacked.
1100 assert isinstance(self.target_type, RTuple), self.target_type
1101 key = builder.coerce(key, self.target_type.types[0], line)
1102 value = builder.coerce(value, self.target_type.types[1], line)
1103
1104 target = builder.get_assignment_target(self.index)
1105 if isinstance(target, AssignmentTargetTuple):
1106 # Simpler code for common case: for k, v in d.items().
1107 if len(target.items) != 2:
1108 builder.error("Expected a pair for dict item iteration", line)
1109 builder.assign(target.items[0], key, line)
1110 builder.assign(target.items[1], value, line)
1111 else:
1112 rvalue = builder.add(TupleSet([key, value], line))
1113 builder.assign(target, rvalue, line)
1114
1115
1116 class ForRange(ForGenerator):
1117 """Generate optimized IR for a for loop over an integer range."""
1118
1119 def init(self, start_reg: Value, end_reg: Value, step: int) -> None:
1120 builder = self.builder
1121 self.start_reg = start_reg
1122 self.end_reg = end_reg
1123 self.step = step
1124 self.end_target = builder.maybe_spill(end_reg)
1125 if is_short_int_rprimitive(start_reg.type) and is_short_int_rprimitive(end_reg.type):
1126 index_type: RType = short_int_rprimitive
1127 elif is_fixed_width_rtype(end_reg.type):
1128 index_type = end_reg.type
1129 else:
1130 index_type = int_rprimitive
1131 index_reg = Register(index_type, line=self.line)
1132 builder.assign(index_reg, start_reg, self.line)
1133 self.index_reg = builder.maybe_spill_assignable(index_reg)
1134 # Initialize loop index to 0. Assert that the index target is assignable.
1135 self.index_target: Register | AssignmentTarget = builder.get_assignment_target(self.index)
1136 builder.assign(self.index_target, builder.read(self.index_reg, self.line), self.line)
1137
1138 def gen_condition(self) -> None:
1139 builder = self.builder
1140 line = self.line
1141 # Add loop condition check.
1142 cmp = "<" if self.step > 0 else ">"
1143 comparison = builder.binary_op(
1144 builder.read(self.index_reg, line), builder.read(self.end_target, line), cmp, line
1145 )
1146 builder.add_bool_branch(comparison, self.body_block, self.loop_exit)
1147
1148 def begin_body(self) -> None:
1149 # Update the user-visible loop variable at the start of the body,
1150 # after the condition check passes. This ensures the variable isn't
1151 # "overshot" when the loop exits (matching CPython semantics).
1152 builder = self.builder
1153 builder.assign(self.index_target, builder.read(self.index_reg, self.line), self.line)
1154
1155 def gen_step(self) -> None:
1156 builder = self.builder
1157 line = self.line
1158
1159 # Increment index register. If the range is known to fit in short ints, use
1160 # short ints.
1161 if is_short_int_rprimitive(self.start_reg.type) and is_short_int_rprimitive(
1162 self.end_reg.type
1163 ):
1164 new_val = builder.int_op(
1165 short_int_rprimitive,
1166 builder.read(self.index_reg, line),
1167 Integer(self.step),
1168 IntOp.ADD,
1169 line,
1170 )
1171
1172 else:
1173 new_val = builder.binary_op(
1174 builder.read(self.index_reg, line), Integer(self.step), "+", line
1175 )
1176 builder.assign(self.index_reg, new_val, line)
1177
1178
1179 class ForInfiniteCounter(ForGenerator):
1180 """Generate optimized IR for a for loop counting from 0 to infinity."""
1181
1182 def init(self) -> None:
1183 builder = self.builder
1184 # Create a register to store the state of the loop index and
1185 # initialize this register along with the loop index to 0.
1186 zero = Integer(0)
1187 self.index_reg = builder.maybe_spill_assignable(zero)
1188 self.index_target: Register | AssignmentTarget = builder.get_assignment_target(self.index)
1189
1190 def gen_step(self) -> None:
1191 builder = self.builder
1192 line = self.line
1193 # We can safely assume that the integer is short, since we are not going to wrap
1194 # around a 63-bit integer.
1195 # NOTE: This would be questionable if short ints could be 32 bits.
1196 new_val = builder.int_op(
1197 short_int_rprimitive, builder.read(self.index_reg, line), Integer(1), IntOp.ADD, line
1198 )
1199 builder.assign(self.index_reg, new_val, line)
1200
1201 def begin_body(self) -> None:
1202 self.builder.assign(
1203 self.index_target, self.builder.read(self.index_reg, self.line), self.line
1204 )
1205
1206
1207 class ForEnumerate(ForGenerator):
1208 """Generate optimized IR for a for loop of form "for i, x in enumerate(it)"."""
1209
1210 def need_cleanup(self) -> bool:
1211 # The wrapped for loop might need cleanup. This might generate a
1212 # redundant cleanup block, but that's okay.
1213 return True
1214
1215 def init(self, index1: Lvalue, index2: Lvalue, expr: Expression) -> None:
1216 # Count from 0 to infinity (for the index lvalue).
1217 self.index_gen = ForInfiniteCounter(
1218 self.builder, index1, self.body_block, self.loop_exit, self.line, nested=True
1219 )
1220 self.index_gen.init()
1221 # Iterate over the actual iterable.
1222 self.main_gen = make_for_loop_generator(
1223 self.builder, index2, expr, self.body_block, self.loop_exit, self.line, nested=True
1224 )
1225
1226 def gen_condition(self) -> None:
1227 # No need for a check for the index generator, since it's unconditional.
1228 self.main_gen.gen_condition()
1229
1230 def begin_body(self) -> None:
1231 self.index_gen.begin_body()
1232 self.main_gen.begin_body()
1233
1234 def gen_step(self) -> None:
1235 self.index_gen.gen_step()
1236 self.main_gen.gen_step()
1237
1238 def gen_cleanup(self) -> None:
1239 self.index_gen.gen_cleanup()
1240 self.main_gen.gen_cleanup()
1241
1242
1243 class ForZip(ForGenerator):
1244 """Generate IR for a for loop of form `for x, ... in zip(a, ...)`."""
1245
1246 def need_cleanup(self) -> bool:
1247 # The wrapped for loops might need cleanup. We might generate a
1248 # redundant cleanup block, but that's okay.
1249 return True
1250
1251 def init(self, indexes: list[Lvalue], exprs: list[Expression]) -> None:
1252 assert len(indexes) == len(exprs)
1253 # Condition check will require multiple basic blocks, since there will be
1254 # multiple conditions to check.
1255 self.cond_blocks = [BasicBlock() for _ in range(len(indexes) - 1)] + [self.body_block]
1256 self.gens: list[ForGenerator] = []
1257 for index, expr, next_block in zip(indexes, exprs, self.cond_blocks):
1258 gen = make_for_loop_generator(
1259 self.builder, index, expr, next_block, self.loop_exit, self.line, nested=True
1260 )
1261 self.gens.append(gen)
1262
1263 def gen_condition(self) -> None:
1264 for i, gen in enumerate(self.gens):
1265 gen.gen_condition()
1266 if i < len(self.gens) - 1:
1267 self.builder.activate_block(self.cond_blocks[i])
1268
1269 def begin_body(self) -> None:
1270 for gen in self.gens:
1271 gen.begin_body()
1272
1273 def gen_step(self) -> None:
1274 for gen in self.gens:
1275 gen.gen_step()
1276
1277 def gen_cleanup(self) -> None:
1278 for gen in self.gens:
1279 gen.gen_cleanup()
1280
1281
1282 def get_expr_length(builder: IRBuilder, expr: Expression) -> int | None:
1283 folded = constant_fold_expr(builder, expr)
1284 if isinstance(folded, (str, bytes)):
1285 return len(folded)
1286 elif isinstance(expr, (ListExpr, TupleExpr)):
1287 # if there are no star expressions, or we know the length of them,
1288 # we know the length of the expression
1289 stars = [get_expr_length(builder, i) for i in expr.items if isinstance(i, StarExpr)]
1290 if None not in stars:
1291 other = sum(not isinstance(i, StarExpr) for i in expr.items)
1292 return other + sum(stars) # type: ignore [arg-type]
1293 elif isinstance(expr, StarExpr):
1294 return get_expr_length(builder, expr.expr)
1295 elif (
1296 isinstance(expr, RefExpr)
1297 and isinstance(expr.node, Var)
1298 and expr.node.is_final
1299 and isinstance(expr.node.final_value, str)
1300 and expr.node.has_explicit_value
1301 ):
1302 return len(expr.node.final_value)
1303 elif (
1304 isinstance(expr, CallExpr)
1305 and isinstance(callee := expr.callee, NameExpr)
1306 and all(kind == ARG_POS for kind in expr.arg_kinds)
1307 ):
1308 fullname = callee.fullname
1309 if (
1310 fullname
1311 in (
1312 "builtins.list",
1313 "builtins.tuple",
1314 "builtins.enumerate",
1315 "builtins.sorted",
1316 "builtins.reversed",
1317 )
1318 and len(expr.args) == 1
1319 ):
1320 return get_expr_length(builder, expr.args[0])
1321 elif fullname == "builtins.map" and len(expr.args) == 2:
1322 return get_expr_length(builder, expr.args[1])
1323 elif fullname == "builtins.zip" and expr.args:
1324 arg_lengths = [get_expr_length(builder, arg) for arg in expr.args]
1325 if all(arg is not None for arg in arg_lengths):
1326 return min(arg_lengths) # type: ignore [type-var]
1327 elif fullname == "builtins.range" and len(expr.args) <= 3:
1328 folded_args = [constant_fold_expr(builder, arg) for arg in expr.args]
1329 if all(isinstance(arg, int) for arg in folded_args):
1330 try:
1331 return len(range(*cast(list[int], folded_args)))
1332 except ValueError: # prevent crash if invalid args
1333 pass
1334
1335 # TODO: extend this, passing length of listcomp and genexp should have worthwhile
1336 # performance boost and can be (sometimes) figured out pretty easily. set and dict
1337 # comps *can* be done as well but will need special logic to consider the possibility
1338 # of key conflicts.
1339
1340 # we might still be able to get the length directly from the type
1341 rtype = builder.node_type(expr)
1342 if isinstance(rtype, RTuple):
1343 return len(rtype.types)
1344 return None
1345
1346
1347 def get_expr_length_value(
1348 builder: IRBuilder, expr: Expression, expr_reg: Value, line: int, use_pyssize_t: bool
1349 ) -> Value:
1350 rtype = builder.node_type(expr)
1351 assert is_sequence_rprimitive(rtype) or isinstance(rtype, (RTuple, RVec)), rtype
1352 length = get_expr_length(builder, expr)
1353 if length is None:
1354 # We cannot compute the length at compile time, so we will fetch it.
1355 return builder.builder.builtin_len(expr_reg, line, use_pyssize_t=use_pyssize_t)
1356 # The expression result is known at compile time, so we can use a constant.
1357 return Integer(length, c_pyssize_t_rprimitive if use_pyssize_t else short_int_rprimitive)