Debian Codegraph @

mypyc/irbuild/builder.py

raw
1 """Builder class to transform a mypy AST to the IR form.
2
3 See the docstring of class IRBuilder for more information.
4 """
5
6 from __future__ import annotations
7
8 from collections.abc import Callable, Iterator, Sequence
9 from contextlib import contextmanager
10 from typing import Any, Final, overload
11
12 from mypy.build import Graph
13 from mypy.maptype import map_instance_to_supertype
14 from mypy.nodes import (
15 ARG_NAMED,
16 ARG_POS,
17 GDEF,
18 LDEF,
19 PARAM_SPEC_KIND,
20 TYPE_VAR_KIND,
21 TYPE_VAR_TUPLE_KIND,
22 ArgKind,
23 AssignmentExpr,
24 AwaitExpr,
25 CallExpr,
26 Decorator,
27 DictionaryComprehension,
28 Expression,
29 FuncDef,
30 GeneratorExpr,
31 IndexExpr,
32 IntExpr,
33 LambdaExpr,
34 Lvalue,
35 MemberExpr,
36 MypyFile,
37 NameExpr,
38 OpExpr,
39 OverloadedFuncDef,
40 RefExpr,
41 StarExpr,
42 Statement,
43 SymbolNode,
44 TupleExpr,
45 TypeAlias,
46 TypeInfo,
47 TypeParam,
48 Var,
49 YieldExpr,
50 YieldFromExpr,
51 )
52 from mypy.traverser import TraverserVisitor
53 from mypy.types import (
54 AnyType,
55 DeletedType,
56 Instance,
57 ProperType,
58 TupleType,
59 Type,
60 TypedDictType,
61 TypeOfAny,
62 TypeVarLikeType,
63 UninhabitedType,
64 UnionType,
65 get_proper_type,
66 )
67 from mypy.util import module_prefix, split_target
68 from mypy.visitor import ExpressionVisitor, StatementVisitor
69 from mypyc.common import (
70 BITMAP_BITS,
71 EXT_SUFFIX,
72 GENERATOR_ATTRIBUTE_PREFIX,
73 IS_FREE_THREADED,
74 KEEP_ALIVE_SHORT_LIVED,
75 KEEP_ALIVE_WHOLE_EXPRESSION,
76 MODULE_PREFIX,
77 SELF_NAME,
78 TEMP_ATTR_NAME,
79 shared_lib_name,
80 )
81 from mypyc.crash import catch_errors
82 from mypyc.errors import Errors
83 from mypyc.ir.class_ir import ClassIR, NonExtClassInfo
84 from mypyc.ir.func_ir import INVALID_FUNC_DEF, FuncDecl, FuncIR, FuncSignature, RuntimeArg
85 from mypyc.ir.ops import (
86 NAMESPACE_MODULE,
87 NAMESPACE_TYPE_VAR,
88 NO_TRACEBACK_LINE_NO,
89 Assign,
90 BasicBlock,
91 Branch,
92 Call,
93 Cast,
94 ComparisonOp,
95 GetAttr,
96 InitStatic,
97 Integer,
98 IntOp,
99 LoadAddress,
100 LoadGlobal,
101 LoadStatic,
102 MethodCall,
103 Op,
104 PrimitiveDescription,
105 RaiseStandardError,
106 Register,
107 SetAttr,
108 TupleGet,
109 Unreachable,
110 Value,
111 )
112 from mypyc.ir.rtypes import (
113 RInstance,
114 RTuple,
115 RType,
116 RUnion,
117 RVec,
118 bitmap_rprimitive,
119 bool_rprimitive,
120 bytes_rprimitive,
121 c_pointer_rprimitive,
122 c_pyssize_t_rprimitive,
123 dict_rprimitive,
124 int_rprimitive,
125 is_float_rprimitive,
126 is_list_rprimitive,
127 is_none_rprimitive,
128 is_object_rprimitive,
129 is_tagged,
130 is_tuple_rprimitive,
131 none_rprimitive,
132 object_pointer_rprimitive,
133 object_rprimitive,
134 str_rprimitive,
135 )
136 from mypyc.irbuild.constant_fold import constant_fold_expr
137 from mypyc.irbuild.context import FuncInfo, ImplicitClass
138 from mypyc.irbuild.ll_builder import LowLevelIRBuilder
139 from mypyc.irbuild.mapper import Mapper
140 from mypyc.irbuild.nonlocalcontrol import (
141 BaseNonlocalControl,
142 GeneratorNonlocalControl,
143 LoopNonlocalControl,
144 NonlocalControl,
145 )
146 from mypyc.irbuild.prebuildvisitor import PreBuildVisitor
147 from mypyc.irbuild.prepare import RegisterImplInfo
148 from mypyc.irbuild.targets import (
149 AssignmentTarget,
150 AssignmentTargetAttr,
151 AssignmentTargetIndex,
152 AssignmentTargetRegister,
153 AssignmentTargetTuple,
154 )
155 from mypyc.irbuild.util import bytes_from_str, is_constant
156 from mypyc.irbuild.vec import vec_set_item
157 from mypyc.namegen import exported_name
158 from mypyc.options import CompilerOptions
159 from mypyc.primitives.dict_ops import dict_get_item_op, dict_set_item_op
160 from mypyc.primitives.generic_ops import iter_op, next_op, py_setattr_op
161 from mypyc.primitives.list_ops import (
162 list_get_item_int64_op,
163 list_get_item_unsafe_op,
164 list_pop_last,
165 to_list,
166 )
167 from mypyc.primitives.misc_ops import (
168 check_unpack_count_op,
169 get_module_dict_op,
170 import_op,
171 native_import_op,
172 )
173 from mypyc.primitives.registry import CFunctionDescription, function_ops
174 from mypyc.primitives.tuple_ops import tuple_get_item_unsafe_op
175
176 # These int binary operations can borrow their operands safely, since the
177 # primitives take this into consideration.
178 int_borrow_friendly_op: Final = {"+", "-", "==", "!=", "<", "<=", ">", ">="}
179
180
181 class IRVisitor(ExpressionVisitor[Value], StatementVisitor[None]):
182 pass
183
184
185 class UnsupportedException(Exception):
186 pass
187
188
189 SymbolTarget = AssignmentTargetRegister | AssignmentTargetAttr
190
191
192 class IRBuilder:
193 """Builder class used to construct mypyc IR from a mypy AST.
194
195 The IRBuilder class maintains IR transformation state and provides access
196 to various helpers used to implement the transform.
197
198 mypyc.irbuild.visitor.IRBuilderVisitor is used to dispatch based on mypy
199 AST node type to code that actually does the bulk of the work. For
200 example, expressions are transformed in mypyc.irbuild.expression and
201 functions are transformed in mypyc.irbuild.function.
202
203 Use the "accept()" method to translate individual mypy AST nodes to IR.
204 Other methods are used to generate IR for various lower-level operations.
205
206 This class wraps the lower-level LowLevelIRBuilder class, an instance
207 of which is available through the "builder" attribute. The low-level
208 builder class doesn't have any knowledge of the mypy AST. Wrappers for
209 some LowLevelIRBuilder method are provided for convenience, but others
210 can also be accessed via the "builder" attribute.
211
212 See also:
213 * The mypyc IR is defined in the mypyc.ir package.
214 * The top-level IR transform control logic is in mypyc.irbuild.main.
215 """
216
217 def __init__(
218 self,
219 current_module: str,
220 types: dict[Expression, Type],
221 graph: Graph,
222 errors: Errors,
223 mapper: Mapper,
224 pbv: PreBuildVisitor,
225 visitor: IRVisitor,
226 options: CompilerOptions,
227 singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]],
228 ) -> None:
229 self.builder = LowLevelIRBuilder(errors, options)
230 self.builders = [self.builder]
231 self.symtables: list[dict[SymbolNode, SymbolTarget]] = [{}]
232 self.runtime_args: list[list[RuntimeArg]] = [[]]
233 self.function_name_stack: list[str] = []
234 self.class_ir_stack: list[ClassIR] = []
235 # Keep track of whether the next statement in a block is reachable
236 # or not, separately for each block nesting level
237 self.block_reachable_stack: list[bool] = [True]
238
239 self.current_module = current_module
240 self.mapper = mapper
241 self.types = types
242 self.graph = graph
243 self.ret_types: list[RType] = []
244 self.functions: list[FuncIR] = []
245 self.function_names: set[tuple[str | None, str]] = set()
246 self.classes: list[ClassIR] = []
247 self.final_names: list[tuple[str, RType]] = []
248 self.type_var_names: list[str] = []
249 self.callable_class_names: set[str] = set()
250 self.options = options
251
252 # These variables keep track of the number of lambdas, implicit indices, and implicit
253 # iterators instantiated so we avoid name conflicts. The indices and iterators are
254 # instantiated from for-loops.
255 self.lambda_counter = 0
256 self.temp_counter = 0
257
258 # These variables are populated from the first-pass PreBuildVisitor.
259 self.free_variables = pbv.free_variables
260 self.prop_setters = pbv.prop_setters
261 self.encapsulating_funcs = pbv.encapsulating_funcs
262 self.nested_fitems = pbv.nested_funcs.keys()
263 self.fdefs_to_decorators = pbv.funcs_to_decorators
264 self.module_import_groups = pbv.module_import_groups
265 self.comprehension_to_fitem = pbv.comprehension_to_fitem
266
267 self.singledispatch_impls = singledispatch_impls
268
269 self.visitor = visitor
270
271 # Class body context: tracks ClassVars defined so far when processing
272 # a class body, so that intra-class references (e.g. C = A | B where A is
273 # a ClassVar defined earlier in the same class) can be resolved correctly.
274 # Without this, mypyc looks up such names in module globals, which fails.
275 self.class_body_classvars: dict[Var, None] = {}
276 self.class_body_obj: Value | None = None
277 self.class_body_ir: ClassIR | None = None
278
279 # This list operates similarly to a function call stack for nested functions. Whenever a
280 # function definition begins to be generated, a FuncInfo instance is added to the stack,
281 # and information about that function (e.g. whether it is nested, its environment class to
282 # be generated) is stored in that FuncInfo instance. When the function is done being
283 # generated, its corresponding FuncInfo is popped off the stack.
284 self.fn_info = FuncInfo(INVALID_FUNC_DEF, "", "")
285 self.fn_infos: list[FuncInfo] = [self.fn_info]
286
287 # This list operates as a stack of constructs that modify the
288 # behavior of nonlocal control flow constructs.
289 self.nonlocal_control: list[NonlocalControl] = []
290
291 self.errors = errors
292 # Notionally a list of all of the modules imported by the
293 # module being compiled, but stored as an OrderedDict so we
294 # can also do quick lookups.
295 self.imports: dict[str, None] = {}
296
297 self.can_borrow = False
298 self.expression_depth = 0
299 # Symbols (local vars) reassigned via a walrus expression within the current
300 # top-level expression. Used to avoid borrowing an attribute over the whole
301 # expression when the borrow root could be rebound (and thus freed) partway.
302 self.reassigned_in_expr: set[SymbolNode] = set()
303 # Whether the current top-level expression contains a suspension point
304 # (await, yield or yield from). A whole-expression borrow can't span such a
305 # point, since the borrowed value (and its root) live in registers that are
306 # not spilled into the generator environment across the suspend.
307 self.expr_has_suspend = False
308 # Saved expression state for enclosing functions (see enter()/leave()).
309 self.expression_depth_stack: list[int] = []
310 self.reassigned_in_expr_stack: list[set[SymbolNode]] = []
311 self.expr_has_suspend_stack: list[bool] = []
312
313 # When set, load_globals_dict uses this module instead of self.module_name.
314 # Used by generate_attr_defaults_init for cross-module inherited defaults.
315 self.globals_lookup_module: str | None = None
316
317 # High-level control
318
319 def set_module(self, module_name: str, module_path: str) -> None:
320 """Set the name and path of the current module.
321
322 This must be called before transforming any AST nodes.
323 """
324 self.module_name = module_name
325 self.module_path = module_path
326 self.builder.set_module(module_name, module_path)
327
328 @overload
329 def accept(self, node: Expression, *, can_borrow: bool = False) -> Value: ...
330
331 @overload
332 def accept(self, node: Statement) -> None: ...
333
334 def accept(self, node: Statement | Expression, *, can_borrow: bool = False) -> Value | None:
335 """Transform an expression or a statement.
336
337 If can_borrow is true, prefer to generate a borrowed reference.
338 Borrowed references are faster since they don't require reference count
339 manipulation, but they are only safe to use in specific contexts.
340 """
341 with self.catch_errors(node.line):
342 if isinstance(node, Expression):
343 self.expression_depth += 1
344 if self.expression_depth == 1:
345 self.reassigned_in_expr = find_walrus_targets(node)
346 self.expr_has_suspend = expr_has_suspend(node)
347 old_can_borrow = self.can_borrow
348 self.can_borrow = can_borrow
349 try:
350 res = node.accept(self.visitor)
351 res = self.coerce(res, self.node_type(node), node.line)
352 # If we hit an error during compilation, we want to
353 # keep trying, so we can produce more error
354 # messages. Generate a temp of the right type to keep
355 # from causing more downstream trouble.
356 except UnsupportedException:
357 res = Register(self.node_type(node))
358 self.can_borrow = old_can_borrow
359 if not can_borrow:
360 self.flush_keep_alives(node.line)
361 self.expression_depth -= 1
362 if self.expression_depth == 0:
363 self.flush_keep_alives(node.line, scope=KEEP_ALIVE_WHOLE_EXPRESSION)
364 self.reassigned_in_expr = set()
365 self.expr_has_suspend = False
366 return res
367 else:
368 try:
369 node.accept(self.visitor)
370 except UnsupportedException:
371 pass
372 return None
373
374 def flush_keep_alives(self, line: int, *, scope: int = KEEP_ALIVE_SHORT_LIVED) -> None:
375 self.builder.flush_keep_alives(line, scope=scope)
376
377 # Pass through methods for the most common low-level builder ops, for convenience.
378
379 def add(self, op: Op) -> Value:
380 return self.builder.add(op)
381
382 def goto(self, target: BasicBlock) -> None:
383 self.builder.goto(target)
384
385 def activate_block(self, block: BasicBlock) -> None:
386 self.builder.activate_block(block)
387
388 def goto_and_activate(self, block: BasicBlock) -> None:
389 self.builder.goto_and_activate(block)
390
391 def self(self) -> Register:
392 return self.builder.self()
393
394 def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:
395 return self.builder.py_get_attr(obj, attr, line)
396
397 def load_str(self, value: str, line: int = -1) -> Value:
398 return self.builder.load_str(value, line)
399
400 def load_bytes_from_str_literal(self, value: str, line: int = -1) -> Value:
401 """Load bytes object from a string literal.
402
403 The literal characters of BytesExpr (the characters inside b'')
404 are stored in BytesExpr.value, whose type is 'str' not 'bytes'.
405 Thus we perform a special conversion here.
406 """
407 return self.builder.load_bytes(bytes_from_str(value), line)
408
409 def load_int(self, value: int, line: int = -1) -> Value:
410 return self.builder.load_int(value, line)
411
412 def load_float(self, value: float, line: int = -1) -> Value:
413 return self.builder.load_float(value, line)
414
415 def unary_op(self, lreg: Value, expr_op: str, line: int) -> Value:
416 return self.builder.unary_op(lreg, expr_op, line)
417
418 def binary_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
419 return self.builder.binary_op(lreg, rreg, expr_op, line)
420
421 def coerce(self, src: Value, target_type: RType, line: int, force: bool = False) -> Value:
422 return self.builder.coerce(src, target_type, line, force, can_borrow=self.can_borrow)
423
424 def none_object(self, line: int = -1) -> Value:
425 return self.builder.none_object(line)
426
427 def none(self, line: int = -1) -> Value:
428 return self.builder.none(line)
429
430 def true(self, line: int = -1) -> Value:
431 return self.builder.true(line)
432
433 def false(self, line: int = -1) -> Value:
434 return self.builder.false(line)
435
436 def new_list_op(self, values: list[Value], line: int) -> Value:
437 return self.builder.new_list_op(values, line)
438
439 def new_set_op(self, values: list[Value], line: int) -> Value:
440 return self.builder.new_set_op(values, line)
441
442 def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
443 return self.builder.translate_is_op(lreg, rreg, expr_op, line)
444
445 def py_call(
446 self,
447 function: Value,
448 arg_values: list[Value],
449 line: int,
450 arg_kinds: list[ArgKind] | None = None,
451 arg_names: Sequence[str | None] | None = None,
452 ) -> Value:
453 return self.builder.py_call(function, arg_values, line, arg_kinds, arg_names)
454
455 def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:
456 self.builder.add_bool_branch(value, true, false)
457
458 def load_native_type_object(self, fullname: str) -> Value:
459 return self.builder.load_native_type_object(fullname)
460
461 def gen_method_call(
462 self,
463 base: Value,
464 name: str,
465 arg_values: list[Value],
466 result_type: RType | None,
467 line: int,
468 arg_kinds: list[ArgKind] | None = None,
469 arg_names: list[str | None] | None = None,
470 ) -> Value:
471 return self.builder.gen_method_call(
472 base, name, arg_values, result_type, line, arg_kinds, arg_names, self.can_borrow
473 )
474
475 def load_module(self, name: str) -> Value:
476 return self.builder.load_module(name)
477
478 def call_c(self, desc: CFunctionDescription, args: list[Value], line: int) -> Value:
479 return self.builder.call_c(desc, args, line)
480
481 def primitive_op(
482 self,
483 desc: PrimitiveDescription,
484 args: list[Value],
485 line: int,
486 result_type: RType | None = None,
487 ) -> Value:
488 return self.builder.primitive_op(desc, args, line, result_type)
489
490 def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int) -> Value:
491 return self.builder.int_op(type, lhs, rhs, op, line)
492
493 def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
494 return self.builder.compare_tuples(lhs, rhs, op, line)
495
496 def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Value:
497 return self.builder.builtin_len(val, line, use_pyssize_t)
498
499 def new_tuple(self, items: list[Value], line: int) -> Value:
500 return self.builder.new_tuple(items, line)
501
502 def debug_print(self, toprint: str | Value) -> None:
503 return self.builder.debug_print(toprint)
504
505 def set_immortal_if_free_threaded(self, v: Value, line: int) -> None:
506 """Make an object immortal on free-threaded builds (to avoid contention)."""
507 self.builder.set_immortal_if_free_threaded(v, line)
508
509 # Helpers for IR building
510
511 def add_to_non_ext_dict(
512 self, non_ext: NonExtClassInfo, key: str, val: Value, line: int
513 ) -> None:
514 # Add an attribute entry into the class dict of a non-extension class.
515 key_unicode = self.load_str(key, line)
516 self.primitive_op(dict_set_item_op, [non_ext.dict, key_unicode, val], line)
517
518 # It's important that accessing class dictionary items from multiple threads
519 # doesn't cause contention.
520 self.builder.set_immortal_if_free_threaded(val, line)
521
522 def gen_import(self, module: str, line: int) -> None:
523 self.imports[module] = None
524
525 needs_import, out = BasicBlock(), BasicBlock()
526 self.check_if_module_loaded(module, line, needs_import, out)
527
528 self.activate_block(needs_import)
529 if self.is_native_module(module) and self.is_same_group_module(module):
530 # Use custom import machinery for native-to-native imports in the same group
531 init_only_func = self.add(
532 LoadGlobal(c_pointer_rprimitive, f"CPyInitOnly_{exported_name(module)}")
533 )
534 exec_func = self.add(
535 LoadGlobal(c_pointer_rprimitive, f"CPyExec_{exported_name(module)}")
536 )
537 module_static = self.add(
538 LoadAddress(
539 object_pointer_rprimitive,
540 f"{MODULE_PREFIX}{exported_name(module + '__internal')}",
541 )
542 )
543 group_name = self.mapper.group_map.get(self.module_name)
544 if group_name is not None:
545 shared_lib_mod_name = shared_lib_name(group_name)
546 mod_dict = self.call_c(get_module_dict_op, [], line)
547 shared_lib_obj = self.primitive_op(
548 dict_get_item_op, [mod_dict, self.load_str(shared_lib_mod_name, line)], line
549 )
550 shared_lib_file = self.py_get_attr(shared_lib_obj, "__file__", line)
551 else:
552 shared_lib_file = self.none_object(line)
553 ext_suffix = self.load_str(EXT_SUFFIX, line)
554 is_pkg = self.is_package_module(module)
555 value = self.call_c(
556 native_import_op,
557 [
558 self.load_str(module, line),
559 init_only_func,
560 exec_func,
561 module_static,
562 shared_lib_file,
563 ext_suffix,
564 Integer(1 if is_pkg else 0, c_pyssize_t_rprimitive),
565 ],
566 line,
567 )
568 else:
569 # Import using generic Python C API
570 value = self.call_c(import_op, [self.load_str(module, line)], line)
571 self.add(InitStatic(value, module, namespace=NAMESPACE_MODULE))
572 self.goto_and_activate(out)
573
574 def check_if_module_loaded(
575 self, id: str, line: int, needs_import: BasicBlock, out: BasicBlock
576 ) -> None:
577 """Generate code that checks if the module `id` has been loaded yet.
578
579 Arguments:
580 id: name of module to check if imported
581 line: line number that the import occurs on
582 needs_import: the BasicBlock that is run if the module has not been loaded yet
583 out: the BasicBlock that is run if the module has already been loaded"""
584 first_load = self.load_module(id)
585 comparison = self.translate_is_op(first_load, self.none_object(line), "is not", line)
586 self.add_bool_branch(comparison, out, needs_import)
587
588 def get_module(self, module: str, line: int) -> Value:
589 # Python 3.7 has a nice 'PyImport_GetModule' function that we can't use :(
590 mod_dict = self.call_c(get_module_dict_op, [], line)
591 # Get module object from modules dict.
592 return self.primitive_op(dict_get_item_op, [mod_dict, self.load_str(module, line)], line)
593
594 def get_module_attr(self, module: str, attr: str, line: int) -> Value:
595 """Look up an attribute of a module without storing it in the local namespace.
596
597 For example, get_module_attr('typing', 'TypedDict', line) results in
598 the value of 'typing.TypedDict'.
599
600 Import the module if needed.
601 """
602 self.gen_import(module, line)
603 module_obj = self.get_module(module, line)
604 return self.py_get_attr(module_obj, attr, line)
605
606 def assign_if_null(self, target: Register, get_val: Callable[[], Value], line: int) -> None:
607 """If target is NULL, assign value produced by get_val to it."""
608 error_block, body_block = BasicBlock(), BasicBlock()
609 self.add(Branch(target, error_block, body_block, Branch.IS_ERROR, line))
610 self.activate_block(error_block)
611 self.add(Assign(target, self.coerce(get_val(), target.type, line), line))
612 self.goto(body_block)
613 self.activate_block(body_block)
614
615 def assign_if_bitmap_unset(
616 self, target: Register, get_val: Callable[[], Value], index: int, line: int
617 ) -> None:
618 error_block, body_block = BasicBlock(), BasicBlock()
619 o = self.int_op(
620 bitmap_rprimitive,
621 self.builder.args[-1 - index // BITMAP_BITS],
622 Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive),
623 IntOp.AND,
624 line,
625 )
626 b = self.add(ComparisonOp(o, Integer(0, bitmap_rprimitive), ComparisonOp.EQ, line))
627 self.add(Branch(b, error_block, body_block, Branch.BOOL))
628 self.activate_block(error_block)
629 self.add(Assign(target, self.coerce(get_val(), target.type, line)))
630 self.goto(body_block)
631 self.activate_block(body_block)
632
633 def maybe_add_implicit_return(self) -> None:
634 if is_none_rprimitive(self.ret_types[-1]) or is_object_rprimitive(self.ret_types[-1]):
635 self.add_implicit_return()
636 else:
637 self.add_implicit_unreachable()
638
639 def add_implicit_return(self) -> None:
640 block = self.builder.blocks[-1]
641 if not block.terminated:
642 line = self.fn_info.fitem.line
643 retval = self.coerce(self.builder.none(), self.ret_types[-1], line)
644 self.nonlocal_control[-1].gen_return(self, retval, line)
645
646 def add_implicit_unreachable(self) -> None:
647 block = self.builder.blocks[-1]
648 if not block.terminated:
649 self.add(Unreachable())
650
651 def disallow_class_assignments(self, lvalues: list[Lvalue], line: int) -> None:
652 # Some best-effort attempts to disallow assigning to class
653 # variables that aren't marked ClassVar, since we blatantly
654 # miscompile the interaction between instance and class
655 # variables.
656 for lvalue in lvalues:
657 if (
658 isinstance(lvalue, MemberExpr)
659 and isinstance(lvalue.expr, RefExpr)
660 and isinstance(lvalue.expr.node, TypeInfo)
661 ):
662 var = lvalue.expr.node[lvalue.name].node
663 if isinstance(var, Var) and not var.is_classvar:
664 self.error("Only class variables defined as ClassVar can be assigned to", line)
665
666 def non_function_scope(self) -> bool:
667 # Currently the stack always has at least two items: dummy and top-level.
668 return len(self.fn_infos) <= 2
669
670 def top_level_fn_info(self) -> FuncInfo | None:
671 if self.non_function_scope():
672 return None
673 return self.fn_infos[2]
674
675 def init_final_static(
676 self,
677 lvalue: Lvalue,
678 rvalue_reg: Value,
679 class_name: str | None = None,
680 *,
681 type_override: RType | None = None,
682 ) -> None:
683 assert isinstance(lvalue, NameExpr), lvalue
684 assert isinstance(lvalue.node, Var), lvalue.node
685 if lvalue.node.final_value is None:
686 if class_name is None:
687 name = lvalue.name
688 else:
689 name = f"{class_name}.{lvalue.name}"
690 assert name is not None, "Full name not set for variable"
691 coerced = self.coerce(rvalue_reg, type_override or self.node_type(lvalue), lvalue.line)
692 self.final_names.append((name, coerced.type))
693 self.add(InitStatic(coerced, name, self.module_name))
694
695 def load_final_static(
696 self, fullname: str, typ: RType, line: int, error_name: str | None = None
697 ) -> Value:
698 split_name = split_target(self.graph, fullname)
699 assert split_name is not None
700 module, name = split_name
701 return self.builder.load_static_checked(
702 typ,
703 name,
704 module,
705 line=line,
706 error_msg=f'value for final name "{error_name}" was not set',
707 )
708
709 def init_type_var(self, value: Value, name: str, line: int) -> None:
710 unique_name = name + "___" + str(line)
711 self.type_var_names.append(unique_name)
712 self.add(InitStatic(value, unique_name, self.module_name, namespace=NAMESPACE_TYPE_VAR))
713
714 def load_type_var(self, name: str, line: int) -> Value:
715 return self.add(
716 LoadStatic(
717 object_rprimitive,
718 name + "___" + str(line),
719 self.module_name,
720 namespace=NAMESPACE_TYPE_VAR,
721 )
722 )
723
724 def load_literal_value(
725 self, val: int | str | bytes | float | complex | bool, line: int = -1
726 ) -> Value:
727 """Load value of a final name, class-level attribute, or constant folded expression."""
728 if isinstance(val, bool):
729 if val:
730 return self.true(line)
731 else:
732 return self.false(line)
733 elif isinstance(val, int):
734 return self.builder.load_int(val)
735 elif isinstance(val, float):
736 return self.builder.load_float(val)
737 elif isinstance(val, str):
738 return self.builder.load_str(val)
739 elif isinstance(val, bytes):
740 return self.builder.load_bytes(val)
741 elif isinstance(val, complex):
742 return self.builder.load_complex(val)
743 else:
744 assert False, "Unsupported literal value"
745
746 def get_assignment_target(
747 self, lvalue: Lvalue, line: int = -1, *, for_read: bool = False
748 ) -> AssignmentTarget:
749 if line == -1:
750 line = lvalue.line
751 if isinstance(lvalue, NameExpr):
752 # If we are visiting a decorator, then the SymbolNode we really want to be looking at
753 # is the function that is decorated, not the entire Decorator node itself.
754 symbol = lvalue.node
755 if isinstance(symbol, Decorator):
756 symbol = symbol.func
757 if symbol is None:
758 # Semantic analyzer doesn't create ad-hoc Vars for special forms.
759 assert lvalue.is_special_form
760 symbol = Var(lvalue.name)
761 if not for_read and isinstance(symbol, Var) and symbol.is_cls:
762 self.error("Cannot assign to the first argument of classmethod", line)
763 if lvalue.kind == LDEF:
764 if symbol not in self.symtables[-1]:
765 if isinstance(symbol, Var) and not isinstance(symbol.type, DeletedType):
766 reg_type = self.type_to_rtype(symbol.type)
767 else:
768 reg_type = self.node_type(lvalue)
769 # If the function is a generator function, then first define a new variable
770 # in the current function's environment class. Next, define a target that
771 # refers to the newly defined variable in that environment class. Add the
772 # target to the table containing class environment variables, as well as the
773 # current environment.
774 if self.fn_info.is_generator or self.fn_info.is_coroutine:
775 return self.add_var_to_env_class(
776 symbol,
777 reg_type,
778 self.fn_info.generator_class,
779 reassign=False,
780 prefix=GENERATOR_ATTRIBUTE_PREFIX,
781 )
782
783 # Otherwise define a new local variable.
784 return self.add_local_reg(symbol, reg_type)
785 else:
786 # Assign to a previously defined variable.
787 return self.lookup(symbol)
788 elif lvalue.kind == GDEF:
789 globals_dict = self.load_globals_dict()
790 name = self.load_str(lvalue.name, line)
791 return AssignmentTargetIndex(globals_dict, name)
792 else:
793 assert False, lvalue.kind
794 elif isinstance(lvalue, IndexExpr):
795 # Indexed assignment x[y] = e
796 base = self.accept(lvalue.base)
797 index = self.accept(lvalue.index)
798 return AssignmentTargetIndex(base, index)
799 elif isinstance(lvalue, MemberExpr):
800 # Attribute assignment x.y = e
801 can_borrow = self.is_native_attr_ref(lvalue)
802 obj = self.accept(lvalue.expr, can_borrow=can_borrow)
803 return AssignmentTargetAttr(obj, lvalue.name, can_borrow=can_borrow)
804 elif isinstance(lvalue, TupleExpr):
805 # Multiple assignment a, ..., b = e
806 star_idx: int | None = None
807 lvalues = []
808 for idx, item in enumerate(lvalue.items):
809 targ = self.get_assignment_target(item)
810 lvalues.append(targ)
811 if isinstance(item, StarExpr):
812 if star_idx is not None:
813 self.error("Two starred expressions in assignment", line)
814 star_idx = idx
815
816 return AssignmentTargetTuple(lvalues, star_idx)
817
818 elif isinstance(lvalue, StarExpr):
819 return self.get_assignment_target(lvalue.expr)
820
821 assert False, "Unsupported lvalue: %r" % lvalue
822
823 def read(
824 self,
825 target: Value | AssignmentTarget,
826 line: int = -1,
827 *,
828 can_borrow: bool = False,
829 allow_error_value: bool = False,
830 ) -> Value:
831 if isinstance(target, Value):
832 return target
833 if isinstance(target, AssignmentTargetRegister):
834 return target.register
835 if isinstance(target, AssignmentTargetIndex):
836 reg = self.gen_method_call(
837 target.base, "__getitem__", [target.index], target.type, line
838 )
839 if reg is not None:
840 return reg
841 assert False, target.base.type
842 if isinstance(target, AssignmentTargetAttr):
843 if isinstance(target.obj.type, RInstance) and target.obj.type.class_ir.is_ext_class:
844 borrow = can_borrow and target.can_borrow
845 return self.add(
846 GetAttr(
847 target.obj,
848 target.attr,
849 line,
850 borrow=borrow,
851 allow_error_value=allow_error_value,
852 )
853 )
854 else:
855 return self.py_get_attr(target.obj, target.attr, line)
856
857 assert False, "Unsupported lvalue: %r" % target
858
859 def read_nullable_attr(self, obj: Value, attr: str, line: int = -1) -> Value:
860 """Read an attribute that might have an error value without raising AttributeError."""
861 assert isinstance(obj.type, RInstance) and obj.type.class_ir.is_ext_class
862 return self.add(GetAttr(obj, attr, line, allow_error_value=True))
863
864 def assign(self, target: Register | AssignmentTarget, rvalue_reg: Value, line: int) -> None:
865 if isinstance(target, Register):
866 self.add(Assign(target, self.coerce_rvalue(rvalue_reg, target.type, line), line))
867 elif isinstance(target, AssignmentTargetRegister):
868 rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line)
869 self.add(Assign(target.register, rvalue_reg, line))
870 elif isinstance(target, AssignmentTargetAttr):
871 if isinstance(target.obj_type, RInstance):
872 setattr = target.obj_type.class_ir.get_method("__setattr__")
873 if setattr:
874 key = self.load_str(target.attr, line)
875 boxed_reg = self.builder.box(rvalue_reg)
876 call = MethodCall(target.obj, setattr.name, [key, boxed_reg], line)
877 self.add(call)
878 else:
879 rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line)
880 self.add(SetAttr(target.obj, target.attr, rvalue_reg, line))
881 else:
882 key = self.load_str(target.attr, line)
883 boxed_reg = self.builder.box(rvalue_reg)
884 self.primitive_op(py_setattr_op, [target.obj, key, boxed_reg], line)
885 elif isinstance(target, AssignmentTargetIndex):
886 if isinstance(target.base.type, RVec):
887 vec_set_item(self.builder, target.base, target.index, rvalue_reg, line)
888 else:
889 target_reg2 = self.gen_method_call(
890 target.base, "__setitem__", [target.index, rvalue_reg], None, line
891 )
892 assert target_reg2 is not None, target.base.type
893 elif isinstance(target, AssignmentTargetTuple):
894 if isinstance(rvalue_reg.type, RTuple) and target.star_idx is None:
895 rtypes = rvalue_reg.type.types
896 assert len(rtypes) == len(target.items)
897 for i in range(len(rtypes)):
898 item_value = self.add(TupleGet(rvalue_reg, i, line))
899 self.assign(target.items[i], item_value, line)
900 elif (
901 is_list_rprimitive(rvalue_reg.type) or is_tuple_rprimitive(rvalue_reg.type)
902 ) and target.star_idx is None:
903 self.process_sequence_assignment(target, rvalue_reg, line)
904 else:
905 self.process_iterator_tuple_assignment(target, rvalue_reg, line)
906 else:
907 assert False, "Unsupported assignment target"
908
909 def coerce_rvalue(self, rvalue: Value, rtype: RType, line: int) -> Value:
910 if is_float_rprimitive(rtype) and is_tagged(rvalue.type):
911 typename = rvalue.type.short_name()
912 if typename == "short_int":
913 typename = "int"
914 self.error(
915 "Incompatible value representations in assignment "
916 + f'(expression has type "{typename}", variable has type "float")',
917 line,
918 )
919 return self.coerce(rvalue, rtype, line)
920
921 def process_sequence_assignment(
922 self, target: AssignmentTargetTuple, rvalue: Value, line: int
923 ) -> None:
924 """Process assignment like 'x, y = s', where s is a variable-length list or tuple."""
925 # Check the length of sequence.
926 expected_len = Integer(len(target.items), c_pyssize_t_rprimitive)
927 self.builder.call_c(check_unpack_count_op, [rvalue, expected_len], line)
928
929 # Read sequence items.
930 values = []
931 for i in range(len(target.items)):
932 item = target.items[i]
933 index: Value
934 if is_list_rprimitive(rvalue.type):
935 index = Integer(i, c_pyssize_t_rprimitive)
936 if not IS_FREE_THREADED:
937 item_value = self.primitive_op(list_get_item_unsafe_op, [rvalue, index], line)
938 else:
939 item_value = self.primitive_op(list_get_item_int64_op, [rvalue, index], line)
940 elif is_tuple_rprimitive(rvalue.type):
941 index = Integer(i, c_pyssize_t_rprimitive)
942 item_value = self.call_c(tuple_get_item_unsafe_op, [rvalue, index], line)
943 else:
944 index = self.builder.load_int(i)
945 item_value = self.builder.gen_method_call(
946 rvalue, "__getitem__", [index], item.type, line
947 )
948 values.append(item_value)
949
950 # Assign sequence items to the target lvalues.
951 for lvalue, value in zip(target.items, values):
952 self.assign(lvalue, value, line)
953
954 def process_iterator_tuple_assignment_helper(
955 self, litem: AssignmentTarget, ritem: Value, line: int
956 ) -> None:
957 error_block, ok_block = BasicBlock(), BasicBlock()
958 self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
959
960 self.activate_block(error_block)
961 self.add(
962 RaiseStandardError(RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line)
963 )
964 self.add(Unreachable())
965
966 self.activate_block(ok_block)
967 self.assign(litem, ritem, line)
968
969 def process_iterator_tuple_assignment(
970 self, target: AssignmentTargetTuple, rvalue_reg: Value, line: int
971 ) -> None:
972 iterator = self.primitive_op(iter_op, [rvalue_reg], line)
973
974 # This may be the whole lvalue list if there is no starred value
975 split_idx = target.star_idx if target.star_idx is not None else len(target.items)
976
977 # Assign values before the first starred value
978 for litem in target.items[:split_idx]:
979 ritem = self.call_c(next_op, [iterator], line)
980 error_block, ok_block = BasicBlock(), BasicBlock()
981 self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
982
983 self.activate_block(error_block)
984 self.add(
985 RaiseStandardError(
986 RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line
987 )
988 )
989 self.add(Unreachable())
990
991 self.activate_block(ok_block)
992
993 self.assign(litem, ritem, line)
994
995 # Assign the starred value and all values after it
996 if target.star_idx is not None:
997 post_star_vals = target.items[split_idx + 1 :]
998 iter_list = self.primitive_op(to_list, [iterator], line)
999 iter_list_len = self.builtin_len(iter_list, line)
1000 post_star_len = Integer(len(post_star_vals))
1001 condition = self.binary_op(post_star_len, iter_list_len, "<=", line)
1002
1003 error_block, ok_block = BasicBlock(), BasicBlock()
1004 self.add(Branch(condition, ok_block, error_block, Branch.BOOL))
1005
1006 self.activate_block(error_block)
1007 self.add(
1008 RaiseStandardError(
1009 RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line
1010 )
1011 )
1012 self.add(Unreachable())
1013
1014 self.activate_block(ok_block)
1015
1016 for litem in reversed(post_star_vals):
1017 ritem = self.primitive_op(list_pop_last, [iter_list], line)
1018 self.assign(litem, ritem, line)
1019
1020 # Assign the starred value
1021 self.assign(target.items[target.star_idx], iter_list, line)
1022
1023 # There is no starred value, so check if there are extra values in rhs that
1024 # have not been assigned.
1025 else:
1026 extra = self.call_c(next_op, [iterator], line)
1027 error_block, ok_block = BasicBlock(), BasicBlock()
1028 self.add(Branch(extra, ok_block, error_block, Branch.IS_ERROR))
1029
1030 self.activate_block(error_block)
1031 self.add(
1032 RaiseStandardError(
1033 RaiseStandardError.VALUE_ERROR, "too many values to unpack", line
1034 )
1035 )
1036 self.add(Unreachable())
1037
1038 self.activate_block(ok_block)
1039
1040 def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None:
1041 self.nonlocal_control.append(
1042 LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block)
1043 )
1044
1045 def pop_loop_stack(self) -> None:
1046 self.nonlocal_control.pop()
1047
1048 def make_spill_target(self, type: RType) -> AssignmentTarget:
1049 """Moves a given Value instance into the generator class' environment class."""
1050 name = f"{TEMP_ATTR_NAME}{self.temp_counter}"
1051 self.temp_counter += 1
1052 target = self.add_var_to_env_class(Var(name), type, self.fn_info.generator_class)
1053 return target
1054
1055 def spill(self, value: Value) -> AssignmentTarget:
1056 """Moves a given Value instance into the generator class' environment class."""
1057 target = self.make_spill_target(value.type)
1058 # Shouldn't be able to fail
1059 self.assign(target, value, NO_TRACEBACK_LINE_NO)
1060 return target
1061
1062 def maybe_spill(self, value: Value) -> Value | AssignmentTarget:
1063 """
1064 Moves a given Value instance into the environment class for generator functions. For
1065 non-generator functions, leaves the Value instance as it is.
1066
1067 Returns an AssignmentTarget associated with the Value for generator functions and the
1068 original Value itself for non-generator functions.
1069 """
1070 if self.fn_info.is_generator:
1071 return self.spill(value)
1072 return value
1073
1074 def maybe_spill_assignable(self, value: Value) -> Register | AssignmentTarget:
1075 """
1076 Moves a given Value instance into the environment class for generator functions. For
1077 non-generator functions, allocate a temporary Register.
1078
1079 Returns an AssignmentTarget associated with the Value for generator functions and an
1080 assignable Register for non-generator functions.
1081 """
1082 if self.fn_info.is_generator:
1083 return self.spill(value)
1084
1085 if isinstance(value, Register):
1086 return value
1087
1088 # Allocate a temporary register for the assignable value.
1089 reg = Register(value.type)
1090 self.assign(reg, value, NO_TRACEBACK_LINE_NO)
1091 return reg
1092
1093 def extract_int(self, e: Expression) -> int | None:
1094 folded = constant_fold_expr(self, e)
1095 return folded if isinstance(folded, int) else None
1096
1097 def get_sequence_type(self, expr: Expression) -> RType:
1098 return self.get_sequence_type_from_type(self.types[expr])
1099
1100 def get_sequence_type_from_type(self, target_type: Type) -> RType:
1101 target_type = get_proper_type(target_type)
1102 if isinstance(target_type, UnionType):
1103 return RUnion.make_simplified_union(
1104 [self.get_sequence_type_from_type(item) for item in target_type.items]
1105 )
1106 elif isinstance(target_type, Instance):
1107 if target_type.type.fullname == "builtins.str":
1108 return str_rprimitive
1109 elif target_type.type.fullname == "builtins.bytes":
1110 return bytes_rprimitive
1111 try:
1112 return self.type_to_rtype(target_type.args[0])
1113 except IndexError:
1114 raise ValueError(f"{target_type!r} is not a valid sequence.") from None
1115 # This elif-blocks are needed for iterating over classes derived from NamedTuple.
1116 elif isinstance(target_type, TypeVarLikeType):
1117 return self.get_sequence_type_from_type(target_type.upper_bound)
1118 elif isinstance(target_type, TupleType):
1119 items = target_type.items
1120 assert items, "This function does not support empty tuples"
1121 # Tuple might have elements of different types.
1122 rtypes = list(dict.fromkeys(self.mapper.type_to_rtype(item) for item in items))
1123 if len(rtypes) == 1:
1124 return rtypes.pop()
1125 else:
1126 return RUnion.make_simplified_union(rtypes)
1127 assert False, target_type
1128
1129 def get_dict_base_type(self, expr: Expression) -> list[Instance]:
1130 """Find dict type of a dict-like expression.
1131
1132 This is useful for dict subclasses like SymbolTable.
1133 """
1134 return self.get_dict_base_type_from_type(self.types[expr])
1135
1136 def get_dict_base_type_from_type(self, target_type: Type) -> list[Instance]:
1137 target_type = get_proper_type(target_type)
1138 if isinstance(target_type, UnionType):
1139 return [
1140 inner
1141 for item in target_type.items
1142 for inner in self.get_dict_base_type_from_type(item)
1143 ]
1144 if isinstance(target_type, TypeVarLikeType):
1145 # Match behaviour of self.node_type
1146 # We can only reach this point if `target_type` was a TypeVar(bound=dict[...])
1147 # or a ParamSpec.
1148 return self.get_dict_base_type_from_type(target_type.upper_bound)
1149
1150 if isinstance(target_type, TypedDictType):
1151 target_type = target_type.fallback
1152 dict_base = next(
1153 base for base in target_type.type.mro if base.fullname == "typing.Mapping"
1154 )
1155 elif isinstance(target_type, Instance):
1156 dict_base = next(
1157 base for base in target_type.type.mro if base.fullname == "builtins.dict"
1158 )
1159 else:
1160 assert False, f"Failed to extract dict base from {target_type}"
1161 return [map_instance_to_supertype(target_type, dict_base)]
1162
1163 def get_dict_key_type(self, expr: Expression) -> RType:
1164 dict_base_types = self.get_dict_base_type(expr)
1165 rtypes = [self.type_to_rtype(t.args[0]) for t in dict_base_types]
1166 return RUnion.make_simplified_union(rtypes)
1167
1168 def get_dict_value_type(self, expr: Expression) -> RType:
1169 dict_base_types = self.get_dict_base_type(expr)
1170 rtypes = [self.type_to_rtype(t.args[1]) for t in dict_base_types]
1171 return RUnion.make_simplified_union(rtypes)
1172
1173 def get_dict_item_type(self, expr: Expression) -> RType:
1174 key_type = self.get_dict_key_type(expr)
1175 value_type = self.get_dict_value_type(expr)
1176 return RTuple([key_type, value_type])
1177
1178 def _analyze_iterable_item_type(self, expr: Expression) -> Type:
1179 """Return the item type given by 'expr' in an iterable context."""
1180 # This logic is copied from mypy's TypeChecker.analyze_iterable_item_type.
1181 if expr not in self.types:
1182 # Mypy thinks this is unreachable.
1183 iterable: ProperType = AnyType(TypeOfAny.from_error)
1184 else:
1185 iterable = get_proper_type(self.types[expr])
1186 echk = self.graph[self.module_name].type_checker().expr_checker
1187 iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], expr)[0]
1188
1189 from mypy.join import join_types
1190
1191 if isinstance(iterable, TupleType):
1192 joined: Type = UninhabitedType()
1193 for item in iterable.items:
1194 joined = join_types(joined, item)
1195 return joined
1196 else:
1197 # Non-tuple iterable.
1198 return echk.check_method_call_by_name("__next__", iterator, [], [], expr)[0]
1199
1200 def is_native_module(self, module: str) -> bool:
1201 """Is the given module one compiled by mypyc?"""
1202 return self.mapper.is_native_module(module)
1203
1204 def is_same_group_module(self, module: str) -> bool:
1205 """Is the given module in the same compilation group as the current module?
1206
1207 Modules in the same group share a compiled C extension and can reference
1208 each other's C-level symbols directly. Modules in separate groups (separate
1209 compilation mode) must use the Python import system instead.
1210 """
1211 return self.mapper.group_map.get(module) == self.mapper.group_map.get(self.module_name)
1212
1213 def is_package_module(self, module: str) -> bool:
1214 """Is the given module a package (i.e., an __init__.py file)?"""
1215 st = self.graph.get(module)
1216 return st is not None and st.tree is not None and st.tree.is_package_init_file()
1217
1218 def is_native_ref_expr(self, expr: RefExpr) -> bool:
1219 return self.mapper.is_native_ref_expr(expr)
1220
1221 def is_native_module_ref_expr(self, expr: RefExpr) -> bool:
1222 return self.mapper.is_native_module_ref_expr(expr)
1223
1224 def is_synthetic_type(self, typ: TypeInfo) -> bool:
1225 """Is a type something other than just a class we've created?"""
1226 return typ.is_named_tuple or typ.is_newtype or typ.typeddict_type is not None
1227
1228 def get_final_ref(self, expr: MemberExpr) -> tuple[str, Var, bool] | None:
1229 """Check if `expr` is a final class or module attribute.
1230
1231 Return False for instance attributes.
1232
1233 This needs to be done differently for class and module attributes to
1234 correctly determine fully qualified name. Return a tuple that consists of
1235 the qualified name, the corresponding Var node, and a flag indicating whether
1236 the final name was defined in a compiled module. Return None if `expr` does not
1237 refer to a final attribute.
1238 """
1239 final_var = None
1240 if isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, TypeInfo):
1241 # a class attribute
1242 sym = expr.expr.node.get(expr.name)
1243 if sym and isinstance(sym.node, Var):
1244 # Enum attribute are treated as final since they are added to the global cache
1245 expr_fullname = expr.expr.node.bases[0].type.fullname
1246 is_final = sym.node.is_final or expr_fullname == "enum.Enum"
1247 if is_final:
1248 final_var = sym.node
1249 fullname = f"{sym.node.info.fullname}.{final_var.name}"
1250 native = self.is_native_module(expr.expr.node.module_name)
1251 elif self.is_module_member_expr(expr):
1252 # a module attribute
1253 if isinstance(expr.node, Var) and expr.node.is_final:
1254 final_var = expr.node
1255 fullname = expr.node.fullname
1256 native = self.is_native_ref_expr(expr)
1257 if final_var is not None:
1258 return fullname, final_var, native
1259 return None
1260
1261 def emit_load_final(
1262 self, final_var: Var, fullname: str, name: str, native: bool, typ: Type, line: int
1263 ) -> Value | None:
1264 """Emit code for loading value of a final name (if possible).
1265
1266 Args:
1267 final_var: Var corresponding to the final name
1268 fullname: its qualified name
1269 name: shorter name to show in errors
1270 native: whether the name was defined in a compiled module
1271 typ: its type
1272 line: line number where loading occurs
1273 """
1274 if final_var.final_value is not None: # this is safe even for non-native names
1275 return self.load_literal_value(final_var.final_value, line)
1276 elif native and module_prefix(self.graph, fullname):
1277 return self.load_final_static(fullname, self.mapper.type_to_rtype(typ), line, name)
1278 else:
1279 return None
1280
1281 def is_module_member_expr(self, expr: MemberExpr) -> bool:
1282 return isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, MypyFile)
1283
1284 def call_refexpr_with_args(
1285 self, expr: CallExpr, callee: RefExpr, arg_values: list[Value]
1286 ) -> Value:
1287 # Handle data-driven special-cased primitive call ops.
1288 if callee.fullname and expr.arg_kinds == [ARG_POS] * len(arg_values):
1289 fullname = get_call_target_fullname(callee)
1290 primitive_candidates = function_ops.get(fullname, [])
1291 target = self.builder.matching_primitive_op(
1292 primitive_candidates, arg_values, expr.line, self.node_type(expr)
1293 )
1294 if target:
1295 return target
1296
1297 # Standard native call if signature and fullname are good and all arguments are positional
1298 # or named.
1299 callee_node = callee.node
1300 if isinstance(callee_node, OverloadedFuncDef):
1301 callee_node = callee_node.impl
1302 # TODO: use native calls for any decorated functions which have all their decorators
1303 # removed, not just singledispatch functions (which we don't do now just in case those
1304 # decorated functions are callable classes or cannot be called without the python API for
1305 # some other reason)
1306 if (
1307 isinstance(callee_node, Decorator)
1308 and callee_node.func not in self.fdefs_to_decorators
1309 and callee_node.func in self.singledispatch_impls
1310 ):
1311 callee_node = callee_node.func
1312 if (
1313 callee_node is not None
1314 and callee.fullname
1315 and callee_node in self.mapper.func_to_decl
1316 and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)
1317 ):
1318 decl = self.mapper.func_to_decl[callee_node]
1319 return self.builder.call(decl, arg_values, expr.arg_kinds, expr.arg_names, expr.line)
1320
1321 # Fall back to a Python call
1322 function = self.accept(callee)
1323 return self.py_call(
1324 function, arg_values, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names
1325 )
1326
1327 def shortcircuit_expr(self, expr: OpExpr) -> Value:
1328 def handle_right() -> Value:
1329 if expr.right_unreachable:
1330 self.builder.add(
1331 RaiseStandardError(
1332 RaiseStandardError.RUNTIME_ERROR,
1333 "mypyc internal error: should be unreachable",
1334 expr.right.line,
1335 )
1336 )
1337 return self.builder.none()
1338 return self.accept(expr.right)
1339
1340 return self.builder.shortcircuit_helper(
1341 expr.op, self.node_type(expr), lambda: self.accept(expr.left), handle_right, expr.line
1342 )
1343
1344 # Basic helpers
1345
1346 def flatten_classes(self, arg: RefExpr | TupleExpr) -> list[ClassIR] | None:
1347 """Flatten classes in isinstance(obj, (A, (B, C))).
1348
1349 If at least one item is not a reference to a native class, return None.
1350 """
1351 if isinstance(arg, RefExpr):
1352 if isinstance(arg.node, TypeInfo) and self.is_native_module_ref_expr(arg):
1353 ir = self.mapper.type_to_ir.get(arg.node)
1354 if ir:
1355 return [ir]
1356 return None
1357 else:
1358 res: list[ClassIR] = []
1359 for item in arg.items:
1360 if isinstance(item, (RefExpr, TupleExpr)):
1361 item_part = self.flatten_classes(item)
1362 if item_part is None:
1363 return None
1364 res.extend(item_part)
1365 else:
1366 return None
1367 return res
1368
1369 def enter(self, fn_info: FuncInfo | str = "", *, ret_type: RType = none_rprimitive) -> None:
1370 if isinstance(fn_info, str):
1371 fn_info = FuncInfo(name=fn_info)
1372 self.builder = LowLevelIRBuilder(self.errors, self.options)
1373 self.builder.set_module(self.module_name, self.module_path)
1374 self.builders.append(self.builder)
1375 self.symtables.append({})
1376 self.runtime_args.append([])
1377 self.fn_info = fn_info
1378 self.fn_infos.append(self.fn_info)
1379 self.ret_types.append(ret_type)
1380 # A function body is its own top-level expression context, even when the
1381 # function (e.g. a lambda) is being generated in the middle of an outer
1382 # expression. Save the outer expression state and start fresh.
1383 self.expression_depth_stack.append(self.expression_depth)
1384 self.reassigned_in_expr_stack.append(self.reassigned_in_expr)
1385 self.expr_has_suspend_stack.append(self.expr_has_suspend)
1386 self.expression_depth = 0
1387 self.reassigned_in_expr = set()
1388 self.expr_has_suspend = False
1389 if fn_info.is_generator:
1390 self.nonlocal_control.append(GeneratorNonlocalControl())
1391 else:
1392 self.nonlocal_control.append(BaseNonlocalControl())
1393 self.activate_block(BasicBlock())
1394
1395 def leave(self) -> tuple[list[Register], list[RuntimeArg], list[BasicBlock], RType, FuncInfo]:
1396 builder = self.builders.pop()
1397 self.symtables.pop()
1398 runtime_args = self.runtime_args.pop()
1399 ret_type = self.ret_types.pop()
1400 fn_info = self.fn_infos.pop()
1401 self.nonlocal_control.pop()
1402 self.expression_depth = self.expression_depth_stack.pop()
1403 self.reassigned_in_expr = self.reassigned_in_expr_stack.pop()
1404 self.expr_has_suspend = self.expr_has_suspend_stack.pop()
1405 self.builder = self.builders[-1]
1406 self.fn_info = self.fn_infos[-1]
1407 return builder.args, runtime_args, builder.blocks, ret_type, fn_info
1408
1409 @contextmanager
1410 def enter_scope(self, fn_info: FuncInfo) -> Iterator[None]:
1411 """Push a lightweight scope for comprehensions.
1412
1413 Unlike enter(), this reuses the same LowLevelIRBuilder (same basic
1414 blocks and registers) but pushes new symtable and fn_info entries
1415 so that the closure machinery sees a scope boundary.
1416 """
1417 self.builders.append(self.builder)
1418 # Copy the parent symtable so variables from the enclosing scope
1419 # (e.g. function parameters used as the comprehension iterable)
1420 # remain accessible. The comprehension is inlined (same basic blocks
1421 # and registers), so the parent's register references are still valid.
1422 self.symtables.append(dict(self.symtables[-1]))
1423 self.runtime_args.append([])
1424 self.fn_info = fn_info
1425 self.fn_infos.append(self.fn_info)
1426 self.ret_types.append(none_rprimitive)
1427 self.nonlocal_control.append(BaseNonlocalControl())
1428 try:
1429 yield
1430 finally:
1431 self.builders.pop()
1432 self.symtables.pop()
1433 self.runtime_args.pop()
1434 self.ret_types.pop()
1435 self.fn_infos.pop()
1436 self.nonlocal_control.pop()
1437 self.builder = self.builders[-1]
1438 self.fn_info = self.fn_infos[-1]
1439
1440 @contextmanager
1441 def enter_borrow_scope(self, line: int) -> Iterator[None]:
1442 """Enter new borrow scope from which borrows can't leak to outer expressions.
1443
1444 This is a borrow region (see LowLevelIRBuilder.borrow_region) that also
1445 resets the per-expression borrowing heuristic state, since the body forms
1446 its own top-level expression context (e.g. a comprehension iteration or a
1447 lambda body).
1448 """
1449 old_expression_depth = self.expression_depth
1450 old_reassigned_in_expr = self.reassigned_in_expr
1451 old_expr_has_suspend = self.expr_has_suspend
1452 self.expression_depth = 0
1453 try:
1454 with self.builder.borrow_region(line):
1455 yield
1456 finally:
1457 self.expression_depth = old_expression_depth
1458 self.reassigned_in_expr = old_reassigned_in_expr
1459 self.expr_has_suspend = old_expr_has_suspend
1460
1461 @contextmanager
1462 def enter_method(
1463 self,
1464 class_ir: ClassIR,
1465 name: str,
1466 ret_type: RType,
1467 fn_info: FuncInfo | str = "",
1468 self_type: RType | None = None,
1469 internal: bool = False,
1470 ) -> Iterator[None]:
1471 """Generate IR for a method.
1472
1473 If the method takes arguments, you should immediately afterwards call
1474 add_argument() for each non-self argument (self is created implicitly).
1475
1476 Args:
1477 class_ir: Add method to this class
1478 name: Short name of the method
1479 ret_type: Return type of the method
1480 fn_info: Optionally, additional information about the method
1481 self_type: If not None, override default type of the implicit 'self'
1482 argument (by default, derive type from class_ir)
1483 """
1484 self.enter(fn_info, ret_type=ret_type)
1485 self.function_name_stack.append(name)
1486 self.class_ir_stack.append(class_ir)
1487 if self_type is None:
1488 self_type = RInstance(class_ir)
1489 self.add_argument(SELF_NAME, self_type)
1490 try:
1491 yield
1492 finally:
1493 arg_regs, args, blocks, ret_type, fn_info = self.leave()
1494 sig = FuncSignature(args, ret_type)
1495 name = self.function_name_stack.pop()
1496 class_ir = self.class_ir_stack.pop()
1497 decl = FuncDecl(name, class_ir.name, self.module_name, sig, internal=internal)
1498 ir = FuncIR(decl, arg_regs, blocks)
1499 class_ir.methods[name] = ir
1500 class_ir.method_decls[name] = ir.decl
1501 self.functions.append(ir)
1502
1503 def add_argument(self, var: str | Var, typ: RType, kind: ArgKind = ARG_POS) -> Register:
1504 """Declare an argument in the current function.
1505
1506 You should use this instead of directly calling add_local() in new code.
1507 """
1508 if isinstance(var, str):
1509 var = Var(var)
1510 reg = self.add_local(var, typ, is_arg=True)
1511 self.runtime_args[-1].append(RuntimeArg(var.name, typ, kind))
1512 return reg
1513
1514 def lookup(self, symbol: SymbolNode) -> SymbolTarget:
1515 return self.symtables[-1][symbol]
1516
1517 def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> Register:
1518 """Add register that represents a symbol to the symbol table.
1519
1520 Args:
1521 is_arg: is this a function argument
1522 """
1523 assert isinstance(symbol, SymbolNode), symbol
1524 reg = Register(
1525 typ, remangle_redefinition_name(symbol.name), is_arg=is_arg, line=symbol.line
1526 )
1527 self.symtables[-1][symbol] = AssignmentTargetRegister(reg)
1528 if is_arg:
1529 self.builder.args.append(reg)
1530 return reg
1531
1532 def add_local_reg(
1533 self, symbol: SymbolNode, typ: RType, is_arg: bool = False
1534 ) -> AssignmentTargetRegister:
1535 """Like add_local, but return an assignment target instead of value."""
1536 self.add_local(symbol, typ, is_arg)
1537 target = self.symtables[-1][symbol]
1538 assert isinstance(target, AssignmentTargetRegister), target
1539 return target
1540
1541 def add_self_to_env(self, cls: ClassIR) -> AssignmentTargetRegister:
1542 """Low-level function that adds a 'self' argument.
1543
1544 This is only useful if using enter() instead of enter_method().
1545 """
1546 return self.add_local_reg(Var(SELF_NAME), RInstance(cls), is_arg=True)
1547
1548 def add_target(self, symbol: SymbolNode, target: SymbolTarget) -> SymbolTarget:
1549 self.symtables[-1][symbol] = target
1550 return target
1551
1552 def type_to_rtype(self, typ: Type | None) -> RType:
1553 return self.mapper.type_to_rtype(typ)
1554
1555 def node_type(self, node: Expression) -> RType:
1556 if isinstance(node, IntExpr):
1557 # TODO: Don't special case IntExpr
1558 return int_rprimitive
1559 if node not in self.types:
1560 return object_rprimitive
1561 mypy_type = self.types[node]
1562 return self.type_to_rtype(mypy_type)
1563
1564 def add_var_to_env_class(
1565 self,
1566 var: SymbolNode,
1567 rtype: RType,
1568 base: FuncInfo | ImplicitClass,
1569 reassign: bool = False,
1570 always_defined: bool = False,
1571 keep_alive_on_completion: bool = False,
1572 prefix: str = "",
1573 ) -> AssignmentTarget:
1574 # First, define the variable name as an attribute of the environment class, and then
1575 # construct a target for that attribute.
1576 name = prefix + remangle_redefinition_name(var.name)
1577 self.fn_info.env_class.attributes[name] = rtype
1578 if keep_alive_on_completion:
1579 self.fn_info.env_class.attrs_to_keep_alive_on_completion.add(name)
1580 if always_defined:
1581 self.fn_info.env_class.attrs_with_defaults.add(name)
1582 attr_target = AssignmentTargetAttr(base.curr_env_reg, name)
1583
1584 if reassign:
1585 # Read the local definition of the variable, and set the corresponding attribute of
1586 # the environment class' variable to be that value.
1587 reg = self.read(self.lookup(var), self.fn_info.fitem.line)
1588 self.add(SetAttr(base.curr_env_reg, name, reg, self.fn_info.fitem.line))
1589
1590 # Override the local definition of the variable to instead point at the variable in
1591 # the environment class.
1592 return self.add_target(var, attr_target)
1593
1594 def is_builtin_ref_expr(self, expr: RefExpr) -> bool:
1595 assert expr.node, "RefExpr not resolved"
1596 return "." in expr.node.fullname and expr.node.fullname.split(".")[0] == "builtins"
1597
1598 def load_global(self, expr: NameExpr) -> Value:
1599 """Loads a Python-level global.
1600
1601 This takes a NameExpr and uses its name as a key to retrieve the corresponding PyObject *
1602 from the _globals dictionary in the C-generated code.
1603 """
1604 # If the global is from 'builtins', turn it into a module attr load instead
1605 if self.is_builtin_ref_expr(expr):
1606 assert expr.node, "RefExpr not resolved"
1607 return self.load_module_attr_by_fullname(expr.node.fullname, expr.line)
1608 if (
1609 self.is_native_module_ref_expr(expr)
1610 and isinstance(expr.node, TypeInfo)
1611 and not self.is_synthetic_type(expr.node)
1612 ):
1613 assert expr.fullname
1614 return self.load_native_type_object(expr.fullname)
1615 return self.load_global_str(expr.name, expr.line)
1616
1617 def load_global_str(self, name: str, line: int) -> Value:
1618 _globals = self.load_globals_dict()
1619 reg = self.load_str(name, line)
1620 return self.primitive_op(dict_get_item_op, [_globals, reg], line)
1621
1622 def load_globals_dict(self) -> Value:
1623 module = self.globals_lookup_module or self.module_name
1624 return self.add(LoadStatic(dict_rprimitive, "globals", module))
1625
1626 def load_module_attr_by_fullname(self, fullname: str, line: int) -> Value:
1627 module, _, name = fullname.rpartition(".")
1628 left = self.load_module(module)
1629 return self.py_get_attr(left, name, line)
1630
1631 def is_native_attr_ref(self, expr: MemberExpr) -> bool:
1632 """Is expr a direct reference to a native (struct) attribute of an instance?"""
1633 obj_rtype = self.node_type(expr.expr)
1634 return (
1635 isinstance(obj_rtype, RInstance)
1636 and obj_rtype.class_ir.is_ext_class
1637 and any(expr.name in ir.attributes for ir in obj_rtype.class_ir.mro)
1638 )
1639
1640 def is_final_native_attr_ref(self, expr: MemberExpr) -> bool:
1641 """Is expr a direct reference to a Final native (struct) attribute of an instance?
1642
1643 A Final attribute is read-only at runtime (it has no setter), so it can never be
1644 reassigned after construction. This makes it safe to borrow even on free-threaded
1645 builds, since no concurrent store can invalidate the borrowed reference.
1646 """
1647 obj_rtype = self.node_type(expr.expr)
1648 return (
1649 isinstance(obj_rtype, RInstance)
1650 and obj_rtype.class_ir.is_ext_class
1651 and obj_rtype.class_ir.is_final_attr(expr.name)
1652 )
1653
1654 def root_is_reassigned(self, v: Value) -> bool:
1655 """Is the root local variable a borrow chain 'v' reads from reassigned this expression?
1656
1657 A whole-expression borrow of an attribute keeps the borrow root alive only
1658 via the register holding it. If that register belongs to a local variable
1659 that is rebound (via a walrus assignment) during the same top-level
1660 expression, the old value may be freed while the borrow is still live.
1661 """
1662 if not self.reassigned_in_expr:
1663 return False
1664 # Peel borrowed links back to the root value the chain reads from.
1665 while True:
1666 if isinstance(v, GetAttr) and v.is_borrowed:
1667 v = v.obj
1668 elif isinstance(v, Cast) and v.is_borrowed:
1669 v = v.src
1670 else:
1671 break
1672 if not isinstance(v, Register):
1673 return False
1674 for symbol in self.reassigned_in_expr:
1675 target = self.symtables[-1].get(symbol)
1676 if isinstance(target, AssignmentTargetRegister) and target.register is v:
1677 return True
1678 return False
1679
1680 def mark_block_unreachable(self) -> None:
1681 """Mark statements in the innermost block being processed as unreachable.
1682
1683 This should be called after a statement that unconditionally leaves the
1684 block, such as 'break' or 'return'.
1685 """
1686 self.block_reachable_stack[-1] = False
1687
1688 # Lacks a good type because there wasn't a reasonable type in 3.5 :(
1689 def catch_errors(self, line: int) -> Any:
1690 return catch_errors(self.module_path, line)
1691
1692 def warning(self, msg: str, line: int) -> None:
1693 self.errors.warning(msg, self.module_path, line)
1694
1695 def error(self, msg: str, line: int) -> None:
1696 self.errors.error(msg, self.module_path, line)
1697
1698 def note(self, msg: str, line: int) -> None:
1699 self.errors.note(msg, self.module_path, line)
1700
1701 def add_function(self, func_ir: FuncIR, line: int) -> None:
1702 name = (func_ir.class_name, func_ir.name)
1703 if name in self.function_names:
1704 self.error(f'Duplicate definition of "{name[1]}" not supported by mypyc', line)
1705 return
1706 self.function_names.add(name)
1707 self.functions.append(func_ir)
1708
1709 def get_current_class_ir(self) -> ClassIR | None:
1710 type_info = self.fn_info.fitem.info
1711 return self.mapper.type_to_ir.get(type_info)
1712
1713 def add_coroutine_setup_call(self, class_name: str, obj: Value) -> Value:
1714 return self.add(
1715 Call(
1716 FuncDecl(
1717 class_name + "_coroutine_setup",
1718 None,
1719 self.module_name,
1720 FuncSignature([RuntimeArg("type", object_rprimitive)], bool_rprimitive),
1721 ),
1722 [obj],
1723 obj.line,
1724 )
1725 )
1726
1727 def load_builtin(self, name: str, line: int) -> Value | None:
1728 return self.builder.load_builtin(name, line)
1729
1730
1731 def gen_arg_defaults(builder: IRBuilder) -> None:
1732 """Generate blocks for arguments that have default values.
1733
1734 If the passed value is an error value, then assign the default
1735 value to the argument.
1736 """
1737 fitem = builder.fn_info.fitem
1738 nb = 0
1739 for arg in fitem.arguments:
1740 if arg.initializer:
1741 target = builder.lookup(arg.variable)
1742
1743 def get_default() -> Value:
1744 assert arg.initializer is not None
1745
1746 # If it is constant, don't bother storing it
1747 if is_constant(arg.initializer):
1748 return builder.accept(arg.initializer)
1749
1750 # Because gen_arg_defaults runs before calculate_arg_defaults, we
1751 # add the static/attribute to final_names/the class here.
1752 elif not builder.fn_info.is_nested:
1753 name = fitem.fullname + "." + arg.variable.name
1754 builder.final_names.append((name, target.type))
1755 return builder.add(LoadStatic(target.type, name, builder.module_name))
1756 else:
1757 name = arg.variable.name
1758 builder.fn_info.callable_class.ir.attributes[name] = target.type
1759 return builder.add(
1760 GetAttr(builder.fn_info.callable_class.self_reg, name, arg.line)
1761 )
1762
1763 assert isinstance(target, AssignmentTargetRegister), target
1764 reg = target.register
1765 if not reg.type.error_overlap:
1766 builder.assign_if_null(target.register, get_default, arg.initializer.line)
1767 else:
1768 builder.assign_if_bitmap_unset(
1769 target.register, get_default, nb, arg.initializer.line
1770 )
1771 nb += 1
1772
1773
1774 def remangle_redefinition_name(name: str) -> str:
1775 """Remangle names produced by mypy when allow-redefinition-old is used and a name
1776 is used with multiple types within a single block.
1777
1778 We only need to do this for locals, because the name is used as the name of the register;
1779 for globals, the name itself is stored in a register for the purpose of doing dict
1780 lookups.
1781 """
1782 return name.replace("'", "__redef__")
1783
1784
1785 def get_call_target_fullname(ref: RefExpr) -> str:
1786 if isinstance(ref.node, TypeAlias):
1787 # Resolve simple type aliases. In calls they evaluate to the type they point to.
1788 target = get_proper_type(ref.node.target)
1789 if isinstance(target, Instance):
1790 return target.type.fullname
1791 return ref.fullname
1792
1793
1794 class WalrusTargetCollector(TraverserVisitor):
1795 """Collect the symbols assigned to by walrus expressions in a subtree."""
1796
1797 def __init__(self) -> None:
1798 self.targets: set[SymbolNode] = set()
1799
1800 def visit_assignment_expr(self, o: AssignmentExpr) -> None:
1801 if o.target.node is not None:
1802 self.targets.add(o.target.node)
1803 super().visit_assignment_expr(o)
1804
1805 def visit_lambda_expr(self, o: LambdaExpr) -> None:
1806 # A lambda body forms its own expression context, so don't descend into it.
1807 pass
1808
1809
1810 def find_walrus_targets(expr: Expression) -> set[SymbolNode]:
1811 """Return the symbols reassigned via a walrus expression within 'expr'.
1812
1813 Walrus (':=') is the only way to rebind a variable in the middle of evaluating
1814 an expression, so this is the complete set of in-expression reassignments.
1815 """
1816 collector = WalrusTargetCollector()
1817 expr.accept(collector)
1818 return collector.targets
1819
1820
1821 class SuspendDetector(TraverserVisitor):
1822 """Detect await/yield/yield from expressions in a subtree."""
1823
1824 def __init__(self) -> None:
1825 self.found = False
1826
1827 def visit_await_expr(self, o: AwaitExpr) -> None:
1828 self.found = True
1829
1830 def visit_yield_expr(self, o: YieldExpr) -> None:
1831 self.found = True
1832
1833 def visit_yield_from_expr(self, o: YieldFromExpr) -> None:
1834 self.found = True
1835
1836 def visit_generator_expr(self, o: GeneratorExpr) -> None:
1837 # An 'async for' clause suspends via an implicit await on __anext__ that
1838 # isn't represented as an AwaitExpr node in the AST (list/set comprehensions
1839 # delegate to a GeneratorExpr, so they are covered here too).
1840 if any(o.is_async):
1841 self.found = True
1842 super().visit_generator_expr(o)
1843
1844 def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> None:
1845 if any(o.is_async):
1846 self.found = True
1847 super().visit_dictionary_comprehension(o)
1848
1849 def visit_lambda_expr(self, o: LambdaExpr) -> None:
1850 # A lambda body forms its own function (and suspension) context.
1851 pass
1852
1853
1854 def expr_has_suspend(expr: Expression) -> bool:
1855 """Does evaluating 'expr' involve a suspension point (await/yield/yield from)?
1856
1857 A whole-expression borrow can't safely span a suspension point, since the
1858 borrowed value and its borrow root are held in registers that aren't spilled
1859 into the generator environment across the suspend.
1860 """
1861 detector = SuspendDetector()
1862 expr.accept(detector)
1863 return detector.found
1864
1865
1866 def create_type_params(
1867 builder: IRBuilder, typing_mod: Value, type_args: list[TypeParam], line: int
1868 ) -> list[Value]:
1869 """Create objects representing various kinds of Python 3.12 type parameters.
1870
1871 The "typing_mod" argument is the "_typing" module object. The type objects
1872 are looked up from it.
1873
1874 The returned list has one item for each "type_args" item, in the same order.
1875 Each item is either a TypeVar, TypeVarTuple or ParamSpec instance.
1876 """
1877 tvs = []
1878 type_var_imported: Value | None = None
1879 for type_param in type_args:
1880 if type_param.kind == TYPE_VAR_KIND:
1881 if type_var_imported:
1882 # Reuse previously imported value as a minor optimization
1883 tvt = type_var_imported
1884 else:
1885 tvt = builder.py_get_attr(typing_mod, "TypeVar", line)
1886 type_var_imported = tvt
1887 elif type_param.kind == TYPE_VAR_TUPLE_KIND:
1888 tvt = builder.py_get_attr(typing_mod, "TypeVarTuple", line)
1889 else:
1890 assert type_param.kind == PARAM_SPEC_KIND
1891 tvt = builder.py_get_attr(typing_mod, "ParamSpec", line)
1892 if type_param.kind != TYPE_VAR_TUPLE_KIND:
1893 # To match runtime semantics, pass infer_variance=True
1894 tv = builder.py_call(
1895 tvt,
1896 [builder.load_str(type_param.name, line), builder.true(line)],
1897 line,
1898 arg_kinds=[ARG_POS, ARG_NAMED],
1899 arg_names=[None, "infer_variance"],
1900 )
1901 else:
1902 tv = builder.py_call(tvt, [builder.load_str(type_param.name, line)], line)
1903 builder.init_type_var(tv, type_param.name, line)
1904 tvs.append(tv)
1905 return tvs
1906
1907
1908 def calculate_arg_defaults(
1909 builder: IRBuilder,
1910 fn_info: FuncInfo,
1911 func_reg: Value | None,
1912 symtable: dict[SymbolNode, SymbolTarget],
1913 ) -> None:
1914 """Calculate default argument values and store them.
1915
1916 They are stored in statics for top level functions and in
1917 the function objects for nested functions (while constants are
1918 still stored computed on demand).
1919 """
1920 fitem = fn_info.fitem
1921 for arg in fitem.arguments:
1922 # Constant values don't get stored but just recomputed
1923 if arg.initializer and not is_constant(arg.initializer):
1924 value = builder.coerce(
1925 builder.accept(arg.initializer), symtable[arg.variable].type, arg.line
1926 )
1927 if not fn_info.is_nested:
1928 name = fitem.fullname + "." + arg.variable.name
1929 builder.add(InitStatic(value, name, builder.module_name))
1930 else:
1931 assert func_reg is not None
1932 builder.add(SetAttr(func_reg, arg.variable.name, value, arg.line))