Debian Codegraph @

mypyc/irbuild/expression.py

raw
1 """Transform mypy expression ASTs to mypyc IR (Intermediate Representation).
2
3 The top-level AST transformation logic is implemented in mypyc.irbuild.visitor
4 and mypyc.irbuild.builder.
5 """
6
7 from __future__ import annotations
8
9 import math
10 from collections.abc import Callable, Sequence
11
12 from mypy.nodes import (
13 ARG_NAMED,
14 ARG_POS,
15 LDEF,
16 AssertTypeExpr,
17 AssignmentExpr,
18 BytesExpr,
19 CallExpr,
20 CastExpr,
21 ComparisonExpr,
22 ComplexExpr,
23 ConditionalExpr,
24 DictExpr,
25 DictionaryComprehension,
26 EllipsisExpr,
27 Expression,
28 FloatExpr,
29 GeneratorExpr,
30 IndexExpr,
31 IntExpr,
32 ListComprehension,
33 ListExpr,
34 MemberExpr,
35 MypyFile,
36 NameExpr,
37 OpExpr,
38 RefExpr,
39 SetComprehension,
40 SetExpr,
41 SliceExpr,
42 StarExpr,
43 StrExpr,
44 SuperExpr,
45 TupleExpr,
46 TypeApplication,
47 TypeInfo,
48 TypeVarLikeExpr,
49 UnaryExpr,
50 Var,
51 )
52 from mypy.types import (
53 AnyType,
54 Instance,
55 ProperType,
56 TupleType,
57 TypeOfAny,
58 TypeType,
59 get_proper_type,
60 )
61 from mypyc.common import MAX_SHORT_INT
62 from mypyc.ir.class_ir import ClassIR
63 from mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD
64 from mypyc.ir.ops import (
65 ERR_MAGIC,
66 Assign,
67 BasicBlock,
68 CallC,
69 ComparisonOp,
70 Integer,
71 LoadAddress,
72 LoadLiteral,
73 PrimitiveDescription,
74 RaiseStandardError,
75 Register,
76 TupleGet,
77 TupleSet,
78 Value,
79 )
80 from mypyc.ir.rtypes import (
81 RInstance,
82 RTuple,
83 RVec,
84 bool_rprimitive,
85 int64_rprimitive,
86 int_rprimitive,
87 is_any_int,
88 is_bytearray_rprimitive,
89 is_bytes_rprimitive,
90 is_fixed_width_rtype,
91 is_int64_rprimitive,
92 is_int_rprimitive,
93 is_list_rprimitive,
94 is_none_rprimitive,
95 is_object_rprimitive,
96 is_str_rprimitive,
97 is_tagged,
98 is_tuple_rprimitive,
99 object_rprimitive,
100 set_rprimitive,
101 short_int_rprimitive,
102 vec_api_by_item_type,
103 )
104 from mypyc.irbuild.ast_helpers import is_borrow_friendly_expr, process_conditional
105 from mypyc.irbuild.builder import IRBuilder, int_borrow_friendly_op
106 from mypyc.irbuild.constant_fold import constant_fold_expr
107 from mypyc.irbuild.for_helpers import (
108 comprehension_helper,
109 raise_error_if_contains_unreachable_names,
110 translate_list_comprehension,
111 translate_set_comprehension,
112 translate_vec_comprehension,
113 )
114 from mypyc.irbuild.format_str_tokenizer import (
115 convert_format_expr_to_bytes,
116 convert_format_expr_to_str,
117 join_formatted_bytes,
118 join_formatted_strings,
119 tokenizer_printf_style,
120 )
121 from mypyc.irbuild.specialize import (
122 apply_dunder_specialization,
123 apply_function_specialization,
124 apply_method_specialization,
125 translate_getitem_with_bounds_check,
126 translate_object_new,
127 translate_object_setattr,
128 )
129 from mypyc.irbuild.vec import (
130 as_platform_int,
131 vec_append,
132 vec_create,
133 vec_create_from_values,
134 vec_create_initialized,
135 vec_item_type,
136 vec_slice,
137 )
138 from mypyc.primitives.bytes_ops import bytes_slice_op
139 from mypyc.primitives.dict_ops import dict_get_item_op, dict_new_op, exact_dict_set_item_op
140 from mypyc.primitives.generic_ops import iter_op, name_op
141 from mypyc.primitives.list_ops import list_append_op, list_extend_op, list_slice_op
142 from mypyc.primitives.misc_ops import ellipsis_op, get_module_dict_op, new_slice_op, type_op
143 from mypyc.primitives.set_ops import set_add_op, set_in_op, set_update_op
144 from mypyc.primitives.str_ops import (
145 str_adjust_index_op,
146 str_get_item_unsafe_as_int_op,
147 str_range_check_op,
148 str_slice_op,
149 )
150 from mypyc.primitives.tuple_ops import list_tuple_op, tuple_slice_op
151
152 # Name and attribute references
153
154
155 def transform_name_expr(builder: IRBuilder, expr: NameExpr) -> Value:
156 if isinstance(expr.node, TypeVarLikeExpr) and expr.node.is_new_style:
157 # Reference to Python 3.12 implicit TypeVar/TupleVarTuple/... object.
158 # These are stored in C statics and not visible in Python namespaces.
159 return builder.load_type_var(expr.node.name, expr.node.line)
160 if expr.node is None:
161 builder.add(
162 RaiseStandardError(
163 RaiseStandardError.NAME_ERROR, f'name "{expr.name}" is not defined', expr.line
164 )
165 )
166 return builder.none(expr.line)
167 fullname = expr.node.fullname
168 if builtin := builder.load_builtin(fullname, expr.line):
169 return builtin
170 # special cases
171 if fullname == "builtins.None":
172 return builder.none(expr.line)
173 if fullname == "builtins.True":
174 return builder.true(expr.line)
175 if fullname == "builtins.False":
176 return builder.false(expr.line)
177 if fullname in ("typing.TYPE_CHECKING", "typing_extensions.TYPE_CHECKING"):
178 return builder.false(expr.line)
179
180 math_literal = transform_math_literal(builder, fullname, expr.line)
181 if math_literal is not None:
182 return math_literal
183
184 if isinstance(expr.node, Var) and expr.node.is_final:
185 final_type = builder.types.get(expr) or expr.node.type
186 if final_type is None:
187 final_type = AnyType(TypeOfAny.special_form)
188 value = builder.emit_load_final(
189 expr.node, fullname, expr.name, builder.is_native_ref_expr(expr), final_type, expr.line
190 )
191 if value is not None:
192 return value
193
194 if isinstance(expr.node, MypyFile) and expr.node.fullname in builder.imports:
195 return builder.load_module(expr.node.fullname)
196
197 # If the expression is locally defined, then read the result from the corresponding
198 # assignment target and return it. Otherwise if the expression is a global, load it from
199 # the globals dictionary.
200 # Except for imports, that currently always happens in the global namespace.
201 if expr.kind == LDEF and not (isinstance(expr.node, Var) and expr.node.is_suppressed_import):
202 # Try to detect and error when we hit the irritating mypy bug
203 # where a local variable is cast to None. (#5423)
204 if (
205 isinstance(expr.node, Var)
206 and is_none_rprimitive(builder.node_type(expr))
207 and expr.node.is_inferred
208 ):
209 builder.error(
210 'Local variable "{}" has inferred type None; add an annotation'.format(
211 expr.node.name
212 ),
213 expr.node.line,
214 )
215
216 # TODO: Behavior currently only defined for Var, FuncDef and MypyFile node types.
217 if isinstance(expr.node, MypyFile):
218 # Load reference to a module imported inside function from
219 # the modules dictionary. It would be closer to Python
220 # semantics to access modules imported inside functions
221 # via local variables, but this is tricky since the mypy
222 # AST doesn't include a Var node for the module. We
223 # instead load the module separately on each access.
224 mod_dict = builder.call_c(get_module_dict_op, [], expr.line)
225 obj = builder.primitive_op(
226 dict_get_item_op, [mod_dict, builder.load_str(expr.node.fullname)], expr.line
227 )
228 return obj
229 else:
230 return builder.read(builder.get_assignment_target(expr, for_read=True), expr.line)
231
232 # If we're evaluating a class body and this name is a ClassVar defined earlier
233 # in the same class, load it from the class being built (type object for ext classes,
234 # class dict for non-ext classes) instead of module globals.
235 if (
236 builder.class_body_obj is not None
237 and isinstance(expr.node, Var)
238 and expr.node in builder.class_body_classvars
239 ):
240 if builder.class_body_ir is not None and builder.class_body_ir.is_ext_class:
241 return builder.py_get_attr(builder.class_body_obj, expr.name, expr.line)
242 else:
243 return builder.primitive_op(
244 dict_get_item_op, [builder.class_body_obj, builder.load_str(expr.name)], expr.line
245 )
246
247 return builder.load_global(expr)
248
249
250 def transform_member_expr(builder: IRBuilder, expr: MemberExpr) -> Value:
251 # Special Cases
252 if expr.fullname in ("typing.TYPE_CHECKING", "typing_extensions.TYPE_CHECKING"):
253 return builder.false(expr.line)
254
255 # First check if this is maybe a final attribute.
256 final = builder.get_final_ref(expr)
257 if final is not None:
258 fullname, final_var, native = final
259 final_type = builder.types.get(expr) or final_var.type
260 if final_type is None:
261 final_type = AnyType(TypeOfAny.special_form)
262 value = builder.emit_load_final(
263 final_var, fullname, final_var.name, native, final_type, expr.line
264 )
265 if value is not None:
266 return value
267
268 math_literal = transform_math_literal(builder, expr.fullname, expr.line)
269 if math_literal is not None:
270 return math_literal
271
272 if isinstance(expr.node, MypyFile) and expr.node.fullname in builder.imports:
273 return builder.load_module(expr.node.fullname)
274
275 can_borrow = builder.is_native_attr_ref(expr)
276 obj = builder.accept(expr.expr, can_borrow=can_borrow)
277 rtype = builder.node_type(expr)
278
279 if (
280 is_object_rprimitive(obj.type)
281 and expr.name == "__name__"
282 and builder.options.capi_version >= (3, 11)
283 ):
284 return builder.primitive_op(name_op, [obj], expr.line)
285
286 if isinstance(obj.type, RInstance) and expr.name == "__class__":
287 # A non-native class could override "__class__" using "__getattribute__", so
288 # only apply to RInstance types.
289 return builder.primitive_op(type_op, [obj], expr.line)
290
291 # Special case: for named tuples transform attribute access to faster index access.
292 typ = get_proper_type(builder.types.get(expr.expr))
293 if isinstance(typ, TupleType) and typ.partial_fallback.type.is_named_tuple:
294 fields = typ.partial_fallback.type.metadata["namedtuple"]["fields"]
295 if expr.name in fields:
296 index = builder.builder.load_int(fields.index(expr.name))
297 return builder.gen_method_call(obj, "__getitem__", [index], rtype, expr.line)
298
299 check_instance_attribute_access_through_class(builder, expr, typ)
300
301 borrow = can_borrow and builder.can_borrow
302 return builder.builder.get_attr(obj, expr.name, rtype, expr.line, borrow=borrow)
303
304
305 def check_instance_attribute_access_through_class(
306 builder: IRBuilder, expr: MemberExpr, typ: ProperType | None
307 ) -> None:
308 """Report error if accessing an instance attribute through class object."""
309 if isinstance(expr.expr, RefExpr):
310 node = expr.expr.node
311 if isinstance(typ, TypeType) and isinstance(typ.item, Instance):
312 # TODO: Handle other item types
313 node = typ.item.type
314 if isinstance(node, TypeInfo):
315 class_ir = builder.mapper.type_to_ir.get(node)
316 if class_ir is not None and class_ir.is_ext_class:
317 sym = node.get(expr.name)
318 if (
319 sym is not None
320 and isinstance(sym.node, Var)
321 and not sym.node.is_classvar
322 and not sym.node.is_final
323 ):
324 builder.error(
325 'Cannot access instance attribute "{}" through class object'.format(
326 expr.name
327 ),
328 expr.line,
329 )
330 builder.note(
331 '(Hint: Use "x: Final = ..." or "x: ClassVar = ..." to define '
332 "a class attribute)",
333 expr.line,
334 )
335
336
337 def transform_super_expr(builder: IRBuilder, o: SuperExpr) -> Value:
338 # warning(builder, 'can not optimize super() expression', o.line)
339 sup_val = builder.load_module_attr_by_fullname("builtins.super", o.line)
340 if o.call.args:
341 args = [builder.accept(arg) for arg in o.call.args]
342 else:
343 assert o.info is not None
344 typ = builder.load_native_type_object(o.info.fullname)
345 ir = builder.mapper.type_to_ir[o.info]
346 iter_env = iter(builder.builder.args)
347 # Grab first argument
348 vself: Value = next(iter_env)
349 if builder.fn_info.is_generator:
350 # grab seventh argument (see comment in translate_super_method_call)
351 self_targ = list(builder.symtables[-1].values())[7]
352 vself = builder.read(self_targ, builder.fn_info.fitem.line)
353 elif not ir.is_ext_class:
354 vself = next(iter_env) # second argument is self if non_extension class
355 args = [typ, vself]
356 res = builder.py_call(sup_val, args, o.line)
357 return builder.py_get_attr(res, o.name, o.line)
358
359
360 # Calls
361
362
363 def transform_call_expr(builder: IRBuilder, expr: CallExpr) -> Value:
364 callee = expr.callee
365 if isinstance(expr.analyzed, CastExpr):
366 return translate_cast_expr(builder, expr.analyzed)
367 elif isinstance(expr.analyzed, AssertTypeExpr):
368 # Compile to a no-op.
369 return builder.accept(expr.analyzed.expr)
370 elif (
371 isinstance(callee, (NameExpr, MemberExpr))
372 and isinstance(callee.node, TypeInfo)
373 and callee.node.is_newtype
374 ):
375 # A call to a NewType type is a no-op at runtime.
376 return builder.accept(expr.args[0])
377
378 if isinstance(callee, IndexExpr) and isinstance(callee.analyzed, TypeApplication):
379 analyzed = callee.analyzed
380 if (
381 isinstance(analyzed.expr, RefExpr)
382 and analyzed.expr.fullname == "librt.vecs.vec"
383 and len(analyzed.types) == 1
384 ):
385 item_type = builder.type_to_rtype(analyzed.types[0])
386 vec_type = RVec(item_type)
387 capacity = _get_vec_capacity(builder, expr)
388 if len(expr.args) == 0 or (len(expr.args) == 1 and expr.arg_kinds == [ARG_NAMED]):
389 # vec[T]() or vec[T](capacity=N)
390 return vec_create(builder.builder, vec_type, 0, expr.line, capacity=capacity)
391 elif (len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]) or (
392 len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_NAMED]
393 ):
394 # vec[T](items) or vec[T](items, capacity=N)
395 return translate_vec_create_from_iterable(
396 builder, vec_type, expr.args[0], capacity=capacity
397 )
398 callee = analyzed.expr # Unwrap type application
399
400 if isinstance(callee, MemberExpr):
401 if isinstance(callee.expr, RefExpr) and isinstance(callee.expr.node, MypyFile):
402 # Call a module-level function, not a method.
403 return translate_call(builder, expr, callee)
404 return apply_method_specialization(builder, expr, callee) or translate_method_call(
405 builder, expr, callee
406 )
407 elif isinstance(callee, SuperExpr):
408 return translate_super_method_call(builder, expr, callee)
409 else:
410 return translate_call(builder, expr, callee)
411
412
413 def translate_call(builder: IRBuilder, expr: CallExpr, callee: Expression) -> Value:
414 # The common case of calls is refexprs
415 if isinstance(callee, RefExpr):
416 return apply_function_specialization(builder, expr, callee) or translate_refexpr_call(
417 builder, expr, callee
418 )
419
420 function = builder.accept(callee)
421 args = [builder.accept(arg) for arg in expr.args]
422 return builder.py_call(
423 function, args, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names
424 )
425
426
427 def translate_refexpr_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value:
428 """Translate a non-method call."""
429 # Gen the argument values
430 arg_values = [builder.accept(arg) for arg in expr.args]
431
432 return builder.call_refexpr_with_args(expr, callee, arg_values)
433
434
435 def translate_method_call(builder: IRBuilder, expr: CallExpr, callee: MemberExpr) -> Value:
436 """Generate IR for an arbitrary call of form e.m(...).
437
438 This can also deal with calls to module-level functions.
439 """
440 if builder.is_native_ref_expr(callee):
441 # Call to module-level native function or such
442 return translate_call(builder, expr, callee)
443 elif (
444 isinstance(callee.expr, RefExpr)
445 and isinstance(callee.expr.node, TypeInfo)
446 and callee.expr.node in builder.mapper.type_to_ir
447 and builder.mapper.type_to_ir[callee.expr.node].has_method(callee.name)
448 and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)
449 ):
450 # Call a method via the *class*
451 assert isinstance(callee.expr.node, TypeInfo), callee.expr.node
452 ir = builder.mapper.type_to_ir[callee.expr.node]
453 return call_classmethod(builder, ir, expr, callee)
454 elif builder.is_module_member_expr(callee):
455 # Fall back to a PyCall for non-native module calls
456 function = builder.accept(callee)
457 args = [builder.accept(arg) for arg in expr.args]
458 return builder.py_call(
459 function, args, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names
460 )
461 else:
462 if isinstance(callee.expr, RefExpr):
463 node = callee.expr.node
464 if isinstance(node, Var) and node.is_cls:
465 typ = get_proper_type(node.type)
466 if isinstance(typ, TypeType) and isinstance(typ.item, Instance):
467 class_ir = builder.mapper.type_to_ir.get(typ.item.type)
468 if class_ir and class_ir.is_ext_class and class_ir.has_no_subclasses():
469 # Call a native classmethod via cls that can be statically bound,
470 # since the class has no subclasses.
471 return call_classmethod(builder, class_ir, expr, callee)
472
473 receiver_typ = builder.node_type(callee.expr)
474
475 # If there is a specializer for this method name/type, try calling it.
476 # We would return the first successful one.
477 val = apply_method_specialization(builder, expr, callee, receiver_typ)
478 if val is not None:
479 return val
480
481 obj = builder.accept(callee.expr)
482 args = [builder.accept(arg) for arg in expr.args]
483 return builder.gen_method_call(
484 obj,
485 callee.name,
486 args,
487 builder.node_type(expr),
488 expr.line,
489 expr.arg_kinds,
490 expr.arg_names,
491 )
492
493
494 def call_classmethod(builder: IRBuilder, ir: ClassIR, expr: CallExpr, callee: MemberExpr) -> Value:
495 decl = ir.method_decl(callee.name)
496 args = []
497 arg_kinds, arg_names = expr.arg_kinds.copy(), expr.arg_names.copy()
498 # Add the class argument for class methods in extension classes
499 if decl.kind == FUNC_CLASSMETHOD and ir.is_ext_class:
500 args.append(builder.load_native_type_object(ir.fullname))
501 arg_kinds.insert(0, ARG_POS)
502 arg_names.insert(0, None)
503 args += [builder.accept(arg) for arg in expr.args]
504
505 if ir.is_ext_class:
506 return builder.builder.call(decl, args, arg_kinds, arg_names, expr.line)
507 else:
508 obj = builder.accept(callee.expr)
509 return builder.gen_method_call(
510 obj,
511 callee.name,
512 args,
513 builder.node_type(expr),
514 expr.line,
515 expr.arg_kinds,
516 expr.arg_names,
517 )
518
519
520 def translate_super_method_call(builder: IRBuilder, expr: CallExpr, callee: SuperExpr) -> Value:
521 if callee.info is None or (len(callee.call.args) != 0 and len(callee.call.args) != 2):
522 return translate_call(builder, expr, callee)
523
524 # We support two-argument super but only when it is super(CurrentClass, self)
525 # TODO: We could support it when it is a parent class in many cases?
526 if len(callee.call.args) == 2:
527 self_arg = callee.call.args[1]
528 if (
529 not isinstance(self_arg, NameExpr)
530 or not isinstance(self_arg.node, Var)
531 or not self_arg.node.is_self
532 ):
533 return translate_call(builder, expr, callee)
534
535 typ_arg = callee.call.args[0]
536 if (
537 not isinstance(typ_arg, NameExpr)
538 or not isinstance(typ_arg.node, TypeInfo)
539 or callee.info is not typ_arg.node
540 ):
541 return translate_call(builder, expr, callee)
542
543 ir = builder.mapper.type_to_ir[callee.info]
544 # Search for the method in the mro, skipping ourselves. We
545 # determine targets of super calls to native methods statically.
546 for base in ir.mro[1:]:
547 if callee.name in base.method_decls:
548 break
549 else:
550 if callee.name == "__new__":
551 result = translate_object_new(builder, expr, MemberExpr(callee.call, "__new__"))
552 if result:
553 return result
554 elif callee.name == "__setattr__":
555 result = translate_object_setattr(
556 builder, expr, MemberExpr(callee.call, "__setattr__")
557 )
558 if result:
559 return result
560 if ir.is_ext_class and ir.builtin_base is None and not ir.inherits_python:
561 if callee.name == "__init__" and len(expr.args) == 0:
562 # Call translates to object.__init__(self), which is a
563 # no-op, so omit the call.
564 return builder.none()
565 return translate_call(builder, expr, callee)
566
567 decl = base.method_decl(callee.name)
568 arg_values = [builder.accept(arg) for arg in expr.args]
569 arg_kinds, arg_names = expr.arg_kinds.copy(), expr.arg_names.copy()
570
571 if decl.kind != FUNC_STATICMETHOD and decl.name != "__new__":
572 # Grab first argument
573 vself: Value = builder.self()
574 if decl.kind == FUNC_CLASSMETHOD:
575 vself = builder.primitive_op(type_op, [vself], expr.line)
576 elif builder.fn_info.is_generator:
577 # For generator classes, the self target is the 7th value
578 # in the symbol table (which is an ordered dict). This is sort
579 # of ugly, but we can't search by name since the 'self' parameter
580 # could be named anything, and it doesn't get added to the
581 # environment indexes.
582 self_targ = list(builder.symtables[-1].values())[7]
583 vself = builder.read(self_targ, builder.fn_info.fitem.line)
584 arg_values.insert(0, vself)
585 arg_kinds.insert(0, ARG_POS)
586 arg_names.insert(0, None)
587
588 return builder.builder.call(decl, arg_values, arg_kinds, arg_names, expr.line)
589
590
591 def _get_vec_capacity(builder: IRBuilder, expr: CallExpr) -> Value | None:
592 """Extract the 'capacity' keyword argument value from a vec() call, or None."""
593 for i, (kind, name) in enumerate(zip(expr.arg_kinds, expr.arg_names)):
594 if kind == ARG_NAMED and name == "capacity":
595 return builder.accept(expr.args[i])
596 return None
597
598
599 def translate_vec_create_from_iterable(
600 builder: IRBuilder, vec_type: RVec, arg: Expression, *, capacity: Value | None = None
601 ) -> Value:
602 line = arg.line
603 item_type = vec_type.item_type
604 if isinstance(arg, OpExpr) and arg.op == "*":
605 if isinstance(arg.left, ListExpr):
606 lst = arg.left
607 other = arg.right
608 elif isinstance(arg.right, ListExpr):
609 lst = arg.right
610 other = arg.left
611 else:
612 assert False
613 assert len(lst.items) == 1
614 other_type = builder.node_type(other)
615 # TODO: is_any_int(...)
616 if is_int64_rprimitive(other_type) or is_int_rprimitive(other_type):
617 length = builder.accept(other)
618 init = builder.accept(lst.items[0])
619 return vec_create_initialized(
620 builder.builder, vec_type, length, init, line, capacity=capacity
621 )
622 assert False, other_type
623 if isinstance(arg, ListExpr):
624 items = []
625 for item in arg.items:
626 value = builder.accept(item)
627 items.append(builder.coerce(value, item_type, line))
628 return vec_create_from_values(builder.builder, vec_type, items, line, capacity=capacity)
629 if isinstance(arg, ListComprehension):
630 return translate_vec_comprehension(builder, vec_type, arg.generator, capacity=capacity)
631 return vec_from_iterable(builder, vec_type, arg, line, capacity=capacity)
632
633
634 def vec_from_iterable(
635 builder: IRBuilder,
636 vec_type: RVec,
637 iterable: Expression,
638 line: int,
639 *,
640 capacity: Value | None = None,
641 ) -> Value:
642 """Construct a vec from an arbitrary iterable."""
643 item_type = vec_type.item_type
644 api_name = vec_api_by_item_type.get(item_type)
645 iterable_rtype = builder.node_type(iterable)
646 use_c_from_iterable = (
647 is_object_rprimitive(iterable_rtype)
648 or is_list_rprimitive(iterable_rtype)
649 or is_tuple_rprimitive(iterable_rtype)
650 )
651 if api_name is not None and (
652 use_c_from_iterable
653 or is_bytes_rprimitive(iterable_rtype)
654 or is_bytearray_rprimitive(iterable_rtype)
655 ):
656 # For generic iterables (typed as object) and bytes/bytearray
657 # (which support the buffer protocol for fast memcpy), call the
658 # C-level from_iterable. For concrete types like range, list,
659 # vec, etc., the for-loop desugaring below produces better IR.
660 name = f"{api_name}.from_iterable"
661 extra_args: list[Value] = []
662 elif api_name is None and vec_type.depth() == 0 and use_c_from_iterable:
663 name = "VecTApi.from_iterable"
664 extra_args = [vec_item_type(builder.builder, item_type, line)]
665 else:
666 name = None
667 if name is not None:
668 iterable_val = builder.accept(iterable)
669 cap = (
670 as_platform_int(builder.builder, capacity, line)
671 if capacity is not None
672 else Integer(0, int64_rprimitive)
673 )
674 args = extra_args + [iterable_val, cap]
675 call = CallC(
676 name,
677 args,
678 vec_type,
679 steals=[False] * len(args),
680 is_borrowed=False,
681 error_kind=ERR_MAGIC,
682 line=line,
683 )
684 return builder.add(call)
685
686 # Use a for loop with vec_append. The comprehension helper
687 # special-cases range, list, vec, etc. for efficient iteration.
688 vec = Register(vec_type)
689 builder.assign(vec, vec_create(builder.builder, vec_type, 0, line, capacity=capacity), line)
690 name = f"___tmp_{line}"
691 var = Var(name)
692 reg = builder.add_local(var, vec_type.item_type)
693 index = NameExpr(name)
694 index.kind = LDEF
695 index.node = var
696 loop_params: list[tuple[Expression, Expression, list[Expression], bool]] = [
697 (index, iterable, [], False)
698 ]
699
700 def gen_inner_stmts() -> None:
701 builder.assign(vec, vec_append(builder.builder, vec, reg, line), line)
702
703 comprehension_helper(builder, loop_params, gen_inner_stmts, line)
704 return vec
705
706
707 def translate_cast_expr(builder: IRBuilder, expr: CastExpr) -> Value:
708 src = builder.accept(expr.expr)
709 target_type = builder.type_to_rtype(expr.type)
710 return builder.coerce(src, target_type, expr.line)
711
712
713 # Operators
714
715
716 def transform_unary_expr(builder: IRBuilder, expr: UnaryExpr) -> Value:
717 folded = try_constant_fold(builder, expr)
718 if folded:
719 return folded
720
721 return builder.unary_op(builder.accept(expr.expr), expr.op, expr.line)
722
723
724 def transform_op_expr(builder: IRBuilder, expr: OpExpr) -> Value:
725 if expr.op in ("and", "or"):
726 return builder.shortcircuit_expr(expr)
727
728 # Special case for string formatting
729 if expr.op == "%" and isinstance(expr.left, (StrExpr, BytesExpr)):
730 ret = translate_printf_style_formatting(builder, expr.left, expr.right)
731 if ret is not None:
732 return ret
733
734 folded = try_constant_fold(builder, expr)
735 if folded:
736 return folded
737
738 borrow_left = False
739 borrow_right = False
740
741 ltype = builder.node_type(expr.left)
742 rtype = builder.node_type(expr.right)
743
744 # Special case some int ops to allow borrowing operands.
745 if is_int_rprimitive(ltype) and is_int_rprimitive(rtype):
746 if expr.op == "//":
747 expr = try_optimize_int_floor_divide(builder, expr)
748 if expr.op in int_borrow_friendly_op:
749 borrow_left = is_borrow_friendly_expr(builder, expr.right)
750 borrow_right = True
751 elif is_fixed_width_rtype(ltype) and is_fixed_width_rtype(rtype):
752 borrow_left = is_borrow_friendly_expr(builder, expr.right)
753 borrow_right = True
754
755 left = builder.accept(expr.left, can_borrow=borrow_left)
756 right = builder.accept(expr.right, can_borrow=borrow_right)
757 return builder.binary_op(left, right, expr.op, expr.line)
758
759
760 def try_optimize_int_floor_divide(builder: IRBuilder, expr: OpExpr) -> OpExpr:
761 """Replace // with a power of two with a right shift, if possible."""
762 divisor = constant_fold_expr(builder, expr.right)
763 if not isinstance(divisor, int):
764 return expr
765 shift = divisor.bit_length() - 1
766 if 0 < shift < 28 and divisor == (1 << shift):
767 new_expr = OpExpr(">>", expr.left, IntExpr(shift))
768 new_expr.line = expr.line
769 return new_expr
770 return expr
771
772
773 def transform_index_expr(builder: IRBuilder, expr: IndexExpr) -> Value:
774 index = expr.index
775 base_type = builder.node_type(expr.base)
776 can_borrow = is_list_rprimitive(base_type) or isinstance(base_type, RVec)
777 can_borrow_base = can_borrow and is_borrow_friendly_expr(builder, index)
778
779 # Check for dunder specialization for non-slice indexing
780 if not isinstance(index, SliceExpr):
781 specialized = apply_dunder_specialization(builder, expr.base, [index], "__getitem__", expr)
782 if specialized is not None:
783 return specialized
784
785 base = builder.accept(expr.base, can_borrow=can_borrow_base)
786
787 if isinstance(base.type, RTuple):
788 folded_index = constant_fold_expr(builder, index)
789 if isinstance(folded_index, int):
790 length = len(base.type.types)
791 if -length <= folded_index <= length - 1:
792 return builder.add(TupleGet(base, folded_index, expr.line))
793
794 if isinstance(index, SliceExpr):
795 value = try_gen_slice_op(builder, base, index)
796 if value:
797 return value
798
799 index_reg = builder.accept(expr.index, can_borrow=can_borrow)
800 return builder.builder.get_item(
801 base, index_reg, builder.node_type(expr), expr.line, can_borrow=builder.can_borrow
802 )
803
804
805 def try_constant_fold(builder: IRBuilder, expr: Expression) -> Value | None:
806 """Return the constant value of an expression if possible.
807
808 Return None otherwise.
809 """
810 value = constant_fold_expr(builder, expr)
811 if value is not None:
812 return builder.load_literal_value(value)
813 return None
814
815
816 def try_gen_slice_op(builder: IRBuilder, base: Value, index: SliceExpr) -> Value | None:
817 """Generate specialized slice op for some index expressions.
818
819 Return None if a specialized op isn't available.
820
821 This supports obj[x:y], obj[:x], and obj[x:] for a few types.
822 """
823 if index.stride:
824 # We can only handle the default stride of 1.
825 return None
826
827 if index.begin_index:
828 begin_type = builder.node_type(index.begin_index)
829 else:
830 begin_type = int_rprimitive
831 if index.end_index:
832 end_type = builder.node_type(index.end_index)
833 else:
834 end_type = int_rprimitive
835
836 # Both begin and end index must be int (or missing).
837 if is_any_int(begin_type) and is_any_int(end_type):
838 if index.begin_index:
839 begin = builder.accept(index.begin_index)
840 else:
841 begin = builder.load_int(0)
842 if index.end_index:
843 end = builder.accept(index.end_index)
844 else:
845 # Replace missing end index with the largest short integer
846 # (a sequence can't be longer).
847 end = builder.load_int(MAX_SHORT_INT)
848 if isinstance(base.type, RVec):
849 return vec_slice(builder.builder, base, begin, end, index.line)
850 candidates = [list_slice_op, tuple_slice_op, str_slice_op, bytes_slice_op]
851 return builder.builder.matching_call_c(candidates, [base, begin, end], index.line)
852
853 return None
854
855
856 def transform_conditional_expr(builder: IRBuilder, expr: ConditionalExpr) -> Value:
857 if_body, else_body, next_block = BasicBlock(), BasicBlock(), BasicBlock()
858
859 process_conditional(builder, expr.cond, if_body, else_body)
860 expr_type = builder.node_type(expr)
861 # Having actual Phi nodes would be really nice here!
862 target = Register(expr_type)
863
864 builder.activate_block(if_body)
865 true_value = builder.accept(expr.if_expr)
866 true_value = builder.coerce(true_value, expr_type, expr.line)
867 builder.add(Assign(target, true_value, expr.line))
868 builder.goto(next_block)
869
870 builder.activate_block(else_body)
871 false_value = builder.accept(expr.else_expr)
872 false_value = builder.coerce(false_value, expr_type, expr.line)
873 builder.add(Assign(target, false_value, expr.line))
874 builder.goto(next_block)
875
876 builder.activate_block(next_block)
877
878 return target
879
880
881 def set_literal_values(builder: IRBuilder, items: Sequence[Expression]) -> list[object] | None:
882 values: list[object] = []
883 for item in items:
884 const_value = constant_fold_expr(builder, item)
885 if const_value is not None:
886 values.append(const_value)
887 continue
888
889 if isinstance(item, RefExpr):
890 if item.fullname == "builtins.None":
891 values.append(None)
892 elif item.fullname == "builtins.True":
893 values.append(True)
894 elif item.fullname == "builtins.False":
895 values.append(False)
896 elif isinstance(item, TupleExpr):
897 tuple_values = set_literal_values(builder, item.items)
898 if tuple_values is not None:
899 values.append(tuple(tuple_values))
900
901 if len(values) != len(items):
902 # Bail if not all items can be converted into values.
903 return None
904 return values
905
906
907 def precompute_set_literal(builder: IRBuilder, s: SetExpr) -> Value | None:
908 """Try to pre-compute a frozenset literal during module initialization.
909
910 Return None if it's not possible.
911
912 Supported items:
913 - Anything supported by irbuild.constant_fold.constant_fold_expr()
914 - None, True, and False
915 - Tuple literals with only items listed above
916 """
917 values = set_literal_values(builder, s.items)
918 if values is not None:
919 return builder.add(LoadLiteral(frozenset(values), set_rprimitive))
920
921 return None
922
923
924 def transform_comparison_expr(builder: IRBuilder, e: ComparisonExpr) -> Value:
925 # x in (...)/[...]
926 # x not in (...)/[...]
927 first_op = e.operators[0]
928 if first_op in ["in", "not in"] and len(e.operators) == 1:
929 result = try_specialize_in_expr(builder, first_op, e.operands[0], e.operands[1], e.line)
930 if result is not None:
931 return result
932
933 if len(e.operators) == 1:
934 # s[i] == 'x' / s[i] != 'x' (and the symmetric RHS) -> int compare of
935 # codepoints. Skips the per-iteration 1-char str allocation/lookup and
936 # generic str equality call.
937 if first_op in ("==", "!="):
938 result = try_specialize_str_index_compare(
939 builder, first_op, e.operands[0], e.operands[1], e.line
940 )
941 if result is not None:
942 return result
943
944 # Special some common simple cases
945 if first_op in ("is", "is not"):
946 right_expr = e.operands[1]
947 if isinstance(right_expr, NameExpr) and right_expr.fullname == "builtins.None":
948 # Special case 'is None' / 'is not None'.
949 return translate_is_none(builder, e.operands[0], negated=first_op != "is")
950 left_expr = e.operands[0]
951 if is_int_rprimitive(builder.node_type(left_expr)):
952 right_expr = e.operands[1]
953 if is_int_rprimitive(builder.node_type(right_expr)):
954 if first_op in int_borrow_friendly_op:
955 borrow_left = is_borrow_friendly_expr(builder, right_expr)
956 left = builder.accept(left_expr, can_borrow=borrow_left)
957 right = builder.accept(right_expr, can_borrow=True)
958 return builder.binary_op(left, right, first_op, e.line)
959
960 # TODO: Don't produce an expression when used in conditional context
961 # All of the trickiness here is due to support for chained conditionals
962 # (`e1 < e2 > e3`, etc). `e1 < e2 > e3` is approximately equivalent to
963 # `e1 < e2 and e2 > e3` except that `e2` is only evaluated once.
964 expr_type = builder.node_type(e)
965
966 # go(i, prev) generates code for `ei opi e{i+1} op{i+1} ... en`,
967 # assuming that prev contains the value of `ei`.
968 def go(i: int, prev: Value) -> Value:
969 if i == len(e.operators) - 1:
970 return transform_basic_comparison(
971 builder, e.operators[i], prev, builder.accept(e.operands[i + 1]), e.line
972 )
973
974 next = builder.accept(e.operands[i + 1])
975 return builder.builder.shortcircuit_helper(
976 "and",
977 expr_type,
978 lambda: transform_basic_comparison(builder, e.operators[i], prev, next, e.line),
979 lambda: go(i + 1, next),
980 e.line,
981 )
982
983 return go(0, builder.accept(e.operands[0]))
984
985
986 def try_specialize_str_index_compare(
987 builder: IRBuilder, op: str, lhs: Expression, rhs: Expression, line: int
988 ) -> Value | None:
989 """Specialize `s[i] == 'x'` / `s[i] != 'x'` (and the symmetric form with
990 operands swapped) into an int compare of codepoints.
991
992 Returns None if the pattern doesn't match: the indexed base must be str,
993 the index must be an integer, and the literal must be a 1-character str.
994 Multi-character or empty literals fall through to the generic str compare
995 (which still returns False for them, matching today's behavior).
996 """
997 # Normalize so the IndexExpr is on the left.
998 if isinstance(rhs, IndexExpr) and not isinstance(lhs, IndexExpr):
999 tmp = lhs
1000 lhs, rhs = rhs, tmp
1001 # Shape: s[i] {==, !=} "x" where "x" is exactly one codepoint.
1002 if (
1003 not isinstance(lhs, IndexExpr)
1004 or not isinstance(rhs, StrExpr)
1005 or len(rhs.value) != 1
1006 or not is_str_rprimitive(builder.node_type(lhs.base))
1007 ):
1008 return None
1009 index_type = builder.node_type(lhs.index)
1010 if not (is_tagged(index_type) or is_fixed_width_rtype(index_type)):
1011 return None
1012
1013 # ord(s[i]) with bounds check; raises IndexError for out-of-range indices,
1014 # matching the behavior of the generic s[i] path.
1015 codepoint = translate_getitem_with_bounds_check(
1016 builder,
1017 lhs.base,
1018 [lhs.index],
1019 lhs,
1020 str_adjust_index_op,
1021 str_range_check_op,
1022 str_get_item_unsafe_as_int_op,
1023 )
1024 if codepoint is None:
1025 return None
1026 literal_cp = Integer(ord(rhs.value), short_int_rprimitive, line)
1027 return builder.binary_op(codepoint, literal_cp, op, line)
1028
1029
1030 def try_specialize_in_expr(
1031 builder: IRBuilder, op: str, lhs: Expression, rhs: Expression, line: int
1032 ) -> Value | None:
1033 left: Value | None = None
1034 items: list[Value] | None = None
1035
1036 if isinstance(rhs, (TupleExpr, ListExpr)):
1037 left = builder.accept(lhs)
1038 items = [builder.accept(item) for item in rhs.items]
1039 elif isinstance(builder.node_type(rhs), RTuple):
1040 left = builder.accept(lhs)
1041 tuple_val = builder.accept(rhs)
1042 assert isinstance(tuple_val.type, RTuple)
1043 items = [builder.add(TupleGet(tuple_val, i)) for i in range(len(tuple_val.type.types))]
1044
1045 if items is not None:
1046 assert left is not None
1047 n_items = len(items)
1048 # x in y -> x == y[0] or ... or x == y[n]
1049 # x not in y -> x != y[0] and ... and x != y[n]
1050 if n_items > 1:
1051 if op == "in":
1052 cmp_op = "=="
1053 else:
1054 cmp_op = "!="
1055 out = BasicBlock()
1056 for item in items:
1057 cmp = transform_basic_comparison(builder, cmp_op, left, item, line)
1058 bool_val = builder.builder.bool_value(cmp)
1059 next_block = BasicBlock()
1060 if op == "in":
1061 builder.add_bool_branch(bool_val, out, next_block)
1062 else:
1063 builder.add_bool_branch(bool_val, next_block, out)
1064 builder.activate_block(next_block)
1065 result_reg = Register(bool_rprimitive)
1066 end = BasicBlock()
1067 if op == "in":
1068 values = builder.false(), builder.true()
1069 else:
1070 values = builder.true(), builder.false()
1071 builder.assign(result_reg, values[0], line)
1072 builder.goto(end)
1073 builder.activate_block(out)
1074 builder.assign(result_reg, values[1], line)
1075 builder.goto(end)
1076 builder.activate_block(end)
1077 return result_reg
1078 # x in [y]/(y) -> x == y
1079 # x not in [y]/(y) -> x != y
1080 elif n_items == 1:
1081 if op == "in":
1082 cmp_op = "=="
1083 else:
1084 cmp_op = "!="
1085 right = items[0]
1086 return transform_basic_comparison(builder, cmp_op, left, right, line)
1087 # x in []/() -> False
1088 # x not in []/() -> True
1089 elif n_items == 0:
1090 if op == "in":
1091 return builder.false()
1092 else:
1093 return builder.true()
1094
1095 # x in {...}
1096 # x not in {...}
1097 if isinstance(rhs, SetExpr):
1098 set_literal = precompute_set_literal(builder, rhs)
1099 if set_literal is not None:
1100 result = builder.builder.primitive_op(
1101 set_in_op, [builder.accept(lhs), set_literal], line, bool_rprimitive
1102 )
1103 if op == "not in":
1104 return builder.unary_op(result, "not", line)
1105 return result
1106
1107 return None
1108
1109
1110 def translate_is_none(builder: IRBuilder, expr: Expression, negated: bool) -> Value:
1111 v = builder.accept(expr, can_borrow=True)
1112 return builder.binary_op(v, builder.none_object(), "is not" if negated else "is", expr.line)
1113
1114
1115 def transform_basic_comparison(
1116 builder: IRBuilder, op: str, left: Value, right: Value, line: int
1117 ) -> Value:
1118 """Transform single comparison.
1119
1120 'op' must be one of these:
1121
1122 '==', '!=', '<', '<=', '>', '>='
1123 'in', 'not in'
1124 'is', 'is not'
1125 """
1126 if is_fixed_width_rtype(left.type) and op in ComparisonOp.signed_ops:
1127 if right.type == left.type:
1128 if left.type.is_signed:
1129 op_id = ComparisonOp.signed_ops[op]
1130 else:
1131 op_id = ComparisonOp.unsigned_ops[op]
1132 return builder.builder.comparison_op(left, right, op_id, line)
1133 elif isinstance(right, Integer):
1134 if left.type.is_signed:
1135 op_id = ComparisonOp.signed_ops[op]
1136 else:
1137 op_id = ComparisonOp.unsigned_ops[op]
1138 return builder.builder.comparison_op(
1139 left, builder.coerce(right, left.type, line), op_id, line
1140 )
1141 elif (
1142 is_fixed_width_rtype(right.type)
1143 and op in ComparisonOp.signed_ops
1144 and isinstance(left, Integer)
1145 ):
1146 if right.type.is_signed:
1147 op_id = ComparisonOp.signed_ops[op]
1148 else:
1149 op_id = ComparisonOp.unsigned_ops[op]
1150 return builder.builder.comparison_op(
1151 builder.coerce(left, right.type, line), right, op_id, line
1152 )
1153
1154 negate = False
1155 if op == "is not":
1156 op, negate = "is", True
1157 elif op == "not in":
1158 op, negate = "in", True
1159
1160 target = builder.binary_op(left, right, op, line)
1161
1162 if negate:
1163 target = builder.unary_op(target, "not", line)
1164 return target
1165
1166
1167 def translate_printf_style_formatting(
1168 builder: IRBuilder, format_expr: StrExpr | BytesExpr, rhs: Expression
1169 ) -> Value | None:
1170 tokens = tokenizer_printf_style(format_expr.value)
1171 if tokens is not None:
1172 literals, format_ops = tokens
1173
1174 exprs = []
1175 if isinstance(rhs, TupleExpr):
1176 exprs = rhs.items
1177 elif isinstance(rhs, Expression):
1178 exprs.append(rhs)
1179
1180 if isinstance(format_expr, BytesExpr):
1181 substitutions = convert_format_expr_to_bytes(
1182 builder, format_ops, exprs, format_expr.line
1183 )
1184 if substitutions is not None:
1185 return join_formatted_bytes(builder, literals, substitutions, format_expr.line)
1186 else:
1187 substitutions = convert_format_expr_to_str(
1188 builder, format_ops, exprs, format_expr.line
1189 )
1190 if substitutions is not None:
1191 return join_formatted_strings(builder, literals, substitutions, format_expr.line)
1192
1193 return None
1194
1195
1196 # Literals
1197
1198
1199 def transform_int_expr(builder: IRBuilder, expr: IntExpr) -> Value:
1200 return builder.builder.load_int(expr.value)
1201
1202
1203 def transform_float_expr(builder: IRBuilder, expr: FloatExpr) -> Value:
1204 return builder.builder.load_float(expr.value)
1205
1206
1207 def transform_complex_expr(builder: IRBuilder, expr: ComplexExpr) -> Value:
1208 return builder.builder.load_complex(expr.value)
1209
1210
1211 def transform_str_expr(builder: IRBuilder, expr: StrExpr) -> Value:
1212 return builder.load_str(expr.value)
1213
1214
1215 def transform_bytes_expr(builder: IRBuilder, expr: BytesExpr) -> Value:
1216 return builder.load_bytes_from_str_literal(expr.value)
1217
1218
1219 def transform_ellipsis(builder: IRBuilder, o: EllipsisExpr) -> Value:
1220 return builder.add(LoadAddress(ellipsis_op.type, ellipsis_op.src, o.line))
1221
1222
1223 # Display expressions
1224
1225
1226 def transform_list_expr(builder: IRBuilder, expr: ListExpr) -> Value:
1227 return _visit_list_display(builder, expr.items, expr.line)
1228
1229
1230 def _visit_list_display(builder: IRBuilder, items: list[Expression], line: int) -> Value:
1231 return _visit_display(
1232 builder, items, builder.new_list_op, list_append_op, list_extend_op, line, True
1233 )
1234
1235
1236 def transform_tuple_expr(builder: IRBuilder, expr: TupleExpr) -> Value:
1237 if any(isinstance(item, StarExpr) for item in expr.items):
1238 # create a tuple of unknown length
1239 return _visit_tuple_display(builder, expr)
1240
1241 # create a tuple of fixed length (RTuple)
1242 tuple_type = builder.node_type(expr)
1243 # When handling NamedTuple et. al we might not have proper type info,
1244 # so make some up if we need it.
1245 types = (
1246 tuple_type.types
1247 if isinstance(tuple_type, RTuple)
1248 else [object_rprimitive] * len(expr.items)
1249 )
1250
1251 items = []
1252 for item_expr, item_type in zip(expr.items, types):
1253 reg = builder.accept(item_expr)
1254 item = builder.coerce(reg, item_type, item_expr.line)
1255 if isinstance(item, Register):
1256 temp = Register(item.type)
1257 builder.assign(temp, item, item_expr.line)
1258 item = temp
1259 items.append(item)
1260 return builder.add(TupleSet(items, expr.line))
1261
1262
1263 def _visit_tuple_display(builder: IRBuilder, expr: TupleExpr) -> Value:
1264 """Create a list, then turn it into a tuple."""
1265 val_as_list = _visit_list_display(builder, expr.items, expr.line)
1266 return builder.primitive_op(list_tuple_op, [val_as_list], expr.line)
1267
1268
1269 def transform_dict_expr(builder: IRBuilder, expr: DictExpr) -> Value:
1270 """First accepts all keys and values, then makes a dict out of them."""
1271 key_value_pairs = []
1272 for key_expr, value_expr in expr.items:
1273 key = builder.accept(key_expr) if key_expr is not None else None
1274 value = builder.accept(value_expr)
1275 key_value_pairs.append((key, value))
1276
1277 return builder.builder.make_dict(key_value_pairs, expr.line)
1278
1279
1280 def transform_set_expr(builder: IRBuilder, expr: SetExpr) -> Value:
1281 return _visit_display(
1282 builder, expr.items, builder.new_set_op, set_add_op, set_update_op, expr.line, False
1283 )
1284
1285
1286 def _visit_display(
1287 builder: IRBuilder,
1288 items: list[Expression],
1289 constructor_op: Callable[[list[Value], int], Value],
1290 append_op: PrimitiveDescription,
1291 extend_op: PrimitiveDescription,
1292 line: int,
1293 is_list: bool,
1294 ) -> Value:
1295 accepted_items = []
1296 for item in items:
1297 if isinstance(item, StarExpr):
1298 accepted_items.append((True, builder.accept(item.expr)))
1299 else:
1300 accepted_items.append((False, builder.accept(item)))
1301
1302 result: Value | None = None
1303 initial_items = []
1304 for starred, value in accepted_items:
1305 if result is None and not starred and is_list:
1306 initial_items.append(value)
1307 continue
1308
1309 if result is None:
1310 result = constructor_op(initial_items, line)
1311
1312 builder.primitive_op(extend_op if starred else append_op, [result, value], line)
1313
1314 if result is None:
1315 result = constructor_op(initial_items, line)
1316
1317 return result
1318
1319
1320 # Comprehensions
1321 #
1322 # mypyc always inlines comprehensions (the loop body is emitted directly into
1323 # the enclosing function's IR, no implicit function call like CPython).
1324 #
1325 # However, when a comprehension body contains a lambda, we need a lightweight
1326 # scope boundary so the closure/env-class machinery can see the comprehension
1327 # as a separate scope. The comprehension is still inlined (same basic blocks
1328 # and registers), but we push a new FuncInfo and set up an env class so the
1329 # lambda can capture loop variables through the standard env-class chain.
1330
1331
1332 def transform_list_comprehension(builder: IRBuilder, o: ListComprehension) -> Value:
1333 gen = o.generator
1334 if gen in builder.comprehension_to_fitem:
1335 return _translate_comprehension_with_scope(
1336 builder, gen, lambda: translate_list_comprehension(builder, gen)
1337 )
1338 return translate_list_comprehension(builder, gen)
1339
1340
1341 def transform_set_comprehension(builder: IRBuilder, o: SetComprehension) -> Value:
1342 gen = o.generator
1343 if gen in builder.comprehension_to_fitem:
1344 return _translate_comprehension_with_scope(
1345 builder, gen, lambda: translate_set_comprehension(builder, gen)
1346 )
1347 return translate_set_comprehension(builder, gen)
1348
1349
1350 def transform_dictionary_comprehension(builder: IRBuilder, o: DictionaryComprehension) -> Value:
1351 if raise_error_if_contains_unreachable_names(builder, o):
1352 return builder.none()
1353
1354 if o in builder.comprehension_to_fitem:
1355 return _translate_comprehension_with_scope(builder, o, lambda: _dict_comp_body(builder, o))
1356 return _dict_comp_body(builder, o)
1357
1358
1359 def _dict_comp_body(builder: IRBuilder, o: DictionaryComprehension) -> Value:
1360 d = builder.maybe_spill(builder.call_c(dict_new_op, [], o.line))
1361 loop_params = list(zip(o.indices, o.sequences, o.condlists, o.is_async))
1362
1363 def gen_inner_stmts() -> None:
1364 k = builder.accept(o.key)
1365 v = builder.accept(o.value)
1366 builder.call_c(exact_dict_set_item_op, [builder.read(d, o.line), k, v], o.line)
1367
1368 comprehension_helper(builder, loop_params, gen_inner_stmts, o.line)
1369 return builder.read(d, o.line)
1370
1371
1372 def _translate_comprehension_with_scope(
1373 builder: IRBuilder,
1374 node: GeneratorExpr | DictionaryComprehension,
1375 gen_body: Callable[[], Value],
1376 ) -> Value:
1377 """Wrap a comprehension body with a lightweight scope for closure capture."""
1378 from mypyc.irbuild.context import FuncInfo
1379 from mypyc.irbuild.env_class import add_vars_to_env, finalize_env_class, setup_env_class
1380
1381 comprehension_fdef = builder.comprehension_to_fitem[node]
1382 fn_info = FuncInfo(
1383 fitem=comprehension_fdef,
1384 name=comprehension_fdef.name,
1385 is_nested=True,
1386 contains_nested=True,
1387 is_comprehension_scope=True,
1388 )
1389
1390 with builder.enter_scope(fn_info):
1391 setup_env_class(builder)
1392 finalize_env_class(builder)
1393 add_vars_to_env(builder)
1394 return gen_body()
1395
1396
1397 # Misc
1398
1399
1400 def transform_slice_expr(builder: IRBuilder, expr: SliceExpr) -> Value:
1401 def get_arg(arg: Expression | None) -> Value:
1402 if arg is None:
1403 return builder.none_object()
1404 else:
1405 return builder.accept(arg)
1406
1407 args = [get_arg(expr.begin_index), get_arg(expr.end_index), get_arg(expr.stride)]
1408 return builder.primitive_op(new_slice_op, args, expr.line)
1409
1410
1411 def transform_generator_expr(builder: IRBuilder, o: GeneratorExpr) -> Value:
1412 builder.warning("Treating generator comprehension as list", o.line)
1413 if o in builder.comprehension_to_fitem:
1414 return builder.primitive_op(
1415 iter_op,
1416 [
1417 _translate_comprehension_with_scope(
1418 builder, o, lambda: translate_list_comprehension(builder, o)
1419 )
1420 ],
1421 o.line,
1422 )
1423 return builder.primitive_op(iter_op, [translate_list_comprehension(builder, o)], o.line)
1424
1425
1426 def transform_assignment_expr(builder: IRBuilder, o: AssignmentExpr) -> Value:
1427 value = builder.accept(o.value)
1428 target = builder.get_assignment_target(o.target)
1429 builder.assign(target, value, o.line)
1430 return value
1431
1432
1433 def transform_math_literal(builder: IRBuilder, fullname: str, line: int) -> Value | None:
1434 if fullname == "math.e":
1435 return builder.load_float(math.e, line)
1436 if fullname == "math.pi":
1437 return builder.load_float(math.pi, line)
1438 if fullname == "math.inf":
1439 return builder.load_float(math.inf, line)
1440 if fullname == "math.nan":
1441 return builder.load_float(math.nan, line)
1442 if fullname == "math.tau":
1443 return builder.load_float(math.tau, line)
1444
1445 return None