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 if node.node.is_final:
649 ir.final_attributes.add(name)
650 elif isinstance(node.node, (FuncDef, Decorator)):
651 prepare_method_def(ir, module_name, cdef, mapper, node.node, options)
652 elif isinstance(node.node, OverloadedFuncDef):
653 # Handle case for property with both a getter and a setter
654 if node.node.is_property:
655 if is_valid_multipart_property_def(node.node):
656 for item in node.node.items:
657 prepare_method_def(ir, module_name, cdef, mapper, item, options)
658 else:
659 errors.error("Unsupported property decorator semantics", path, cdef.line)
660
661 # Handle case for regular function overload
662 else:
663 if not node.node.impl:
664 errors.error(
665 "Overloads without implementation are not supported", path, cdef.line
666 )
667 else:
668 prepare_method_def(ir, module_name, cdef, mapper, node.node.impl, options)
669
670 if ir.builtin_base:
671 ir.attributes.clear()
672
673
674 def prepare_implicit_property_accessors(
675 info: TypeInfo, ir: ClassIR, module_name: str, mapper: Mapper
676 ) -> None:
677 concrete_attributes = set()
678 for base in ir.base_mro:
679 for name, attr_rtype in base.attributes.items():
680 concrete_attributes.add(name)
681 add_property_methods_for_attribute_if_needed(
682 info, ir, name, attr_rtype, module_name, mapper
683 )
684 for base in ir.mro[1:]:
685 if base.is_trait:
686 for name, attr_rtype in base.attributes.items():
687 if name not in concrete_attributes:
688 add_property_methods_for_attribute_if_needed(
689 info, ir, name, attr_rtype, module_name, mapper
690 )
691
692
693 def add_property_methods_for_attribute_if_needed(
694 info: TypeInfo,
695 ir: ClassIR,
696 attr_name: str,
697 attr_rtype: RType,
698 module_name: str,
699 mapper: Mapper,
700 ) -> None:
701 """Add getter and/or setter for attribute if defined as property in a base class.
702
703 Only add declarations. The body IR will be synthesized later during irbuild.
704 """
705 for base in info.mro[1:]:
706 if base in mapper.type_to_ir:
707 base_ir = mapper.type_to_ir[base]
708 n = base.names.get(attr_name)
709 if n is None:
710 continue
711 node = n.node
712 if isinstance(node, Decorator) and node.name not in ir.method_decls:
713 # Defined as a read-only property in base class/trait
714 add_getter_declaration(ir, attr_name, attr_rtype, module_name)
715 elif isinstance(node, OverloadedFuncDef) and is_valid_multipart_property_def(node):
716 # Defined as a read-write property in base class/trait
717 add_getter_declaration(ir, attr_name, attr_rtype, module_name)
718 add_setter_declaration(ir, attr_name, attr_rtype, module_name)
719 elif base_ir.is_trait and attr_rtype.error_overlap:
720 add_getter_declaration(ir, attr_name, attr_rtype, module_name)
721 add_setter_declaration(ir, attr_name, attr_rtype, module_name)
722
723
724 def add_getter_declaration(
725 ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str
726 ) -> None:
727 self_arg = RuntimeArg("self", RInstance(ir), pos_only=True)
728 sig = FuncSignature([self_arg], attr_rtype)
729 decl = FuncDecl(attr_name, ir.name, module_name, sig, FUNC_NORMAL)
730 decl.is_prop_getter = True
731 decl.implicit = True # Triggers synthesization
732 ir.method_decls[attr_name] = decl
733 ir.property_types[attr_name] = attr_rtype # TODO: Needed??
734
735
736 def add_setter_declaration(
737 ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str
738 ) -> None:
739 self_arg = RuntimeArg("self", RInstance(ir), pos_only=True)
740 value_arg = RuntimeArg("value", attr_rtype, pos_only=True)
741 sig = FuncSignature([self_arg, value_arg], none_rprimitive)
742 setter_name = PROPSET_PREFIX + attr_name
743 decl = FuncDecl(setter_name, ir.name, module_name, sig, FUNC_NORMAL)
744 decl.is_prop_setter = True
745 decl.implicit = True # Triggers synthesization
746 ir.method_decls[setter_name] = decl
747
748
749 def check_matching_args(init_sig: FuncSignature, new_sig: FuncSignature) -> bool:
750 num_init_args = len(init_sig.args) - init_sig.num_bitmap_args
751 num_new_args = len(new_sig.args) - new_sig.num_bitmap_args
752 if num_init_args != num_new_args:
753 return False
754
755 for idx in range(1, num_init_args):
756 init_arg = init_sig.args[idx]
757 new_arg = new_sig.args[idx]
758 if init_arg.type != new_arg.type:
759 return False
760
761 if init_arg.kind != new_arg.kind:
762 return False
763
764 return True
765
766
767 def prepare_init_method(cdef: ClassDef, ir: ClassIR, module_name: str, mapper: Mapper) -> None:
768 # Set up a constructor decl
769 init_node = cdef.info["__init__"].node
770
771 new_node: SymbolNode | None = None
772 new_symbol = cdef.info.get("__new__")
773 # We are only interested in __new__ method defined in a user-defined class,
774 # so we ignore it if it comes from a builtin type. It's usually builtins.object
775 # but could also be builtins.type for metaclasses so we detect the prefix which
776 # matches both.
777 if new_symbol and new_symbol.fullname and not new_symbol.fullname.startswith("builtins."):
778 new_node = new_symbol.node
779 if isinstance(new_node, (Decorator, OverloadedFuncDef)):
780 new_node = get_func_def(new_node)
781 if not ir.is_trait and not ir.builtin_base and isinstance(init_node, FuncDef):
782 init_sig = mapper.fdef_to_sig(init_node, True)
783 args_match = True
784 if isinstance(new_node, FuncDef):
785 new_sig = mapper.fdef_to_sig(new_node, True)
786 args_match = check_matching_args(init_sig, new_sig)
787
788 defining_ir = mapper.type_to_ir.get(init_node.info)
789 # If there is a nontrivial __init__ that wasn't defined in an
790 # extension class, we need to make the constructor take *args,
791 # **kwargs so it can call tp_init.
792 if (
793 (
794 defining_ir is None
795 or not defining_ir.is_ext_class
796 or cdef.info["__init__"].plugin_generated
797 )
798 and init_node.info.fullname != "builtins.object"
799 ) or not args_match:
800 init_sig = FuncSignature(
801 [
802 init_sig.args[0],
803 RuntimeArg("args", tuple_rprimitive, ARG_STAR),
804 RuntimeArg("kwargs", dict_rprimitive, ARG_STAR2),
805 ],
806 init_sig.ret_type,
807 )
808
809 last_arg = len(init_sig.args) - init_sig.num_bitmap_args
810 ctor_sig = FuncSignature(init_sig.args[1:last_arg], RInstance(ir))
811 ir.ctor = FuncDecl(cdef.name, None, module_name, ctor_sig)
812 mapper.func_to_decl[cdef.info] = ir.ctor
813
814
815 def prepare_non_ext_class_def(
816 path: str,
817 module_name: str,
818 cdef: ClassDef,
819 errors: Errors,
820 mapper: Mapper,
821 options: CompilerOptions,
822 ) -> None:
823 ir = mapper.type_to_ir[cdef.info]
824 info = cdef.info
825
826 for node in info.names.values():
827 if isinstance(node.node, (FuncDef, Decorator)):
828 prepare_method_def(ir, module_name, cdef, mapper, node.node, options)
829 elif isinstance(node.node, OverloadedFuncDef):
830 # Handle case for property with both a getter and a setter
831 if node.node.is_property:
832 if not is_valid_multipart_property_def(node.node):
833 errors.error("Unsupported property decorator semantics", path, cdef.line)
834 for item in node.node.items:
835 prepare_method_def(ir, module_name, cdef, mapper, item, options)
836 # Handle case for regular function overload
837 else:
838 prepare_method_def(ir, module_name, cdef, mapper, get_func_def(node.node), options)
839
840 prepare_fast_path(ir, module_name, cdef, mapper, node.node, options)
841
842 if any(cls in mapper.type_to_ir and mapper.type_to_ir[cls].is_ext_class for cls in info.mro):
843 errors.error(
844 "Non-extension classes may not inherit from extension classes", path, cdef.line
845 )
846
847
848 RegisterImplInfo = tuple[TypeInfo, FuncDef]
849
850
851 class SingledispatchInfo(NamedTuple):
852 singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]]
853 decorators_to_remove: dict[FuncDef, list[int]]
854
855
856 def find_singledispatch_register_impls(
857 modules: list[MypyFile], errors: Errors
858 ) -> SingledispatchInfo:
859 visitor = SingledispatchVisitor(errors)
860 for module in modules:
861 visitor.current_path = module.path
862 module.accept(visitor)
863 return SingledispatchInfo(visitor.singledispatch_impls, visitor.decorators_to_remove)
864
865
866 class SingledispatchVisitor(TraverserVisitor):
867 current_path: str
868
869 def __init__(self, errors: Errors) -> None:
870 super().__init__()
871
872 # Map of main singledispatch function to list of registered implementations
873 self.singledispatch_impls: defaultdict[FuncDef, list[RegisterImplInfo]] = defaultdict(list)
874
875 # Map of decorated function to the indices of any decorators to remove
876 self.decorators_to_remove: dict[FuncDef, list[int]] = {}
877
878 self.errors: Errors = errors
879 self.func_stack_depth = 0
880
881 def visit_func_def(self, o: FuncDef) -> None:
882 self.func_stack_depth += 1
883 super().visit_func_def(o)
884 self.func_stack_depth -= 1
885
886 def visit_decorator(self, dec: Decorator) -> None:
887 if dec.decorators:
888 decorators_to_store = dec.decorators.copy()
889 decorators_to_remove: list[int] = []
890 # the index of the last non-register decorator before finding a register decorator
891 # when going through decorators from top to bottom
892 last_non_register: int | None = None
893 for i, d in enumerate(decorators_to_store):
894 impl = get_singledispatch_register_call_info(d, dec.func)
895 if impl is not None:
896 if self.func_stack_depth > 0:
897 self.errors.error(
898 "Registering nested functions not supported", self.current_path, d.line
899 )
900 self.singledispatch_impls[impl.singledispatch_func].append(
901 (impl.dispatch_type, dec.func)
902 )
903 decorators_to_remove.append(i)
904 if last_non_register is not None:
905 # found a register decorator after a non-register decorator, which we
906 # don't support because we'd have to make a copy of the function before
907 # calling the decorator so that we can call it later, which complicates
908 # the implementation for something that is probably not commonly used
909 self.errors.error(
910 "Calling decorator after registering function not supported",
911 self.current_path,
912 decorators_to_store[last_non_register].line,
913 )
914 else:
915 if refers_to_fullname(d, "functools.singledispatch"):
916 if self.func_stack_depth > 0:
917 self.errors.error(
918 "Nested singledispatch functions not supported",
919 self.current_path,
920 d.line,
921 )
922 decorators_to_remove.append(i)
923 # make sure that we still treat the function as a singledispatch function
924 # even if we don't find any registered implementations (which might happen
925 # if all registered implementations are registered dynamically)
926 self.singledispatch_impls.setdefault(dec.func, [])
927 last_non_register = i
928
929 if decorators_to_remove:
930 # calling register on a function that tries to dispatch based on type annotations
931 # raises a TypeError because compiled functions don't have an __annotations__
932 # attribute
933 self.decorators_to_remove[dec.func] = decorators_to_remove
934
935 super().visit_decorator(dec)
936
937
938 class RegisteredImpl(NamedTuple):
939 singledispatch_func: FuncDef
940 dispatch_type: TypeInfo
941
942
943 def get_singledispatch_register_call_info(
944 decorator: Expression, func: FuncDef
945 ) -> RegisteredImpl | None:
946 # @fun.register(complex)
947 # def g(arg): ...
948 if (
949 isinstance(decorator, CallExpr)
950 and len(decorator.args) == 1
951 and isinstance(decorator.args[0], RefExpr)
952 ):
953 callee = decorator.callee
954 dispatch_type = decorator.args[0].node
955 if not isinstance(dispatch_type, TypeInfo):
956 return None
957
958 if isinstance(callee, MemberExpr):
959 return registered_impl_from_possible_register_call(callee, dispatch_type)
960 # @fun.register
961 # def g(arg: int): ...
962 elif isinstance(decorator, MemberExpr):
963 # we don't know if this is a register call yet, so we can't be sure that the function
964 # actually has arguments
965 if not func.arguments:
966 return None
967 arg_type = get_proper_type(func.arguments[0].variable.type)
968 if not isinstance(arg_type, Instance):
969 return None
970 info = arg_type.type
971 return registered_impl_from_possible_register_call(decorator, info)
972 return None
973
974
975 def registered_impl_from_possible_register_call(
976 expr: MemberExpr, dispatch_type: TypeInfo
977 ) -> RegisteredImpl | None:
978 if expr.name == "register" and isinstance(expr.expr, NameExpr):
979 node = expr.expr.node
980 if isinstance(node, Decorator):
981 return RegisteredImpl(node.func, dispatch_type)
982 return None
983
984
985 def adjust_generator_classes_of_methods(mapper: Mapper) -> None:
986 """Make optimizations and adjustments to generated generator classes of methods.
987
988 This is a separate pass after type map has been built, since we need all classes
989 to be processed to analyze class hierarchies.
990 """
991
992 generator_methods = []
993
994 for fdef, fn_ir in mapper.func_to_decl.items():
995 if isinstance(fdef, FuncDef) and (fdef.is_coroutine or fdef.is_generator):
996 gen_ir = create_generator_class_for_func(
997 fn_ir.module_name, fn_ir.class_name, fdef, mapper
998 )
999 # TODO: We could probably support decorators sometimes (static and class method?)
1000 if not fdef.is_decorated:
1001 name = fn_ir.name
1002 precise_ret_type = True
1003 if fn_ir.class_name is not None:
1004 class_ir = mapper.type_to_ir[fdef.info]
1005 subcls = class_ir.subclasses()
1006 if subcls is None:
1007 # Override could be of a different type, so we can't make assumptions.
1008 precise_ret_type = False
1009 elif class_ir.is_trait:
1010 # Give up on traits. We could possibly have an abstract base class
1011 # for generator return types to make this use precise types.
1012 precise_ret_type = False
1013 else:
1014 for s in subcls:
1015 if name in s.method_decls:
1016 m = s.method_decls[name]
1017 if (
1018 m.is_generator != fn_ir.is_generator
1019 or m.is_coroutine != fn_ir.is_coroutine
1020 ):
1021 # Override is of a different kind, and the optimization
1022 # to use a precise generator return type doesn't work.
1023 precise_ret_type = False
1024 else:
1025 class_ir = None
1026
1027 if precise_ret_type:
1028 # Give a more precise type for generators, so that we can optimize
1029 # code that uses them. They return a generator object, which has a
1030 # specific class. Without this, the type would have to be 'object'.
1031 fn_ir.sig.ret_type = RInstance(gen_ir)
1032 if fn_ir.bound_sig:
1033 fn_ir.bound_sig.ret_type = RInstance(gen_ir)
1034 if class_ir is not None:
1035 if class_ir.is_method_final(name):
1036 gen_ir.is_final_class = True
1037 generator_methods.append((name, class_ir, gen_ir))
1038
1039 new_bases = {}
1040
1041 for name, class_ir, gen in generator_methods:
1042 # For generator methods, we need to have subclass generator classes inherit from
1043 # baseclass generator classes when there are overrides to maintain LSP.
1044 base = class_ir.real_base()
1045 if base is not None:
1046 if base.has_method(name):
1047 base_sig = base.method_sig(name)
1048 if isinstance(base_sig.ret_type, RInstance):
1049 base_gen = base_sig.ret_type.class_ir
1050 new_bases[gen] = base_gen
1051
1052 # Add generator inheritance relationships by adjusting MROs.
1053 for deriv, base in new_bases.items():
1054 if base.children is not None:
1055 base.children.append(deriv)
1056 while True:
1057 deriv.mro.append(base)
1058 deriv.base_mro.append(base)
1059 if base not in new_bases:
1060 break
1061 base = new_bases[base]