Debian Codegraph @

mypyc/irbuild/classdef.py

raw
1 """Transform class definitions from the mypy AST form to IR."""
2
3 from __future__ import annotations
4
5 from abc import abstractmethod
6 from collections.abc import Callable
7 from typing import Final
8
9 from mypy.nodes import (
10 ARG_POS,
11 EXCLUDED_ENUM_ATTRIBUTES,
12 TYPE_VAR_TUPLE_KIND,
13 AssignmentStmt,
14 CallExpr,
15 ClassDef,
16 Decorator,
17 EllipsisExpr,
18 ExpressionStmt,
19 FuncDef,
20 Lvalue,
21 MemberExpr,
22 NameExpr,
23 OverloadedFuncDef,
24 PassStmt,
25 StrExpr,
26 TempNode,
27 TypeInfo,
28 TypeParam,
29 Var,
30 is_class_var,
31 )
32 from mypy.types import Instance, UnboundType, get_proper_type
33 from mypyc.common import MYPYC_DEFAULTS_SETUP, PROPSET_PREFIX
34 from mypyc.ir.class_ir import ClassIR, NonExtClassInfo
35 from mypyc.ir.func_ir import FuncDecl, FuncSignature
36 from mypyc.ir.ops import (
37 NAMESPACE_TYPE,
38 BasicBlock,
39 Branch,
40 Call,
41 InitStatic,
42 LoadAddress,
43 LoadErrorValue,
44 LoadStatic,
45 MethodCall,
46 Register,
47 Return,
48 SetAttr,
49 TupleSet,
50 Value,
51 )
52 from mypyc.ir.rtypes import RType, bool_rprimitive, dict_rprimitive, object_rprimitive
53 from mypyc.irbuild.builder import IRBuilder, create_type_params
54 from mypyc.irbuild.function import (
55 gen_property_getter_ir,
56 gen_property_setter_ir,
57 handle_ext_method,
58 handle_non_ext_method,
59 load_type,
60 )
61 from mypyc.irbuild.prepare import GENERATOR_HELPER_NAME
62 from mypyc.irbuild.util import (
63 dataclass_type,
64 default_attr_name,
65 get_func_def,
66 is_constant,
67 is_dataclass_decorator,
68 )
69 from mypyc.primitives.dict_ops import dict_new_op, exact_dict_set_item_op
70 from mypyc.primitives.generic_ops import (
71 iter_op,
72 next_op,
73 py_get_item_op,
74 py_hasattr_op,
75 py_setattr_op,
76 )
77 from mypyc.primitives.misc_ops import (
78 dataclass_sleight_of_hand,
79 import_op,
80 not_implemented_op,
81 py_calc_meta_op,
82 py_init_subclass_op,
83 pytype_from_template_op,
84 type_object_op,
85 )
86 from mypyc.subtype import is_subtype
87
88
89 def transform_class_def(builder: IRBuilder, cdef: ClassDef) -> None:
90 """Create IR for a class definition.
91
92 This can generate both extension (native) and non-extension
93 classes. These are generated in very different ways. In the
94 latter case we construct a Python type object at runtime by doing
95 the equivalent of "type(name, bases, dict)" in IR. Extension
96 classes are defined via C structs that are generated later in
97 mypyc.codegen.emitclass.
98
99 This is the main entry point to this module.
100 """
101 if cdef.info not in builder.mapper.type_to_ir:
102 builder.error("Nested class definitions not supported", cdef.line)
103 return
104
105 ir = builder.mapper.type_to_ir[cdef.info]
106
107 # We do this check here because the base field of parent
108 # classes aren't necessarily populated yet at
109 # prepare_class_def time.
110 if any(ir.base_mro[i].base != ir.base_mro[i + 1] for i in range(len(ir.base_mro) - 1)):
111 builder.error("Multiple inheritance is not supported (except for traits)", cdef.line)
112
113 if ir.allow_interpreted_subclasses:
114 for parent in ir.mro:
115 if not parent.allow_interpreted_subclasses:
116 builder.error(
117 'Base class "{}" does not allow interpreted subclasses'.format(
118 parent.fullname
119 ),
120 cdef.line,
121 )
122
123 # Currently, we only create non-extension classes for classes that are
124 # decorated or inherit from Enum. Classes decorated with @trait do not
125 # apply here, and are handled in a different way.
126 if ir.is_ext_class:
127 cls_type = dataclass_type(cdef)
128 if cls_type is None:
129 cls_builder: ClassBuilder = ExtClassBuilder(builder, cdef)
130 elif cls_type in ["dataclasses", "attr-auto"]:
131 cls_builder = DataClassBuilder(builder, cdef)
132 elif cls_type == "attr":
133 cls_builder = AttrsClassBuilder(builder, cdef)
134 else:
135 raise ValueError(cls_type)
136 else:
137 cls_builder = NonExtClassBuilder(builder, cdef)
138
139 # Set up class body context so that intra-class ClassVar references
140 # (e.g. C = A | B where A is defined earlier in the same class) can be
141 # resolved from the class being built instead of module globals.
142 builder.class_body_classvars = {}
143 builder.class_body_obj = cls_builder.class_body_obj()
144 builder.class_body_ir = ir
145
146 for stmt in cdef.defs.body:
147 if (
148 isinstance(stmt, (FuncDef, Decorator, OverloadedFuncDef))
149 and stmt.name == GENERATOR_HELPER_NAME
150 ):
151 builder.error(
152 f'Method name "{stmt.name}" is reserved for mypyc internal use', stmt.line
153 )
154
155 if isinstance(stmt, OverloadedFuncDef) and stmt.is_property:
156 if isinstance(cls_builder, NonExtClassBuilder):
157 # properties with both getters and setters in non_extension
158 # classes not supported
159 builder.error("Property setters not supported in non-extension classes", stmt.line)
160 for item in stmt.items:
161 with builder.catch_errors(stmt.line):
162 cls_builder.add_method(get_func_def(item))
163 elif isinstance(stmt, (FuncDef, Decorator, OverloadedFuncDef)):
164 # Ignore plugin generated methods (since they have no
165 # bodies to compile and will need to have the bodies
166 # provided by some other mechanism.)
167 if cdef.info.names[stmt.name].plugin_generated:
168 continue
169 with builder.catch_errors(stmt.line):
170 cls_builder.add_method(get_func_def(stmt))
171 elif isinstance(stmt, PassStmt) or (
172 isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)
173 ):
174 continue
175 elif isinstance(stmt, AssignmentStmt):
176 if len(stmt.lvalues) != 1:
177 builder.error("Multiple assignment in class bodies not supported", stmt.line)
178 continue
179 lvalue = stmt.lvalues[0]
180 if not isinstance(lvalue, NameExpr):
181 builder.error(
182 "Only assignment to variables is supported in class bodies", stmt.line
183 )
184 continue
185 # We want to collect class variables in a dictionary for both real
186 # non-extension classes and fake dataclass ones.
187 cls_builder.add_attr(lvalue, stmt)
188 # Track this ClassVar so subsequent class body statements can reference it.
189 if is_class_var(lvalue) or stmt.is_final_def:
190 assert isinstance(lvalue.node, Var), lvalue.node
191 builder.class_body_classvars[lvalue.node] = None
192
193 elif isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr):
194 # Docstring. Ignore
195 pass
196 else:
197 builder.error("Unsupported statement in class body", stmt.line)
198
199 # Clear class body context (nested classes are rejected above, so no need to save/restore).
200 builder.class_body_classvars = {}
201 builder.class_body_obj = None
202 builder.class_body_ir = None
203
204 # Generate implicit property setters/getters
205 for name, decl in ir.method_decls.items():
206 if decl.implicit and decl.is_prop_getter:
207 getter_ir = gen_property_getter_ir(builder, decl, cdef, ir.is_trait)
208 builder.functions.append(getter_ir)
209 ir.methods[getter_ir.decl.name] = getter_ir
210
211 setter_ir = None
212 setter_name = PROPSET_PREFIX + name
213 if setter_name in ir.method_decls:
214 setter_ir = gen_property_setter_ir(
215 builder, ir.method_decls[setter_name], cdef, ir.is_trait
216 )
217 builder.functions.append(setter_ir)
218 ir.methods[setter_name] = setter_ir
219
220 ir.properties[name] = (getter_ir, setter_ir)
221 # TODO: Generate glue method if needed?
222 # TODO: Do we need interpreted glue methods? Maybe not?
223
224 cls_builder.finalize(ir)
225
226
227 class ClassBuilder:
228 """Create IR for a class definition.
229
230 This is an abstract base class.
231 """
232
233 def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:
234 self.builder = builder
235 self.cdef = cdef
236 self.attrs_to_cache: list[tuple[Lvalue, RType]] = []
237
238 @abstractmethod
239 def add_method(self, fdef: FuncDef) -> None:
240 """Add a method to the class IR"""
241
242 @abstractmethod
243 def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:
244 """Add an attribute to the class IR"""
245
246 @abstractmethod
247 def finalize(self, ir: ClassIR) -> None:
248 """Perform any final operations to complete the class IR"""
249
250 def class_body_obj(self) -> Value | None:
251 """Return the object to use for loading class attributes during class body init.
252
253 For extension classes, this is the type object. For non-extension classes,
254 this is the class dict. Returns None if not applicable.
255 """
256 return None
257
258
259 class NonExtClassBuilder(ClassBuilder):
260 def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:
261 super().__init__(builder, cdef)
262 self.non_ext = self.create_non_ext_info()
263
264 def class_body_obj(self) -> Value | None:
265 return self.non_ext.dict
266
267 def create_non_ext_info(self) -> NonExtClassInfo:
268 non_ext_bases = populate_non_ext_bases(self.builder, self.cdef)
269 non_ext_metaclass = find_non_ext_metaclass(self.builder, self.cdef, non_ext_bases)
270 non_ext_dict = setup_non_ext_dict(
271 self.builder, self.cdef, non_ext_metaclass, non_ext_bases
272 )
273 # We populate __annotations__ for non-extension classes
274 # because dataclasses uses it to determine which attributes to compute on.
275 # TODO: Maybe generate more precise types for annotations
276 non_ext_anns = self.builder.call_c(dict_new_op, [], self.cdef.line)
277 return NonExtClassInfo(non_ext_dict, non_ext_bases, non_ext_anns, non_ext_metaclass)
278
279 def add_method(self, fdef: FuncDef) -> None:
280 handle_non_ext_method(self.builder, self.non_ext, self.cdef, fdef)
281
282 def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:
283 add_non_ext_class_attr_ann(self.builder, self.non_ext, lvalue, stmt)
284 add_non_ext_class_attr(
285 self.builder, self.non_ext, lvalue, stmt, self.cdef, self.attrs_to_cache
286 )
287
288 def finalize(self, ir: ClassIR) -> None:
289 # Dynamically create the class via the type constructor
290 non_ext_class = load_non_ext_class(self.builder, ir, self.non_ext, self.cdef.line)
291 non_ext_class = load_decorated_class(self.builder, self.cdef, non_ext_class)
292
293 # Try to avoid contention when using free threading.
294 self.builder.set_immortal_if_free_threaded(non_ext_class, self.cdef.line)
295
296 # Save the decorated class
297 self.builder.add(
298 InitStatic(non_ext_class, self.cdef.name, self.builder.module_name, NAMESPACE_TYPE)
299 )
300
301 # Add the non-extension class to the dict
302 self.builder.call_c(
303 exact_dict_set_item_op,
304 [
305 self.builder.load_globals_dict(),
306 self.builder.load_str(self.cdef.name),
307 non_ext_class,
308 ],
309 self.cdef.line,
310 )
311
312 # Cache any cacheable class attributes
313 cache_class_attrs(self.builder, self.attrs_to_cache, self.cdef)
314
315
316 class ExtClassBuilder(ClassBuilder):
317 def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:
318 super().__init__(builder, cdef)
319 # If the class is not decorated, generate an extension class for it.
320 self.type_obj: Value = allocate_class(builder, cdef)
321
322 def class_body_obj(self) -> Value | None:
323 return self.type_obj
324
325 def add_method(self, fdef: FuncDef) -> None:
326 handle_ext_method(self.builder, self.cdef, fdef)
327
328 def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:
329 # Variable declaration with no body
330 if isinstance(stmt.rvalue, TempNode):
331 return
332 # Only treat marked class variables as class variables.
333 if not (is_class_var(lvalue) or stmt.is_final_def):
334 return
335 typ = self.builder.load_native_type_object(self.cdef.fullname)
336 value = self.builder.accept(stmt.rvalue)
337 self.builder.primitive_op(
338 py_setattr_op, [typ, self.builder.load_str(lvalue.name), value], stmt.line
339 )
340 if self.builder.non_function_scope() and stmt.is_final_def:
341 self.builder.init_final_static(lvalue, value, self.cdef.name)
342
343 def finalize(self, ir: ClassIR) -> None:
344 # Call __init_subclass__ after class attributes have been set
345 self.builder.call_c(py_init_subclass_op, [self.type_obj], self.cdef.line)
346
347 # Under separate compilation, prepare.py pre-registers the decl iff
348 # the class has its own default attribute assignments to emit, so we
349 # can skip the body walk entirely when it isn't present. Without
350 # separate compilation, find_attr_initializers walks the MRO so that
351 # inherited defaults are reflected in ir.attrs_with_defaults (relied
352 # on by the attribute-definedness analysis), so we always run it.
353 if not self.builder.options.separate or MYPYC_DEFAULTS_SETUP in ir.method_decls:
354 attrs_with_defaults, default_assignments = find_attr_initializers(
355 self.builder, self.cdef
356 )
357 ir.attrs_with_defaults.update(attrs_with_defaults)
358 generate_attr_defaults_init(self.builder, self.cdef, default_assignments)
359 create_ne_from_eq(self.builder, self.cdef)
360
361
362 class DataClassBuilder(ExtClassBuilder):
363 # controls whether an __annotations__ attribute should be added to the class
364 # __dict__. This is not desirable for attrs classes where auto_attribs is
365 # disabled, as attrs will reject it.
366 add_annotations_to_dict = True
367
368 def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:
369 super().__init__(builder, cdef)
370 self.non_ext = self.create_non_ext_info()
371
372 def create_non_ext_info(self) -> NonExtClassInfo:
373 """Set up a NonExtClassInfo to track dataclass attributes.
374
375 In addition to setting up a normal extension class for dataclasses,
376 we also collect its class attributes like a non-extension class so
377 that we can hand them to the dataclass decorator.
378 """
379 return NonExtClassInfo(
380 self.builder.call_c(dict_new_op, [], self.cdef.line),
381 self.builder.add(TupleSet([], self.cdef.line)),
382 self.builder.call_c(dict_new_op, [], self.cdef.line),
383 self.builder.add(LoadAddress(type_object_op.type, type_object_op.src, self.cdef.line)),
384 )
385
386 def get_type_annotation(self, stmt: AssignmentStmt) -> TypeInfo | None:
387 # We populate __annotations__ because dataclasses uses it to determine
388 # which attributes to compute on.
389 ann_type = get_proper_type(stmt.type)
390 if isinstance(ann_type, Instance):
391 return ann_type.type
392 return None
393
394 def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:
395 add_non_ext_class_attr_ann(
396 self.builder, self.non_ext, lvalue, stmt, self.get_type_annotation
397 )
398 add_non_ext_class_attr(
399 self.builder, self.non_ext, lvalue, stmt, self.cdef, self.attrs_to_cache
400 )
401 super().add_attr(lvalue, stmt)
402
403 def finalize(self, ir: ClassIR) -> None:
404 """Generate code to finish instantiating a dataclass.
405
406 This works by replacing all of the attributes on the class
407 (which will be descriptors) with whatever they would be in a
408 non-extension class, calling dataclass, then switching them back.
409
410 The resulting class is an extension class and instances of it do not
411 have a __dict__ (unless something else requires it).
412 All methods written explicitly in the source are compiled and
413 may be called through the vtable while the methods generated
414 by dataclasses are interpreted and may not be.
415
416 (If we just called dataclass without doing this, it would think that all
417 of the descriptors for our attributes are default values and generate an
418 incorrect constructor. We need to do the switch so that dataclass gets the
419 appropriate defaults.)
420 """
421 super().finalize(ir)
422 assert self.type_obj
423 add_dunders_to_non_ext_dict(
424 self.builder, self.non_ext, self.cdef.line, self.add_annotations_to_dict
425 )
426 dec = self.builder.accept(
427 next(d for d in self.cdef.decorators if is_dataclass_decorator(d))
428 )
429 dataclass_type_val = self.builder.load_str(dataclass_type(self.cdef) or "unknown")
430 self.builder.call_c(
431 dataclass_sleight_of_hand,
432 [dec, self.type_obj, self.non_ext.dict, self.non_ext.anns, dataclass_type_val],
433 self.cdef.line,
434 )
435
436
437 class AttrsClassBuilder(DataClassBuilder):
438 """Create IR for an attrs class where auto_attribs=False (the default).
439
440 When auto_attribs is enabled, attrs classes behave similarly to dataclasses
441 (i.e. types are stored as annotations on the class) and are thus handled
442 by DataClassBuilder, but when auto_attribs is disabled the types are
443 provided via attr.ib(type=...)
444 """
445
446 add_annotations_to_dict = False
447
448 def get_type_annotation(self, stmt: AssignmentStmt) -> TypeInfo | None:
449 if isinstance(stmt.rvalue, CallExpr):
450 # find the type arg in `attr.ib(type=str)`
451 callee = stmt.rvalue.callee
452 if (
453 isinstance(callee, MemberExpr)
454 and callee.fullname in ["attr.ib", "attr.attr"]
455 and "type" in stmt.rvalue.arg_names
456 ):
457 index = stmt.rvalue.arg_names.index("type")
458 type_name = stmt.rvalue.args[index]
459 if isinstance(type_name, NameExpr) and isinstance(type_name.node, TypeInfo):
460 lvalue = stmt.lvalues[0]
461 assert isinstance(lvalue, NameExpr), lvalue
462 return type_name.node
463 return None
464
465
466 def allocate_class(builder: IRBuilder, cdef: ClassDef) -> Value:
467 # OK AND NOW THE FUN PART
468 base_exprs = cdef.base_type_exprs + cdef.removed_base_type_exprs
469 new_style_type_args = cdef.type_args
470 if new_style_type_args:
471 bases = [make_generic_base_class(builder, cdef.fullname, new_style_type_args, cdef.line)]
472 else:
473 bases = []
474
475 if base_exprs or new_style_type_args:
476 bases.extend([builder.accept(x) for x in base_exprs])
477 tp_bases = builder.new_tuple(bases, cdef.line)
478 else:
479 tp_bases = builder.add(LoadErrorValue(object_rprimitive, is_borrowed=True))
480 modname = builder.load_str(builder.module_name)
481 template = builder.add(
482 LoadStatic(object_rprimitive, cdef.name + "_template", builder.module_name, NAMESPACE_TYPE)
483 )
484 # Create the class
485 tp = builder.call_c(pytype_from_template_op, [template, tp_bases, modname], cdef.line)
486
487 # Set type object to be immortal if free threaded, as otherwise reference count contention
488 # can cause a big performance hit.
489 builder.set_immortal_if_free_threaded(tp, cdef.line)
490
491 # Immediately fix up the trait vtables, before doing anything with the class.
492 ir = builder.mapper.type_to_ir[cdef.info]
493 if not ir.is_trait and not ir.builtin_base:
494 builder.add(
495 Call(
496 FuncDecl(
497 cdef.name + "_trait_vtable_setup",
498 None,
499 builder.module_name,
500 FuncSignature([], bool_rprimitive),
501 ),
502 [],
503 cdef.line,
504 )
505 )
506 builder.add_coroutine_setup_call(cdef.name, tp)
507
508 # Populate a '__mypyc_attrs__' field containing the list of attrs
509 builder.primitive_op(
510 py_setattr_op,
511 [
512 tp,
513 builder.load_str("__mypyc_attrs__"),
514 create_mypyc_attrs_tuple(builder, builder.mapper.type_to_ir[cdef.info], cdef.line),
515 ],
516 cdef.line,
517 )
518
519 # Save the class
520 builder.add(InitStatic(tp, cdef.name, builder.module_name, NAMESPACE_TYPE))
521
522 # Add it to the dict
523 builder.call_c(
524 exact_dict_set_item_op,
525 [builder.load_globals_dict(), builder.load_str(cdef.name), tp],
526 cdef.line,
527 )
528
529 return tp
530
531
532 def make_generic_base_class(
533 builder: IRBuilder, fullname: str, type_args: list[TypeParam], line: int
534 ) -> Value:
535 """Construct Generic[...] base class object for a new-style generic class (Python 3.12)."""
536 mod = builder.call_c(import_op, [builder.load_str("_typing")], line)
537 tvs = create_type_params(builder, mod, type_args, line)
538 args = []
539 for tv, type_param in zip(tvs, type_args):
540 if type_param.kind == TYPE_VAR_TUPLE_KIND:
541 # Evaluate *Ts for a TypeVarTuple
542 it = builder.primitive_op(iter_op, [tv], line)
543 tv = builder.call_c(next_op, [it], line)
544 args.append(tv)
545
546 gent = builder.py_get_attr(mod, "Generic", line)
547 if len(args) == 1:
548 arg = args[0]
549 else:
550 arg = builder.new_tuple(args, line)
551
552 base = builder.primitive_op(py_get_item_op, [gent, arg], line)
553 return base
554
555
556 # Mypy uses these internally as base classes of TypedDict classes. These are
557 # lies and don't have any runtime equivalent.
558 MAGIC_TYPED_DICT_CLASSES: Final[tuple[str, ...]] = (
559 "typing._TypedDict",
560 "typing_extensions._TypedDict",
561 )
562
563
564 def populate_non_ext_bases(builder: IRBuilder, cdef: ClassDef) -> Value:
565 """Create base class tuple of a non-extension class.
566
567 The tuple is passed to the metaclass constructor.
568 """
569 is_named_tuple = cdef.info.is_named_tuple
570 ir = builder.mapper.type_to_ir[cdef.info]
571 bases = []
572 for cls in (b.type for b in cdef.info.bases):
573 if cls.fullname == "builtins.object":
574 continue
575 if is_named_tuple and cls.fullname in (
576 "typing.Sequence",
577 "typing.Iterable",
578 "typing.Collection",
579 "typing.Reversible",
580 "typing.Container",
581 "typing.Sized",
582 ):
583 # HAX: Synthesized base classes added by mypy don't exist at runtime, so skip them.
584 # This could break if they were added explicitly, though...
585 continue
586 # Add the current class to the base classes list of concrete subclasses
587 if cls in builder.mapper.type_to_ir:
588 base_ir = builder.mapper.type_to_ir[cls]
589 if base_ir.children is not None:
590 base_ir.children.append(ir)
591
592 if cls.fullname in MAGIC_TYPED_DICT_CLASSES:
593 # HAX: Mypy internally represents TypedDict classes differently from what
594 # should happen at runtime. Replace with something that works.
595 module = "typing"
596 name = "_TypedDict"
597 base = builder.get_module_attr(module, name, cdef.line)
598 elif is_named_tuple and cls.fullname == "builtins.tuple":
599 name = "_NamedTuple"
600 base = builder.get_module_attr("typing", name, cdef.line)
601 else:
602 cls_module = cls.fullname.rsplit(".", 1)[0]
603 if cls_module == builder.current_module:
604 base = builder.load_global_str(cls.name, cdef.line)
605 else:
606 base = builder.load_module_attr_by_fullname(cls.fullname, cdef.line)
607 bases.append(base)
608 if cls.fullname in MAGIC_TYPED_DICT_CLASSES:
609 # The remaining base classes are synthesized by mypy and should be ignored.
610 break
611 return builder.new_tuple(bases, cdef.line)
612
613
614 def find_non_ext_metaclass(builder: IRBuilder, cdef: ClassDef, bases: Value) -> Value:
615 """Find the metaclass of a class from its defs and bases."""
616 if cdef.metaclass:
617 declared_metaclass = builder.accept(cdef.metaclass)
618 else:
619 if cdef.info.typeddict_type is not None:
620 # The metaclass for class-based TypedDict is typing._TypedDictMeta.
621 # We can't easily calculate it generically, so special case it.
622 return builder.get_module_attr("typing", "_TypedDictMeta", cdef.line)
623 elif cdef.info.is_named_tuple:
624 # The metaclass for class-based NamedTuple is typing.NamedTupleMeta.
625 # We can't easily calculate it generically, so special case it.
626 return builder.get_module_attr("typing", "NamedTupleMeta", cdef.line)
627
628 declared_metaclass = builder.add(
629 LoadAddress(type_object_op.type, type_object_op.src, cdef.line)
630 )
631
632 return builder.call_c(py_calc_meta_op, [declared_metaclass, bases], cdef.line)
633
634
635 def setup_non_ext_dict(
636 builder: IRBuilder, cdef: ClassDef, metaclass: Value, bases: Value
637 ) -> Value:
638 """Initialize the class dictionary for a non-extension class.
639
640 This class dictionary is passed to the metaclass constructor.
641 """
642 # Check if the metaclass defines a __prepare__ method, and if so, call it.
643 has_prepare = builder.primitive_op(
644 py_hasattr_op, [metaclass, builder.load_str("__prepare__")], cdef.line
645 )
646
647 non_ext_dict = Register(dict_rprimitive)
648
649 true_block, false_block, exit_block = BasicBlock(), BasicBlock(), BasicBlock()
650 builder.add_bool_branch(has_prepare, true_block, false_block)
651
652 builder.activate_block(true_block)
653 cls_name = builder.load_str(cdef.name)
654 prepare_meth = builder.py_get_attr(metaclass, "__prepare__", cdef.line)
655 prepare_dict = builder.py_call(prepare_meth, [cls_name, bases], cdef.line)
656 builder.assign(non_ext_dict, prepare_dict, cdef.line)
657 builder.goto(exit_block)
658
659 builder.activate_block(false_block)
660 builder.assign(non_ext_dict, builder.call_c(dict_new_op, [], cdef.line), cdef.line)
661 builder.goto(exit_block)
662 builder.activate_block(exit_block)
663
664 return non_ext_dict
665
666
667 def add_non_ext_class_attr_ann(
668 builder: IRBuilder,
669 non_ext: NonExtClassInfo,
670 lvalue: NameExpr,
671 stmt: AssignmentStmt,
672 get_type_info: Callable[[AssignmentStmt], TypeInfo | None] | None = None,
673 ) -> None:
674 """Add a class attribute to __annotations__ of a non-extension class."""
675 # FIXME: try to better preserve the special forms and type parameters of generics.
676 typ: Value | None = None
677 if get_type_info is not None:
678 type_info = get_type_info(stmt)
679 if type_info:
680 # NOTE: Using string type information is similar to using
681 # `from __future__ import annotations` in standard python.
682 # NOTE: For string types we need to use the fullname since it
683 # includes the module. If string type doesn't have the module,
684 # @dataclass will try to get the current module and fail since the
685 # current module is not in sys.modules.
686 if builder.current_module == type_info.module_name and stmt.line < type_info.line:
687 typ = builder.load_str(type_info.fullname)
688 else:
689 typ = load_type(builder, type_info, stmt.unanalyzed_type, stmt.line)
690
691 if typ is None:
692 # FIXME: if get_type_info is not provided, don't fall back to stmt.type?
693 ann_type = get_proper_type(stmt.type)
694 if (
695 isinstance(stmt.unanalyzed_type, UnboundType)
696 and stmt.unanalyzed_type.original_str_expr is not None
697 ):
698 # Annotation is a forward reference, so don't attempt to load the actual
699 # type and load the string instead.
700 #
701 # TODO: is it possible to determine whether a non-string annotation is
702 # actually a forward reference due to the __annotations__ future?
703 typ = builder.load_str(stmt.unanalyzed_type.original_str_expr)
704 elif isinstance(ann_type, Instance):
705 typ = load_type(builder, ann_type.type, stmt.unanalyzed_type, stmt.line)
706 else:
707 typ = builder.add(LoadAddress(type_object_op.type, type_object_op.src, stmt.line))
708
709 key = builder.load_str(lvalue.name)
710 builder.call_c(exact_dict_set_item_op, [non_ext.anns, key, typ], stmt.line)
711
712
713 def add_non_ext_class_attr(
714 builder: IRBuilder,
715 non_ext: NonExtClassInfo,
716 lvalue: NameExpr,
717 stmt: AssignmentStmt,
718 cdef: ClassDef,
719 attr_to_cache: list[tuple[Lvalue, RType]],
720 ) -> None:
721 """Add a class attribute to __dict__ of a non-extension class."""
722 # Only add the attribute to the __dict__ if the assignment is of the form:
723 # x: type = value (don't add attributes of the form 'x: type' to the __dict__).
724 if not isinstance(stmt.rvalue, TempNode):
725 rvalue = builder.accept(stmt.rvalue)
726 builder.add_to_non_ext_dict(non_ext, lvalue.name, rvalue, stmt.line)
727 # We cache enum attributes to speed up enum attribute lookup since they
728 # are final.
729 if (
730 cdef.info.bases
731 # Enum class must be the last parent class.
732 and cdef.info.bases[-1].type.is_enum
733 # Skip these since Enum will remove it
734 and lvalue.name not in EXCLUDED_ENUM_ATTRIBUTES
735 ):
736 # Enum values are always boxed, so use object_rprimitive.
737 attr_to_cache.append((lvalue, object_rprimitive))
738
739
740 def find_attr_initializers(
741 builder: IRBuilder, cdef: ClassDef
742 ) -> tuple[set[str], list[tuple[AssignmentStmt, str]]]:
743 """Find initializers of attributes in a class body.
744
745 Under separate compilation, only this class's own body is walked, and
746 generate_attr_defaults_init emits a runtime call to the parent's
747 __mypyc_defaults_setup so inherited defaults are produced by chaining,
748 not by inlining. Walking the MRO here would break under separate=True
749 with mypy's incremental cache: a base class loaded from the cache has
750 an empty ClassDef.defs.body (mypy/nodes.py::ClassDef.serialize doesn't
751 serialize the class body), so inherited assignments would be silently
752 dropped and the subclass's __mypyc_defaults_setup would leave inherited
753 slots in the "undefined" state at runtime.
754
755 Without separate compilation, all modules are parsed in the same pass
756 and the MRO walk is safe; we keep the original inline-all behavior
757 there as an optimization (no chain call needed for instance creation).
758 """
759 cls = builder.mapper.type_to_ir[cdef.info]
760 if cls.builtin_base:
761 return set(), []
762
763 cls_type = dataclass_type(cdef)
764 attrs_with_defaults: set[str] = set()
765 default_assignments: list[tuple[AssignmentStmt, str]] = []
766
767 # TODO: Support nested statements
768 if builder.options.separate:
769 infos: list[TypeInfo] = [cdef.info]
770 else:
771 infos = list(reversed(cdef.info.mro))
772
773 for info in infos:
774 info_ir = builder.mapper.type_to_ir.get(info)
775 if info_ir is None:
776 continue
777 for stmt in info.defn.defs.body:
778 if not isinstance(stmt, AssignmentStmt):
779 continue
780 name = default_attr_name(stmt, info_ir, cls_type)
781 if name is None:
782 continue
783 attrs_with_defaults.add(name)
784 default_assignments.append((stmt, info.module_name))
785
786 return attrs_with_defaults, default_assignments
787
788
789 def generate_attr_defaults_init(
790 builder: IRBuilder, cdef: ClassDef, default_assignments: list[tuple[AssignmentStmt, str]]
791 ) -> None:
792 """Generate an initialization method for default attr values (from class vars).
793
794 Under separate compilation, the emitted __mypyc_defaults_setup chains to
795 the nearest ancestor that has the method (Python __init__ style), then
796 sets only this class's own defaults; inherited defaults are produced by
797 the chain at runtime. The ancestor lookup uses cls.mro[1:] and relies on
798 prepare.py having registered the FuncDecl on every class that needs one
799 before any IR build runs. IR build within a compilation group proceeds
800 in filename order, so this class may be IR-built before its base, and a
801 method_decls lookup that depended on the base having been IR-built first
802 would miss. Without separate compilation, find_attr_initializers has
803 already collected the full MRO's defaults into default_assignments, so
804 we inline them all as before.
805 """
806 cls = builder.mapper.type_to_ir[cdef.info]
807 if cls.builtin_base:
808 return
809
810 parent_with_defaults: ClassIR | None = None
811 if builder.options.separate:
812 for ancestor in cls.mro[1:]:
813 if MYPYC_DEFAULTS_SETUP in ancestor.method_decls:
814 parent_with_defaults = ancestor
815 break
816
817 if not default_assignments and parent_with_defaults is None:
818 return
819
820 with builder.enter_method(cls, MYPYC_DEFAULTS_SETUP, bool_rprimitive):
821 self_var = builder.self()
822
823 # Chain to parent's setup so inherited defaults run first; propagate
824 # its False return so a parent default that raised still aborts
825 # instance creation rather than being silently swallowed here.
826 if parent_with_defaults is not None:
827 decl = parent_with_defaults.method_decl(MYPYC_DEFAULTS_SETUP)
828 parent_ok = builder.builder.call(decl, [self_var], [ARG_POS], [None], cdef.line)
829 fail_block, continue_block = BasicBlock(), BasicBlock()
830 builder.add(Branch(parent_ok, continue_block, fail_block, Branch.BOOL))
831 builder.activate_block(fail_block)
832 builder.add(Return(builder.false()))
833 builder.activate_block(continue_block)
834
835 for stmt, origin_module in default_assignments:
836 lvalue = stmt.lvalues[0]
837 assert isinstance(lvalue, NameExpr), lvalue
838 if not stmt.is_final_def and not is_constant(stmt.rvalue):
839 builder.warning("Unsupported default attribute value", stmt.rvalue.line)
840
841 attr_type = cls.attr_type(lvalue.name)
842 # When the default comes from a parent in a different module,
843 # set the globals lookup module so NameExpr references resolve
844 # against the correct module's globals dict.
845 builder.globals_lookup_module = (
846 origin_module if origin_module != builder.module_name else None
847 )
848 try:
849 val = builder.coerce(builder.accept(stmt.rvalue), attr_type, stmt.line)
850 finally:
851 builder.globals_lookup_module = None
852 init = SetAttr(self_var, lvalue.name, val, stmt.rvalue.line)
853 init.mark_as_initializer()
854 builder.add(init)
855
856 builder.add(Return(builder.true()))
857
858
859 def create_ne_from_eq(builder: IRBuilder, cdef: ClassDef) -> None:
860 """Create a "__ne__" method from a "__eq__" method (if only latter exists)."""
861 cls = builder.mapper.type_to_ir[cdef.info]
862 if cls.has_method("__eq__") and not cls.has_method("__ne__"):
863 gen_glue_ne_method(builder, cls, cdef.line)
864
865
866 def gen_glue_ne_method(builder: IRBuilder, cls: ClassIR, line: int) -> None:
867 """Generate a "__ne__" method from a "__eq__" method."""
868 eq_sig = cls.method_sig("__eq__")
869 strict_typing = builder.options.strict_dunders_typing
870 with builder.enter_method(cls, "__ne__", eq_sig.ret_type):
871 rhs_type = eq_sig.args[1].type
872 rhs_arg = builder.add_argument("rhs", rhs_type)
873 eqval = builder.add(MethodCall(builder.self(), "__eq__", [rhs_arg], line))
874
875 can_return_not_implemented = is_subtype(not_implemented_op.type, eq_sig.ret_type)
876 return_bool = is_subtype(eq_sig.ret_type, bool_rprimitive)
877
878 if not strict_typing or can_return_not_implemented:
879 # If __eq__ returns NotImplemented, then __ne__ should also
880 not_implemented_block, regular_block = BasicBlock(), BasicBlock()
881 not_implemented = builder.add(
882 LoadAddress(not_implemented_op.type, not_implemented_op.src, line)
883 )
884 builder.add(
885 Branch(
886 builder.translate_is_op(eqval, not_implemented, "is", line),
887 not_implemented_block,
888 regular_block,
889 Branch.BOOL,
890 )
891 )
892 builder.activate_block(regular_block)
893 rettype = bool_rprimitive if return_bool and strict_typing else object_rprimitive
894 retval = builder.coerce(
895 builder.builder.unary_not(eqval, line, likely_bool=True), rettype, line
896 )
897 builder.add(Return(retval))
898 builder.activate_block(not_implemented_block)
899 builder.add(Return(not_implemented))
900 else:
901 rettype = bool_rprimitive if return_bool and strict_typing else object_rprimitive
902 retval = builder.coerce(builder.unary_op(eqval, "not", line), rettype, line)
903 builder.add(Return(retval))
904
905
906 def load_non_ext_class(
907 builder: IRBuilder, ir: ClassIR, non_ext: NonExtClassInfo, line: int
908 ) -> Value:
909 cls_name = builder.load_str(ir.name)
910
911 add_dunders_to_non_ext_dict(builder, non_ext, line)
912
913 class_type_obj = builder.py_call(
914 non_ext.metaclass, [cls_name, non_ext.bases, non_ext.dict], line
915 )
916 return class_type_obj
917
918
919 def load_decorated_class(builder: IRBuilder, cdef: ClassDef, type_obj: Value) -> Value:
920 """Apply class decorators to create a decorated (non-extension) class object.
921
922 Given a decorated ClassDef and a register containing a
923 non-extension representation of the ClassDef created via the type
924 constructor, applies the corresponding decorator functions on that
925 decorated ClassDef and returns a register containing the decorated
926 ClassDef.
927 """
928 decorators = cdef.decorators
929 dec_class = type_obj
930 for d in reversed(decorators):
931 decorator = d.accept(builder.visitor)
932 assert isinstance(decorator, Value), decorator
933 dec_class = builder.py_call(decorator, [dec_class], dec_class.line)
934 return dec_class
935
936
937 def cache_class_attrs(
938 builder: IRBuilder, attrs_to_cache: list[tuple[Lvalue, RType]], cdef: ClassDef
939 ) -> None:
940 """Add class attributes to be cached to the global cache."""
941 typ = builder.load_native_type_object(cdef.info.fullname)
942 for lval, rtype in attrs_to_cache:
943 assert isinstance(lval, NameExpr), lval
944 rval = builder.py_get_attr(typ, lval.name, cdef.line)
945 builder.init_final_static(lval, rval, cdef.name, type_override=rtype)
946
947
948 def create_mypyc_attrs_tuple(builder: IRBuilder, ir: ClassIR, line: int) -> Value:
949 attrs = [name for ancestor in ir.mro for name in ancestor.attributes]
950 if ir.inherits_python:
951 attrs.append("__dict__")
952 items = [builder.load_str(attr) for attr in attrs]
953 return builder.new_tuple(items, line)
954
955
956 def add_dunders_to_non_ext_dict(
957 builder: IRBuilder, non_ext: NonExtClassInfo, line: int, add_annotations: bool = True
958 ) -> None:
959 if add_annotations:
960 # Add __annotations__ to the class dict.
961 builder.add_to_non_ext_dict(non_ext, "__annotations__", non_ext.anns, line)
962
963 # We add a __doc__ attribute so if the non-extension class is decorated with the
964 # dataclass decorator, dataclass will not try to look for __text_signature__.
965 # https://github.com/python/cpython/blob/3.7/Lib/dataclasses.py#L957
966 filler_doc_str = "mypyc filler docstring"
967 builder.add_to_non_ext_dict(non_ext, "__doc__", builder.load_str(filler_doc_str), line)
968 builder.add_to_non_ext_dict(non_ext, "__module__", builder.load_str(builder.module_name), line)