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