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