Debian Codegraph @

mypyc/irbuild/prepare.py

raw
1 """Prepare for IR transform.
2
3 This needs to run after type checking and before generating IR.
4
5 For example, construct partially initialized FuncIR and ClassIR
6 objects for all functions and classes. This allows us to bind
7 references to functions and classes before we've generated full IR for
8 functions or classes. The actual IR transform will then populate all
9 the missing bits, such as function bodies (basic blocks).
10
11 Also build a mapping from mypy TypeInfos to ClassIR objects.
12 """
13
14 from __future__ import annotations
15
16 from collections import defaultdict
17 from collections.abc import Iterable
18 from typing import Final, NamedTuple
19
20 from mypy.build import Graph
21 from mypy.nodes import (
22 ARG_STAR,
23 ARG_STAR2,
24 AssignmentStmt,
25 CallExpr,
26 ClassDef,
27 Decorator,
28 Expression,
29 FuncDef,
30 IndexExpr,
31 MemberExpr,
32 MypyFile,
33 NameExpr,
34 OverloadedFuncDef,
35 RefExpr,
36 SymbolNode,
37 TypeInfo,
38 Var,
39 )
40 from mypy.semanal import refers_to_fullname
41 from mypy.traverser import TraverserVisitor
42 from mypy.types import Instance, Type, get_proper_type
43 from mypyc.common import (
44 FAST_PREFIX,
45 MYPYC_DEFAULTS_SETUP,
46 PROPSET_PREFIX,
47 SELF_NAME,
48 get_id_from_name,
49 )
50 from mypyc.crash import catch_errors
51 from mypyc.errors import Errors
52 from mypyc.ir.class_ir import ClassIR
53 from mypyc.ir.func_ir import (
54 FUNC_CLASSMETHOD,
55 FUNC_NORMAL,
56 FUNC_STATICMETHOD,
57 FuncDecl,
58 FuncSignature,
59 RuntimeArg,
60 )
61 from mypyc.ir.ops import DeserMaps
62 from mypyc.ir.rtypes import (
63 RInstance,
64 RType,
65 bool_rprimitive,
66 dict_rprimitive,
67 none_rprimitive,
68 object_pointer_rprimitive,
69 object_rprimitive,
70 tuple_rprimitive,
71 )
72 from mypyc.irbuild.mapper import Mapper
73 from mypyc.irbuild.util import (
74 dataclass_type,
75 default_attr_name,
76 get_func_def,
77 get_mypyc_attrs,
78 is_dataclass,
79 is_extension_class,
80 is_trait,
81 )
82 from mypyc.options import CompilerOptions
83 from mypyc.sametype import is_same_type
84
85 GENERATOR_HELPER_NAME: Final = "__mypyc_generator_helper__"
86
87
88 def build_type_map(
89 mapper: Mapper,
90 modules: list[MypyFile],
91 graph: Graph,
92 types: dict[Expression, Type],
93 options: CompilerOptions,
94 errors: Errors,
95 ) -> None:
96 # Collect all classes defined in everything we are compiling
97 classes = []
98 for module in modules:
99 module_classes = [node for node in module.defs if isinstance(node, ClassDef)]
100 classes.extend([(module, cdef) for cdef in module_classes])
101
102 # Collect all class mappings so that we can bind arbitrary class name
103 # references even if there are import cycles.
104 for module, cdef in classes:
105 class_ir = ClassIR(
106 cdef.name,
107 module.fullname,
108 is_trait(cdef),
109 is_abstract=cdef.info.is_abstract,
110 is_final_class=cdef.info.is_final,
111 )
112 class_ir.is_ext_class = is_extension_class(module.path, cdef, errors)
113 if class_ir.is_ext_class:
114 class_ir.deletable = cdef.info.deletable_attributes.copy()
115 # If global optimizations are disabled, turn of tracking of class children
116 if not options.global_opts:
117 class_ir.children = None
118 mapper.type_to_ir[cdef.info] = class_ir
119 mapper.symbol_fullnames.add(class_ir.fullname)
120 class_ir.is_enum = cdef.info.is_enum and len(cdef.info.enum_members) > 0
121
122 # Populate structural information in class IR for extension classes.
123 for module, cdef in classes:
124 with catch_errors(module.path, cdef.line):
125 if mapper.type_to_ir[cdef.info].is_ext_class:
126 prepare_class_def(module.path, module.fullname, cdef, errors, mapper, options)
127 else:
128 prepare_non_ext_class_def(
129 module.path, module.fullname, cdef, errors, mapper, options
130 )
131
132 # Validate cross-class properties after all ClassIR flags are populated.
133 for module, cdef in classes:
134 with catch_errors(module.path, cdef.line):
135 if mapper.type_to_ir[cdef.info].is_ext_class:
136 validate_acyclic_class_bases(module.path, cdef, errors, mapper)
137
138 # Prepare implicit attribute accessors as needed if an attribute overrides a property.
139 for module, cdef in classes:
140 class_ir = mapper.type_to_ir[cdef.info]
141 if class_ir.is_ext_class:
142 prepare_implicit_property_accessors(cdef.info, class_ir, module.fullname, mapper)
143
144 # Register __mypyc_defaults_setup FuncDecls on classes that have their own
145 # class-level default attribute assignments. Done here, before any IR build
146 # runs, so that the cross-class lookup in generate_attr_defaults_init is
147 # order-independent: IR build within a compilation group proceeds in
148 # filename order, so a subclass may be IR-built before its base.
149 for module, cdef in classes:
150 class_ir = mapper.type_to_ir[cdef.info]
151 if class_ir.is_ext_class and _has_own_default_attrs(cdef, class_ir):
152 _register_defaults_setup_decl(class_ir, module.fullname)
153
154 # Validate __deletable__ declarations. Done here so the compiler exits
155 # early on invalid input before any IR is built.
156 for module, cdef in classes:
157 class_ir = mapper.type_to_ir[cdef.info]
158 if class_ir.is_ext_class:
159 with catch_errors(module.path, cdef.line):
160 _check_deletable_declarations(module.path, cdef, class_ir, errors)
161
162 # Collect all the functions also. We collect from the symbol table
163 # so that we can easily pick out the right copy of a function that
164 # is conditionally defined. This doesn't include nested functions!
165 for module in modules:
166 for func in get_module_func_defs(module):
167 prepare_func_def(module.fullname, None, func, mapper, options)
168 # TODO: what else?
169
170 # Check for incompatible attribute definitions that were not
171 # flagged by mypy but can't be supported when compiling.
172 for module, cdef in classes:
173 class_ir = mapper.type_to_ir[cdef.info]
174 for attr in class_ir.attributes:
175 for base_ir in class_ir.mro[1:]:
176 if attr in base_ir.attributes:
177 if not is_same_type(class_ir.attributes[attr], base_ir.attributes[attr]):
178 node = cdef.info.names[attr].node
179 assert node is not None
180 kind = "trait" if base_ir.is_trait else "class"
181 errors.error(
182 f'Type of "{attr}" is incompatible with '
183 f'definition in {kind} "{base_ir.name}"',
184 module.path,
185 node.line,
186 )
187
188
189 def is_from_module(node: SymbolNode, module: MypyFile) -> bool:
190 return node.fullname == module.fullname + "." + node.name
191
192
193 def load_type_map(mapper: Mapper, modules: list[MypyFile], deser_ctx: DeserMaps) -> None:
194 """Populate a Mapper with deserialized IR from a list of modules."""
195 for module in modules:
196 for node in module.names.values():
197 if (
198 isinstance(node.node, TypeInfo)
199 and is_from_module(node.node, module)
200 and not node.node.is_newtype
201 and not node.node.is_named_tuple
202 and node.node.typeddict_type is None
203 ):
204 # Some TypeInfo entries are mypy-synthetic (e.g. anonymous
205 # intersection classes like "<subclass of X and Y>") and have
206 # no corresponding mypyc ClassIR. Skip those rather than
207 # aborting the whole cache load.
208 ir = deser_ctx.classes.get(node.node.fullname)
209 if ir is None:
210 continue
211 mapper.type_to_ir[node.node] = ir
212 mapper.symbol_fullnames.add(node.node.fullname)
213 # Trait/builtin-base classes have an ir.ctor FuncDecl
214 # but no emitted CPyDef_<ctor>, so a cross-group direct
215 # call would hit an undefined symbol. Mirror the skip
216 # in prepare_init_method.
217 if not ir.is_trait and not ir.builtin_base:
218 mapper.func_to_decl[node.node] = ir.ctor
219
220 for module in modules:
221 for func in get_module_func_defs(module):
222 func_id = get_id_from_name(func.name, func.fullname, func.line)
223 mapper.func_to_decl[func] = deser_ctx.functions[func_id].decl
224
225
226 def get_module_func_defs(module: MypyFile) -> Iterable[FuncDef]:
227 """Collect all of the (non-method) functions declared in a module."""
228 for node in module.names.values():
229 # We need to filter out functions that are imported or
230 # aliases. The best way to do this seems to be by
231 # checking that the fullname matches.
232 if isinstance(node.node, (FuncDef, Decorator, OverloadedFuncDef)) and is_from_module(
233 node.node, module
234 ):
235 yield get_func_def(node.node)
236
237
238 def prepare_func_def(
239 module_name: str,
240 class_name: str | None,
241 fdef: FuncDef,
242 mapper: Mapper,
243 options: CompilerOptions,
244 ) -> FuncDecl:
245 kind = (
246 FUNC_CLASSMETHOD
247 if fdef.is_class
248 else (FUNC_STATICMETHOD if fdef.is_static else FUNC_NORMAL)
249 )
250 sig = mapper.fdef_to_sig(fdef, options.strict_dunders_typing)
251 decl = FuncDecl(
252 fdef.name,
253 class_name,
254 module_name,
255 sig,
256 kind,
257 is_generator=fdef.is_generator,
258 is_coroutine=fdef.is_coroutine,
259 )
260 mapper.func_to_decl[fdef] = decl
261 return decl
262
263
264 def create_generator_class_for_func(
265 module_name: str, class_name: str | None, fdef: FuncDef, mapper: Mapper, name_suffix: str = ""
266 ) -> ClassIR:
267 """For a generator/async function, declare a generator class.
268
269 Each generator and async function gets a dedicated class that implements the
270 generator protocol with generated methods.
271 """
272 assert fdef.is_coroutine or fdef.is_generator
273 name = "_".join(x for x in [fdef.name, class_name] if x) + "_gen" + name_suffix
274 cir = ClassIR(name, module_name, is_generated=True, is_final_class=class_name is None)
275 cir.reuse_freed_instance = True
276 mapper.fdef_to_generator[fdef] = cir
277
278 helper_sig = FuncSignature(
279 (
280 RuntimeArg(SELF_NAME, object_rprimitive),
281 RuntimeArg("type", object_rprimitive),
282 RuntimeArg("value", object_rprimitive),
283 RuntimeArg("traceback", object_rprimitive),
284 RuntimeArg("arg", object_rprimitive),
285 # If non-NULL, used to store return value instead of raising StopIteration(retv)
286 RuntimeArg("stop_iter_ptr", object_pointer_rprimitive),
287 ),
288 object_rprimitive,
289 )
290
291 # The implementation of most generator functionality is behind this magic method.
292 helper_fn_decl = FuncDecl(GENERATOR_HELPER_NAME, name, module_name, helper_sig, internal=True)
293 cir.method_decls[helper_fn_decl.name] = helper_fn_decl
294 return cir
295
296
297 def prepare_method_def(
298 ir: ClassIR,
299 module_name: str,
300 cdef: ClassDef,
301 mapper: Mapper,
302 node: FuncDef | Decorator,
303 options: CompilerOptions,
304 ) -> None:
305 if isinstance(node, FuncDef):
306 ir.method_decls[node.name] = prepare_func_def(
307 module_name, cdef.name, node, mapper, options
308 )
309 elif isinstance(node, Decorator):
310 # TODO: do something about abstract methods here. Currently, they are handled just like
311 # normal methods.
312 decl = prepare_func_def(module_name, cdef.name, node.func, mapper, options)
313 if not node.decorators:
314 ir.method_decls[node.name] = decl
315 elif isinstance(node.decorators[0], MemberExpr) and node.decorators[0].name == "setter":
316 # Make property setter name different than getter name so there are no
317 # name clashes when generating C code, and property lookup at the IR level
318 # works correctly.
319 decl.name = PROPSET_PREFIX + decl.name
320 decl.is_prop_setter = True
321 # Making the argument implicitly positional-only avoids unnecessary glue methods
322 decl.sig.args[1].pos_only = True
323 ir.method_decls[PROPSET_PREFIX + node.name] = decl
324
325 if node.func.is_property:
326 assert node.func.type, f"Expected return type annotation for property '{node.name}'"
327 decl.is_prop_getter = True
328 ir.property_types[node.name] = decl.sig.ret_type
329
330
331 def prepare_fast_path(
332 ir: ClassIR,
333 module_name: str,
334 cdef: ClassDef,
335 mapper: Mapper,
336 node: SymbolNode | None,
337 options: CompilerOptions,
338 ) -> None:
339 """Add fast (direct) variants of methods in non-extension classes."""
340 if ir.is_enum:
341 # We check that non-empty enums are implicitly final in mypy, so we
342 # can generate direct calls to enum methods.
343 if isinstance(node, OverloadedFuncDef):
344 if node.is_property:
345 return
346 node = node.impl
347 if not isinstance(node, FuncDef):
348 # TODO: support decorated methods (at least @classmethod and @staticmethod).
349 return
350 # The simplest case is a regular or overloaded method without decorators. In this
351 # case we can generate practically identical IR method body, but with a signature
352 # suitable for direct calls (usual non-extension class methods are converted to
353 # callable classes, and thus have an extra __mypyc_self__ argument).
354 name = FAST_PREFIX + node.name
355 sig = mapper.fdef_to_sig(node, options.strict_dunders_typing)
356 decl = FuncDecl(name, cdef.name, module_name, sig, FUNC_NORMAL)
357 ir.method_decls[name] = decl
358 return
359
360
361 def is_valid_multipart_property_def(prop: OverloadedFuncDef) -> bool:
362 # Checks to ensure supported property decorator semantics
363 if len(prop.items) != 2:
364 return False
365
366 getter = prop.items[0]
367 setter = prop.items[1]
368
369 return (
370 isinstance(getter, Decorator)
371 and isinstance(setter, Decorator)
372 and getter.func.is_property
373 and len(setter.decorators) == 1
374 and isinstance(setter.decorators[0], MemberExpr)
375 and setter.decorators[0].name == "setter"
376 )
377
378
379 def can_subclass_builtin(builtin_base: str) -> bool:
380 # BaseException and dict are special cased.
381 return builtin_base in (
382 (
383 "builtins.Exception",
384 "builtins.LookupError",
385 "builtins.IndexError",
386 "builtins.Warning",
387 "builtins.UserWarning",
388 "builtins.ValueError",
389 "builtins.object",
390 )
391 )
392
393
394 def get_removed_base_fullname(expr: Expression) -> str | None:
395 if isinstance(expr, IndexExpr):
396 expr = expr.base
397 if isinstance(expr, RefExpr):
398 return expr.fullname
399 return None
400
401
402 def find_non_acyclic_base(cdef: ClassDef, mapper: Mapper) -> str | None:
403 if cdef.type_args:
404 return "typing.Generic"
405
406 for expr in cdef.removed_base_type_exprs:
407 if fullname := get_removed_base_fullname(expr):
408 return fullname
409 return "a removed base class"
410
411 for base in cdef.info.mro[1:]:
412 if base.fullname == "builtins.object":
413 continue
414
415 base_ir = mapper.type_to_ir.get(base)
416 if base_ir is not None and base_ir.is_acyclic:
417 continue
418
419 return base.fullname
420
421 return None
422
423
424 def validate_acyclic_class_bases(
425 path: str, cdef: ClassDef, errors: Errors, mapper: Mapper
426 ) -> None:
427 ir = mapper.type_to_ir[cdef.info]
428 if not ir.is_acyclic:
429 return
430
431 if fullname := find_non_acyclic_base(cdef, mapper):
432 errors.error(
433 f'"acyclic" can\'t be used in a class that inherits from non-acyclic type "{fullname}"',
434 path,
435 cdef.line,
436 )
437
438
439 def _has_own_default_attrs(cdef: ClassDef, ir: ClassIR) -> bool:
440 """Whether this class's own body has any default attribute assignment
441 that would be emitted into __mypyc_defaults_setup.
442
443 Used during prepare to decide whether to register a
444 __mypyc_defaults_setup FuncDecl ahead of IR build.
445 """
446 if ir.builtin_base or ir.is_trait:
447 return False
448 cls_type = dataclass_type(cdef)
449 return any(
450 default_attr_name(stmt, ir, cls_type) is not None
451 for stmt in cdef.info.defn.defs.body
452 if isinstance(stmt, AssignmentStmt)
453 )
454
455
456 def _register_defaults_setup_decl(ir: ClassIR, module_name: str) -> None:
457 sig = FuncSignature([RuntimeArg(SELF_NAME, RInstance(ir))], bool_rprimitive)
458 ir.method_decls[MYPYC_DEFAULTS_SETUP] = FuncDecl(
459 MYPYC_DEFAULTS_SETUP, ir.name, module_name, sig
460 )
461
462
463 def _check_deletable_declarations(path: str, cdef: ClassDef, ir: ClassIR, errors: Errors) -> None:
464 """Validate that attributes listed in __deletable__ refer to definable
465 attributes on the class.
466
467 Runs in the prepare phase so we exit early on invalid programs before
468 any IR is built.
469 """
470 if not ir.deletable:
471 return
472 line = next(
473 (
474 stmt.line
475 for stmt in cdef.info.defn.defs.body
476 if isinstance(stmt, AssignmentStmt)
477 and isinstance(stmt.lvalues[0], NameExpr)
478 and stmt.lvalues[0].name == "__deletable__"
479 ),
480 cdef.line,
481 )
482 for attr in ir.deletable:
483 if attr not in ir.attributes:
484 if not ir.has_attr(attr):
485 errors.error(f'Attribute "{attr}" not defined', path, line)
486 continue
487 for base in ir.mro:
488 if attr in base.property_types:
489 errors.error(f'Cannot make property "{attr}" deletable', path, line)
490 break
491 else:
492 _, base = ir.attr_details(attr)
493 errors.error(
494 f'Attribute "{attr}" not defined in "{ir.name}" '
495 f'(defined in "{base.name}")',
496 path,
497 line,
498 )
499
500
501 def prepare_class_def(
502 path: str,
503 module_name: str,
504 cdef: ClassDef,
505 errors: Errors,
506 mapper: Mapper,
507 options: CompilerOptions,
508 ) -> None:
509 """Populate the interface-level information in a class IR.
510
511 This includes attribute and method declarations, and the MRO, among other things, but
512 method bodies are generated in a later pass.
513 """
514
515 ir = mapper.type_to_ir[cdef.info]
516 info = cdef.info
517
518 attrs, attrs_lines = get_mypyc_attrs(cdef, path, errors)
519 if attrs.get("allow_interpreted_subclasses") is True:
520 ir.allow_interpreted_subclasses = True
521 if attrs.get("serializable") is True:
522 # Supports copy.copy and pickle (including subclasses)
523 ir._serializable = True
524
525 if attrs.get("acyclic") is True:
526 ir.is_acyclic = True
527
528 # Check for subclassing from builtin types
529 for cls in info.mro:
530 # Special case exceptions and dicts
531 # XXX: How do we handle *other* things??
532 if cls.fullname == "builtins.BaseException":
533 ir.builtin_base = "PyBaseExceptionObject"
534 elif cls.fullname == "builtins.dict":
535 ir.builtin_base = "PyDictObject"
536 elif cls.fullname.startswith("builtins."):
537 if not can_subclass_builtin(cls.fullname):
538 # Note that if we try to subclass a C extension class that
539 # isn't in builtins, bad things will happen and we won't
540 # catch it here! But this should catch a lot of the most
541 # common pitfalls.
542 errors.error(
543 "Inheriting from most builtin types is unimplemented", path, cdef.line
544 )
545 errors.note(
546 "Potential workaround: @mypy_extensions.mypyc_attr(native_class=False)",
547 path,
548 cdef.line,
549 )
550 errors.note(
551 "https://mypyc.readthedocs.io/en/stable/native_classes.html#defining-non-native-classes",
552 path,
553 cdef.line,
554 )
555
556 free_list_len = attrs.get("free_list_len")
557 if free_list_len is not None:
558 line = attrs_lines["free_list_len"]
559 if ir.is_trait:
560 errors.error('"free_list_len" can\'t be used with traits', path, line)
561 if ir.allow_interpreted_subclasses:
562 errors.error(
563 '"free_list_len" can\'t be used in a class that allows interpreted subclasses',
564 path,
565 line,
566 )
567 if ir.builtin_base:
568 errors.error(
569 '"free_list_len" can\'t be used in a class that inherits from a built-in type',
570 path,
571 line,
572 )
573 if free_list_len == 1:
574 ir.reuse_freed_instance = True
575 else:
576 errors.error(f'Unsupported value for "free_list_len": {free_list_len}', path, line)
577
578 # Set up the parent class
579 bases = [mapper.type_to_ir[base.type] for base in info.bases if base.type in mapper.type_to_ir]
580 if len(bases) > 1 and any(not c.is_trait for c in bases) and bases[0].is_trait:
581 # If the first base is a non-trait, don't ever error here. While it is correct
582 # to error if a trait comes before the next non-trait base (e.g. non-trait, trait,
583 # non-trait), it's pointless, confusing noise from the bigger issue: multiple
584 # inheritance is *not* supported.
585 errors.error("Non-trait base must appear first in parent list", path, cdef.line)
586 ir.traits = [c for c in bases if c.is_trait]
587
588 mro = [] # All mypyc base classes
589 base_mro = [] # Non-trait mypyc base classes
590 for cls in info.mro:
591 if cls not in mapper.type_to_ir:
592 if cls.fullname != "builtins.object":
593 ir.inherits_python = True
594 continue
595 base_ir = mapper.type_to_ir[cls]
596 if not base_ir.is_trait:
597 base_mro.append(base_ir)
598 mro.append(base_ir)
599
600 if cls.defn.removed_base_type_exprs or not base_ir.is_ext_class:
601 ir.inherits_python = True
602
603 base_idx = 1 if not ir.is_trait else 0
604 if len(base_mro) > base_idx:
605 ir.base = base_mro[base_idx]
606 ir.mro = mro
607 ir.base_mro = base_mro
608
609 prepare_methods_and_attributes(cdef, ir, path, module_name, errors, mapper, options)
610 prepare_init_method(cdef, ir, module_name, mapper)
611
612 for base in bases:
613 if base.children is not None:
614 base.children.append(ir)
615
616 if is_dataclass(cdef):
617 ir.is_augmented = True
618
619
620 def prepare_methods_and_attributes(
621 cdef: ClassDef,
622 ir: ClassIR,
623 path: str,
624 module_name: str,
625 errors: Errors,
626 mapper: Mapper,
627 options: CompilerOptions,
628 ) -> None:
629 """Populate attribute and method declarations."""
630 info = cdef.info
631 for name, node in info.names.items():
632 # Currently all plugin generated methods are dummies and not included.
633 if node.plugin_generated:
634 continue
635
636 if isinstance(node.node, Var):
637 assert node.node.type, "Class member %s missing type" % name
638 if not node.node.is_classvar and name not in ("__slots__", "__deletable__"):
639 attr_rtype = mapper.type_to_rtype(node.node.type)
640 if ir.is_trait and attr_rtype.error_overlap:
641 # Traits don't have attribute definedness bitmaps, so use
642 # property accessor methods to access attributes that need them.
643 # We will generate accessor implementations that use the class bitmap
644 # for any concrete subclasses.
645 add_getter_declaration(ir, name, attr_rtype, module_name)
646 add_setter_declaration(ir, name, attr_rtype, module_name)
647 ir.attributes[name] = attr_rtype
648 elif isinstance(node.node, (FuncDef, Decorator)):
649 prepare_method_def(ir, module_name, cdef, mapper, node.node, options)
650 elif isinstance(node.node, OverloadedFuncDef):
651 # Handle case for property with both a getter and a setter
652 if node.node.is_property:
653 if is_valid_multipart_property_def(node.node):
654 for item in node.node.items:
655 prepare_method_def(ir, module_name, cdef, mapper, item, options)
656 else:
657 errors.error("Unsupported property decorator semantics", path, cdef.line)
658
659 # Handle case for regular function overload
660 else:
661 if not node.node.impl:
662 errors.error(
663 "Overloads without implementation are not supported", path, cdef.line
664 )
665 else:
666 prepare_method_def(ir, module_name, cdef, mapper, node.node.impl, options)
667
668 if ir.builtin_base:
669 ir.attributes.clear()
670
671
672 def prepare_implicit_property_accessors(
673 info: TypeInfo, ir: ClassIR, module_name: str, mapper: Mapper
674 ) -> None:
675 concrete_attributes = set()
676 for base in ir.base_mro:
677 for name, attr_rtype in base.attributes.items():
678 concrete_attributes.add(name)
679 add_property_methods_for_attribute_if_needed(
680 info, ir, name, attr_rtype, module_name, mapper
681 )
682 for base in ir.mro[1:]:
683 if base.is_trait:
684 for name, attr_rtype in base.attributes.items():
685 if name not in concrete_attributes:
686 add_property_methods_for_attribute_if_needed(
687 info, ir, name, attr_rtype, module_name, mapper
688 )
689
690
691 def add_property_methods_for_attribute_if_needed(
692 info: TypeInfo,
693 ir: ClassIR,
694 attr_name: str,
695 attr_rtype: RType,
696 module_name: str,
697 mapper: Mapper,
698 ) -> None:
699 """Add getter and/or setter for attribute if defined as property in a base class.
700
701 Only add declarations. The body IR will be synthesized later during irbuild.
702 """
703 for base in info.mro[1:]:
704 if base in mapper.type_to_ir:
705 base_ir = mapper.type_to_ir[base]
706 n = base.names.get(attr_name)
707 if n is None:
708 continue
709 node = n.node
710 if isinstance(node, Decorator) and node.name not in ir.method_decls:
711 # Defined as a read-only property in base class/trait
712 add_getter_declaration(ir, attr_name, attr_rtype, module_name)
713 elif isinstance(node, OverloadedFuncDef) and is_valid_multipart_property_def(node):
714 # Defined as a read-write property in base class/trait
715 add_getter_declaration(ir, attr_name, attr_rtype, module_name)
716 add_setter_declaration(ir, attr_name, attr_rtype, module_name)
717 elif base_ir.is_trait and attr_rtype.error_overlap:
718 add_getter_declaration(ir, attr_name, attr_rtype, module_name)
719 add_setter_declaration(ir, attr_name, attr_rtype, module_name)
720
721
722 def add_getter_declaration(
723 ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str
724 ) -> None:
725 self_arg = RuntimeArg("self", RInstance(ir), pos_only=True)
726 sig = FuncSignature([self_arg], attr_rtype)
727 decl = FuncDecl(attr_name, ir.name, module_name, sig, FUNC_NORMAL)
728 decl.is_prop_getter = True
729 decl.implicit = True # Triggers synthesization
730 ir.method_decls[attr_name] = decl
731 ir.property_types[attr_name] = attr_rtype # TODO: Needed??
732
733
734 def add_setter_declaration(
735 ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str
736 ) -> None:
737 self_arg = RuntimeArg("self", RInstance(ir), pos_only=True)
738 value_arg = RuntimeArg("value", attr_rtype, pos_only=True)
739 sig = FuncSignature([self_arg, value_arg], none_rprimitive)
740 setter_name = PROPSET_PREFIX + attr_name
741 decl = FuncDecl(setter_name, ir.name, module_name, sig, FUNC_NORMAL)
742 decl.is_prop_setter = True
743 decl.implicit = True # Triggers synthesization
744 ir.method_decls[setter_name] = decl
745
746
747 def check_matching_args(init_sig: FuncSignature, new_sig: FuncSignature) -> bool:
748 num_init_args = len(init_sig.args) - init_sig.num_bitmap_args
749 num_new_args = len(new_sig.args) - new_sig.num_bitmap_args
750 if num_init_args != num_new_args:
751 return False
752
753 for idx in range(1, num_init_args):
754 init_arg = init_sig.args[idx]
755 new_arg = new_sig.args[idx]
756 if init_arg.type != new_arg.type:
757 return False
758
759 if init_arg.kind != new_arg.kind:
760 return False
761
762 return True
763
764
765 def prepare_init_method(cdef: ClassDef, ir: ClassIR, module_name: str, mapper: Mapper) -> None:
766 # Set up a constructor decl
767 init_node = cdef.info["__init__"].node
768
769 new_node: SymbolNode | None = None
770 new_symbol = cdef.info.get("__new__")
771 # We are only interested in __new__ method defined in a user-defined class,
772 # so we ignore it if it comes from a builtin type. It's usually builtins.object
773 # but could also be builtins.type for metaclasses so we detect the prefix which
774 # matches both.
775 if new_symbol and new_symbol.fullname and not new_symbol.fullname.startswith("builtins."):
776 new_node = new_symbol.node
777 if isinstance(new_node, (Decorator, OverloadedFuncDef)):
778 new_node = get_func_def(new_node)
779 if not ir.is_trait and not ir.builtin_base and isinstance(init_node, FuncDef):
780 init_sig = mapper.fdef_to_sig(init_node, True)
781 args_match = True
782 if isinstance(new_node, FuncDef):
783 new_sig = mapper.fdef_to_sig(new_node, True)
784 args_match = check_matching_args(init_sig, new_sig)
785
786 defining_ir = mapper.type_to_ir.get(init_node.info)
787 # If there is a nontrivial __init__ that wasn't defined in an
788 # extension class, we need to make the constructor take *args,
789 # **kwargs so it can call tp_init.
790 if (
791 (
792 defining_ir is None
793 or not defining_ir.is_ext_class
794 or cdef.info["__init__"].plugin_generated
795 )
796 and init_node.info.fullname != "builtins.object"
797 ) or not args_match:
798 init_sig = FuncSignature(
799 [
800 init_sig.args[0],
801 RuntimeArg("args", tuple_rprimitive, ARG_STAR),
802 RuntimeArg("kwargs", dict_rprimitive, ARG_STAR2),
803 ],
804 init_sig.ret_type,
805 )
806
807 last_arg = len(init_sig.args) - init_sig.num_bitmap_args
808 ctor_sig = FuncSignature(init_sig.args[1:last_arg], RInstance(ir))
809 ir.ctor = FuncDecl(cdef.name, None, module_name, ctor_sig)
810 mapper.func_to_decl[cdef.info] = ir.ctor
811
812
813 def prepare_non_ext_class_def(
814 path: str,
815 module_name: str,
816 cdef: ClassDef,
817 errors: Errors,
818 mapper: Mapper,
819 options: CompilerOptions,
820 ) -> None:
821 ir = mapper.type_to_ir[cdef.info]
822 info = cdef.info
823
824 for node in info.names.values():
825 if isinstance(node.node, (FuncDef, Decorator)):
826 prepare_method_def(ir, module_name, cdef, mapper, node.node, options)
827 elif isinstance(node.node, OverloadedFuncDef):
828 # Handle case for property with both a getter and a setter
829 if node.node.is_property:
830 if not is_valid_multipart_property_def(node.node):
831 errors.error("Unsupported property decorator semantics", path, cdef.line)
832 for item in node.node.items:
833 prepare_method_def(ir, module_name, cdef, mapper, item, options)
834 # Handle case for regular function overload
835 else:
836 prepare_method_def(ir, module_name, cdef, mapper, get_func_def(node.node), options)
837
838 prepare_fast_path(ir, module_name, cdef, mapper, node.node, options)
839
840 if any(cls in mapper.type_to_ir and mapper.type_to_ir[cls].is_ext_class for cls in info.mro):
841 errors.error(
842 "Non-extension classes may not inherit from extension classes", path, cdef.line
843 )
844
845
846 RegisterImplInfo = tuple[TypeInfo, FuncDef]
847
848
849 class SingledispatchInfo(NamedTuple):
850 singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]]
851 decorators_to_remove: dict[FuncDef, list[int]]
852
853
854 def find_singledispatch_register_impls(
855 modules: list[MypyFile], errors: Errors
856 ) -> SingledispatchInfo:
857 visitor = SingledispatchVisitor(errors)
858 for module in modules:
859 visitor.current_path = module.path
860 module.accept(visitor)
861 return SingledispatchInfo(visitor.singledispatch_impls, visitor.decorators_to_remove)
862
863
864 class SingledispatchVisitor(TraverserVisitor):
865 current_path: str
866
867 def __init__(self, errors: Errors) -> None:
868 super().__init__()
869
870 # Map of main singledispatch function to list of registered implementations
871 self.singledispatch_impls: defaultdict[FuncDef, list[RegisterImplInfo]] = defaultdict(list)
872
873 # Map of decorated function to the indices of any decorators to remove
874 self.decorators_to_remove: dict[FuncDef, list[int]] = {}
875
876 self.errors: Errors = errors
877 self.func_stack_depth = 0
878
879 def visit_func_def(self, o: FuncDef) -> None:
880 self.func_stack_depth += 1
881 super().visit_func_def(o)
882 self.func_stack_depth -= 1
883
884 def visit_decorator(self, dec: Decorator) -> None:
885 if dec.decorators:
886 decorators_to_store = dec.decorators.copy()
887 decorators_to_remove: list[int] = []
888 # the index of the last non-register decorator before finding a register decorator
889 # when going through decorators from top to bottom
890 last_non_register: int | None = None
891 for i, d in enumerate(decorators_to_store):
892 impl = get_singledispatch_register_call_info(d, dec.func)
893 if impl is not None:
894 if self.func_stack_depth > 0:
895 self.errors.error(
896 "Registering nested functions not supported", self.current_path, d.line
897 )
898 self.singledispatch_impls[impl.singledispatch_func].append(
899 (impl.dispatch_type, dec.func)
900 )
901 decorators_to_remove.append(i)
902 if last_non_register is not None:
903 # found a register decorator after a non-register decorator, which we
904 # don't support because we'd have to make a copy of the function before
905 # calling the decorator so that we can call it later, which complicates
906 # the implementation for something that is probably not commonly used
907 self.errors.error(
908 "Calling decorator after registering function not supported",
909 self.current_path,
910 decorators_to_store[last_non_register].line,
911 )
912 else:
913 if refers_to_fullname(d, "functools.singledispatch"):
914 if self.func_stack_depth > 0:
915 self.errors.error(
916 "Nested singledispatch functions not supported",
917 self.current_path,
918 d.line,
919 )
920 decorators_to_remove.append(i)
921 # make sure that we still treat the function as a singledispatch function
922 # even if we don't find any registered implementations (which might happen
923 # if all registered implementations are registered dynamically)
924 self.singledispatch_impls.setdefault(dec.func, [])
925 last_non_register = i
926
927 if decorators_to_remove:
928 # calling register on a function that tries to dispatch based on type annotations
929 # raises a TypeError because compiled functions don't have an __annotations__
930 # attribute
931 self.decorators_to_remove[dec.func] = decorators_to_remove
932
933 super().visit_decorator(dec)
934
935
936 class RegisteredImpl(NamedTuple):
937 singledispatch_func: FuncDef
938 dispatch_type: TypeInfo
939
940
941 def get_singledispatch_register_call_info(
942 decorator: Expression, func: FuncDef
943 ) -> RegisteredImpl | None:
944 # @fun.register(complex)
945 # def g(arg): ...
946 if (
947 isinstance(decorator, CallExpr)
948 and len(decorator.args) == 1
949 and isinstance(decorator.args[0], RefExpr)
950 ):
951 callee = decorator.callee
952 dispatch_type = decorator.args[0].node
953 if not isinstance(dispatch_type, TypeInfo):
954 return None
955
956 if isinstance(callee, MemberExpr):
957 return registered_impl_from_possible_register_call(callee, dispatch_type)
958 # @fun.register
959 # def g(arg: int): ...
960 elif isinstance(decorator, MemberExpr):
961 # we don't know if this is a register call yet, so we can't be sure that the function
962 # actually has arguments
963 if not func.arguments:
964 return None
965 arg_type = get_proper_type(func.arguments[0].variable.type)
966 if not isinstance(arg_type, Instance):
967 return None
968 info = arg_type.type
969 return registered_impl_from_possible_register_call(decorator, info)
970 return None
971
972
973 def registered_impl_from_possible_register_call(
974 expr: MemberExpr, dispatch_type: TypeInfo
975 ) -> RegisteredImpl | None:
976 if expr.name == "register" and isinstance(expr.expr, NameExpr):
977 node = expr.expr.node
978 if isinstance(node, Decorator):
979 return RegisteredImpl(node.func, dispatch_type)
980 return None
981
982
983 def adjust_generator_classes_of_methods(mapper: Mapper) -> None:
984 """Make optimizations and adjustments to generated generator classes of methods.
985
986 This is a separate pass after type map has been built, since we need all classes
987 to be processed to analyze class hierarchies.
988 """
989
990 generator_methods = []
991
992 for fdef, fn_ir in mapper.func_to_decl.items():
993 if isinstance(fdef, FuncDef) and (fdef.is_coroutine or fdef.is_generator):
994 gen_ir = create_generator_class_for_func(
995 fn_ir.module_name, fn_ir.class_name, fdef, mapper
996 )
997 # TODO: We could probably support decorators sometimes (static and class method?)
998 if not fdef.is_decorated:
999 name = fn_ir.name
1000 precise_ret_type = True
1001 if fn_ir.class_name is not None:
1002 class_ir = mapper.type_to_ir[fdef.info]
1003 subcls = class_ir.subclasses()
1004 if subcls is None:
1005 # Override could be of a different type, so we can't make assumptions.
1006 precise_ret_type = False
1007 elif class_ir.is_trait:
1008 # Give up on traits. We could possibly have an abstract base class
1009 # for generator return types to make this use precise types.
1010 precise_ret_type = False
1011 else:
1012 for s in subcls:
1013 if name in s.method_decls:
1014 m = s.method_decls[name]
1015 if (
1016 m.is_generator != fn_ir.is_generator
1017 or m.is_coroutine != fn_ir.is_coroutine
1018 ):
1019 # Override is of a different kind, and the optimization
1020 # to use a precise generator return type doesn't work.
1021 precise_ret_type = False
1022 else:
1023 class_ir = None
1024
1025 if precise_ret_type:
1026 # Give a more precise type for generators, so that we can optimize
1027 # code that uses them. They return a generator object, which has a
1028 # specific class. Without this, the type would have to be 'object'.
1029 fn_ir.sig.ret_type = RInstance(gen_ir)
1030 if fn_ir.bound_sig:
1031 fn_ir.bound_sig.ret_type = RInstance(gen_ir)
1032 if class_ir is not None:
1033 if class_ir.is_method_final(name):
1034 gen_ir.is_final_class = True
1035 generator_methods.append((name, class_ir, gen_ir))
1036
1037 new_bases = {}
1038
1039 for name, class_ir, gen in generator_methods:
1040 # For generator methods, we need to have subclass generator classes inherit from
1041 # baseclass generator classes when there are overrides to maintain LSP.
1042 base = class_ir.real_base()
1043 if base is not None:
1044 if base.has_method(name):
1045 base_sig = base.method_sig(name)
1046 if isinstance(base_sig.ret_type, RInstance):
1047 base_gen = base_sig.ret_type.class_ir
1048 new_bases[gen] = base_gen
1049
1050 # Add generator inheritance relationships by adjusting MROs.
1051 for deriv, base in new_bases.items():
1052 if base.children is not None:
1053 base.children.append(deriv)
1054 while True:
1055 deriv.mro.append(base)
1056 deriv.base_mro.append(base)
1057 if base not in new_bases:
1058 break
1059 base = new_bases[base]