Debian Codegraph @

mypyc/ir/class_ir.py

raw
1 """Intermediate representation of classes."""
2
3 from __future__ import annotations
4
5 from typing import NamedTuple
6
7 from mypyc.common import PROPSET_PREFIX, JsonDict
8 from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg
9 from mypyc.ir.ops import DeserMaps, Value
10 from mypyc.ir.rtypes import RInstance, RType, c_int_rprimitive, deserialize_type, object_rprimitive
11 from mypyc.namegen import NameGenerator, exported_name
12
13 # Some notes on the vtable layout: Each concrete class has a vtable
14 # that contains function pointers for its methods. So that subclasses
15 # may be efficiently used when their parent class is expected, the
16 # layout of child vtables must be an extension of their base class's
17 # vtable.
18 #
19 # This makes multiple inheritance tricky, since obviously we cannot be
20 # an extension of multiple parent classes. We solve this by requiring
21 # all but one parent to be "traits", which we can operate on in a
22 # somewhat less efficient way. For each trait implemented by a class,
23 # we generate a separate vtable for the methods in that trait.
24 # We then store an array of (trait type, trait vtable) pointers alongside
25 # a class's main vtable. When we want to call a trait method, we
26 # (at runtime!) search the array of trait vtables to find the correct one,
27 # then call through it.
28 # Trait vtables additionally need entries for attribute getters and setters,
29 # since they can't always be in the same location.
30 #
31 # To keep down the number of indirections necessary, we store the
32 # array of trait vtables in the memory *before* the class vtable, and
33 # search it backwards. (This is a trick we can only do once---there
34 # are only two directions to store data in---but I don't think we'll
35 # need it again.)
36 # There are some tricks we could try in the future to store the trait
37 # vtables inline in the trait table (which would cut down one indirection),
38 # but this seems good enough for now.
39 #
40 # As an example:
41 # Imagine that we have a class B that inherits from a concrete class A
42 # and traits T1 and T2, and that A has methods foo() and
43 # bar() and B overrides bar() with a more specific type.
44 # Then B's vtable will look something like:
45 #
46 # T1 type object
47 # ptr to B's T1 trait vtable
48 # T2 type object
49 # ptr to B's T2 trait vtable
50 # -> | A.foo
51 # | Glue function that converts between A.bar's type and B.bar
52 # B.bar
53 # B.baz
54 #
55 # The arrow points to the "start" of the vtable (what vtable pointers
56 # point to) and the bars indicate which parts correspond to the parent
57 # class A's vtable layout.
58 #
59 # Classes that allow interpreted code to subclass them also have a
60 # "shadow vtable" that contains implementations that delegate to
61 # making a pycall, so that overridden methods in interpreted children
62 # will be called. (A better strategy could dynamically generate these
63 # vtables based on which methods are overridden in the children.)
64
65 # Descriptions of method and attribute entries in class vtables.
66 # The 'cls' field is the class that the method/attr was defined in,
67 # which might be a parent class.
68 # The 'shadow_method', if present, contains the method that should be
69 # placed in the class's shadow vtable (if it has one).
70
71
72 class VTableMethod(NamedTuple):
73 cls: "ClassIR" # noqa: UP037
74 name: str
75 method: FuncIR
76 shadow_method: FuncIR | None
77
78
79 VTableEntries = list[VTableMethod]
80
81
82 class ClassIR:
83 """Intermediate representation of a class.
84
85 This also describes the runtime structure of native instances.
86 """
87
88 def __init__(
89 self,
90 name: str,
91 module_name: str,
92 is_trait: bool = False,
93 is_generated: bool = False,
94 is_abstract: bool = False,
95 is_ext_class: bool = True,
96 is_final_class: bool = False,
97 ) -> None:
98 self.name = name
99 self.module_name = module_name
100 self.is_trait = is_trait
101 self.is_generated = is_generated
102 self.is_abstract = is_abstract
103 self.is_ext_class = is_ext_class
104 self.is_final_class = is_final_class
105 # An augmented class has additional methods separate from what mypyc generates.
106 # Right now the only one is dataclasses.
107 self.is_augmented = False
108 # Does this inherit from a Python class?
109 self.inherits_python = False
110 # Do instances of this class have __dict__?
111 self.has_dict = False
112 # Do we allow interpreted subclasses? Derived from a mypyc_attr.
113 self.allow_interpreted_subclasses = False
114 # Does this class need getseters to be generated for its attributes? (getseters are also
115 # added if is_generated is False)
116 self.needs_getseters = False
117 # Is this class declared as serializable (supports copy.copy
118 # and pickle) using @mypyc_attr(serializable=True)?
119 #
120 # Additionally, any class with this attribute False but with
121 # an __init__ that can be called without any arguments is
122 # *implicitly serializable*. In this case __init__ will be
123 # called during deserialization without arguments. If this is
124 # True, we match Python semantics and __init__ won't be called
125 # during deserialization.
126 #
127 # This impacts also all subclasses. Use is_serializable() to
128 # also consider base classes.
129 self._serializable = False
130 # If this a subclass of some built-in python class, the name
131 # of the object for that class. We currently only support this
132 # in a few ad-hoc cases.
133 self.builtin_base: str | None = None
134 # Default empty constructor
135 self.ctor = FuncDecl(name, None, module_name, FuncSignature([], RInstance(self)))
136 # Declare setup method that allocates and initializes an object. type is the
137 # type of the class being initialized, which could be another class if there
138 # is an interpreted subclass.
139 # TODO: Make it a regular method and generate its body in IR
140 self.setup = FuncDecl(
141 "__mypyc__" + name + "_setup",
142 None,
143 module_name,
144 FuncSignature([RuntimeArg("type", object_rprimitive)], RInstance(self)),
145 )
146 self.clear = FuncDecl(
147 name + "_clear",
148 None,
149 module_name,
150 FuncSignature([RuntimeArg("self", RInstance(self))], c_int_rprimitive),
151 internal=True,
152 )
153 self.clear_on_completion = FuncDecl(
154 name + "_clear_on_completion",
155 None,
156 module_name,
157 FuncSignature([RuntimeArg("self", RInstance(self))], c_int_rprimitive),
158 internal=True,
159 )
160 # Attributes defined in the class (not inherited)
161 self.attributes: dict[str, RType] = {}
162 # Attributes that must survive generator/coroutine completion because
163 # escaped nested functions may still read them as closure variables.
164 self.attrs_to_keep_alive_on_completion: set[str] = set()
165 # Final attributes defined in the class (not inherited)
166 self.final_attributes: set[str] = set()
167 # Deletable attributes
168 self.deletable: list[str] = []
169 # We populate method_types with the signatures of every method before
170 # we generate methods, and we rely on this information being present.
171 self.method_decls: dict[str, FuncDecl] = {}
172 # Map of methods that are actually present in an extension class
173 self.methods: dict[str, FuncIR] = {}
174 # Glue methods for boxing/unboxing when a class changes the type
175 # while overriding a method. Maps from (parent class overridden, method)
176 # to IR of glue method.
177 self.glue_methods: dict[tuple[ClassIR, str], FuncIR] = {}
178
179 # Properties are accessed like attributes, but have behavior like method calls.
180 # They don't belong in the methods dictionary, since we don't want to expose them to
181 # Python's method API. But we want to put them into our own vtable as methods, so that
182 # they are properly handled and overridden. The property dictionary values are a tuple
183 # containing a property getter and an optional property setter.
184 self.properties: dict[str, tuple[FuncIR, FuncIR | None]] = {}
185 # We generate these in prepare_class_def so that we have access to them when generating
186 # other methods and properties that rely on these types.
187 self.property_types: dict[str, RType] = {}
188
189 self.vtable: dict[str, int] | None = None
190 self.vtable_entries: VTableEntries = []
191 self.trait_vtables: dict[ClassIR, VTableEntries] = {}
192 # N.B: base might not actually quite be the direct base.
193 # It is the nearest concrete base, but we allow a trait in between.
194 self.base: ClassIR | None = None
195 self.traits: list[ClassIR] = []
196 # Supply a working mro for most generated classes. Real classes will need to
197 # fix it up.
198 self.mro: list[ClassIR] = [self]
199 # base_mro is the chain of concrete (non-trait) ancestors
200 self.base_mro: list[ClassIR] = [self]
201
202 # Direct subclasses of this class (use subclasses() to also include non-direct ones)
203 # None if separate compilation prevents this from working.
204 #
205 # Often it's better to use has_no_subclasses() or subclasses() instead.
206 self.children: list[ClassIR] | None = []
207
208 # Instance attributes that are initialized in the class body.
209 self.attrs_with_defaults: set[str] = set()
210
211 # Attributes that are always initialized in __init__ or class body
212 # (inferred in mypyc.analysis.attrdefined using interprocedural analysis).
213 # These can never raise AttributeError when accessed. If an attribute
214 # is *not* always initialized, we normally use the error value for
215 # an undefined value. If the attribute byte has an overlapping error value
216 # (the error_overlap attribute is true for the RType), we use a bitmap
217 # to track if the attribute is defined instead (see bitmap_attrs).
218 self._always_initialized_attrs: set[str] = set()
219
220 # Attributes that are sometimes initialized in __init__
221 self._sometimes_initialized_attrs: set[str] = set()
222
223 # If True, __init__ can make 'self' visible to unanalyzed/arbitrary code
224 self.init_self_leak = False
225
226 # Definedness of these attributes is backed by a bitmap. Index in the list
227 # indicates the bit number. Includes inherited attributes. We need the
228 # bitmap for types such as native ints (i64 etc.) that can't have a dedicated
229 # error value that doesn't overlap a valid value. The bitmap is used if the
230 # value of an attribute is the same as the error value.
231 self.bitmap_attrs: list[str] = []
232
233 # If this is a generator environment class, what is the actual method for it
234 self.env_user_function: FuncIR | None = None
235
236 # If True, keep one freed, cleared instance available for immediate reuse to
237 # speed up allocations. This helps if many objects are freed quickly, before
238 # other instances of the same class are allocated. This is effectively a
239 # per-type free "list" of up to length 1.
240 self.reuse_freed_instance = False
241
242 # If True, the class does not participate in cyclic garbage collection.
243 # This can improve performance but is only safe if instances can never
244 # be part of reference cycles. Derived from @mypyc_attr(acyclic=True).
245 self.is_acyclic = False
246
247 # Is this a class inheriting from enum.Enum? Such classes can be special-cased.
248 self.is_enum = False
249
250 # Name of the function if this a callable class representing a coroutine.
251 self.coroutine_name: str | None = None
252
253 def __repr__(self) -> str:
254 return (
255 "ClassIR("
256 "name={self.name}, module_name={self.module_name}, "
257 "is_trait={self.is_trait}, is_generated={self.is_generated}, "
258 "is_abstract={self.is_abstract}, is_ext_class={self.is_ext_class}, "
259 "is_final_class={self.is_final_class}"
260 ")".format(self=self)
261 )
262
263 @property
264 def fullname(self) -> str:
265 return f"{self.module_name}.{self.name}"
266
267 def real_base(self) -> ClassIR | None:
268 """Return the actual concrete base class, if there is one."""
269 if len(self.mro) > 1 and not self.mro[1].is_trait:
270 return self.mro[1]
271 return None
272
273 def vtable_entry(self, name: str) -> int:
274 assert self.vtable is not None, "vtable not computed yet"
275 assert name in self.vtable, f"{self.name!r} has no attribute {name!r}"
276 return self.vtable[name]
277
278 def attr_details(self, name: str) -> tuple[RType, ClassIR]:
279 for ir in self.mro:
280 if name in ir.attributes:
281 return ir.attributes[name], ir
282 if name in ir.property_types:
283 return ir.property_types[name], ir
284 raise KeyError(f"{self.name!r} has no attribute {name!r}")
285
286 def attr_type(self, name: str) -> RType:
287 return self.attr_details(name)[0]
288
289 def is_final_attr(self, name: str) -> bool:
290 """Is the (possibly inherited) attribute Final, i.e. never rebound?
291
292 A Final attribute is read-only at runtime (it has no setter) and is assigned
293 exactly once during construction, so it can never be reassigned afterwards.
294 This makes it safe to borrow on free-threaded builds (no concurrent store can
295 invalidate a borrowed reference) and lets reads skip the concurrent-writer
296 guard. Returns False for properties and for attributes this class doesn't have.
297 """
298 for ir in self.mro:
299 if name in ir.attributes:
300 return name in ir.final_attributes
301 if name in ir.property_types:
302 return False
303 return False
304
305 def method_decl(self, name: str) -> FuncDecl:
306 for ir in self.mro:
307 if name in ir.method_decls:
308 return ir.method_decls[name]
309 raise KeyError(f"{self.name!r} has no attribute {name!r}")
310
311 def method_sig(self, name: str) -> FuncSignature:
312 return self.method_decl(name).sig
313
314 def has_method(self, name: str) -> bool:
315 try:
316 self.method_decl(name)
317 except KeyError:
318 return False
319 return True
320
321 def is_method_final(self, name: str) -> bool:
322 subs = self.subclasses()
323 if subs is None:
324 return self.is_final_class
325
326 if self.has_method(name):
327 method_decl = self.method_decl(name)
328 for subc in subs:
329 if subc.method_decl(name) != method_decl:
330 return False
331 return True
332 else:
333 return not any(subc.has_method(name) for subc in subs)
334
335 def has_attr(self, name: str) -> bool:
336 try:
337 self.attr_type(name)
338 except KeyError:
339 return False
340 return True
341
342 def is_deletable(self, name: str) -> bool:
343 return any(name in ir.deletable for ir in self.mro)
344
345 def is_always_defined(self, name: str) -> bool:
346 if self.is_deletable(name):
347 return False
348 return name in self._always_initialized_attrs
349
350 def name_prefix(self, names: NameGenerator) -> str:
351 return names.private_name(self.module_name, self.name)
352
353 def struct_name(self, names: NameGenerator) -> str:
354 return f"{exported_name(self.fullname)}Object"
355
356 def get_method_and_class(
357 self, name: str, *, prefer_method: bool = False
358 ) -> tuple[FuncIR, ClassIR] | None:
359 for ir in self.mro:
360 if name in ir.methods:
361 func_ir = ir.methods[name]
362 if not prefer_method and func_ir.decl.implicit:
363 # This is an implicit accessor, so there is also an attribute definition
364 # which the caller prefers. This happens if an attribute overrides a
365 # property.
366 return None
367 return func_ir, ir
368
369 return None
370
371 def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None:
372 res = self.get_method_and_class(name, prefer_method=prefer_method)
373 return res[0] if res else None
374
375 def has_method_decl(self, name: str) -> bool:
376 return any(name in ir.method_decls for ir in self.mro)
377
378 def has_no_subclasses(self) -> bool:
379 return self.children == [] and not self.allow_interpreted_subclasses
380
381 def subclasses(self) -> set[ClassIR] | None:
382 """Return all subclasses of this class, both direct and indirect.
383
384 Return None if it is impossible to identify all subclasses, for example
385 because we are performing separate compilation.
386 """
387 if self.children is None or self.allow_interpreted_subclasses:
388 return None
389 result = set(self.children)
390 for child in self.children:
391 if child.children:
392 child_subs = child.subclasses()
393 if child_subs is None:
394 return None
395 result.update(child_subs)
396 return result
397
398 def concrete_subclasses(self) -> list[ClassIR] | None:
399 """Return all concrete (i.e. non-trait and non-abstract) subclasses.
400
401 Include both direct and indirect subclasses. Place classes with no children first.
402 """
403 subs = self.subclasses()
404 if subs is None:
405 return None
406 concrete = {c for c in subs if not (c.is_trait or c.is_abstract)}
407 # We place classes with no children first because they are more likely
408 # to appear in various isinstance() checks. We then sort leaves by name
409 # to get stable order.
410 return sorted(concrete, key=lambda c: (len(c.children or []), c.name))
411
412 def is_serializable(self) -> bool:
413 return any(ci._serializable for ci in self.mro)
414
415 def serialize(self) -> JsonDict:
416 return {
417 "name": self.name,
418 "module_name": self.module_name,
419 "is_trait": self.is_trait,
420 "is_ext_class": self.is_ext_class,
421 "is_abstract": self.is_abstract,
422 "is_generated": self.is_generated,
423 "is_augmented": self.is_augmented,
424 "is_final_class": self.is_final_class,
425 "inherits_python": self.inherits_python,
426 "has_dict": self.has_dict,
427 "allow_interpreted_subclasses": self.allow_interpreted_subclasses,
428 "needs_getseters": self.needs_getseters,
429 "_serializable": self._serializable,
430 "builtin_base": self.builtin_base,
431 "ctor": self.ctor.serialize(),
432 "clear": self.clear.serialize(),
433 "clear_on_completion": self.clear_on_completion.serialize(),
434 # We serialize dicts as lists to ensure order is preserved
435 "attributes": [(k, t.serialize()) for k, t in self.attributes.items()],
436 "attrs_to_keep_alive_on_completion": sorted(self.attrs_to_keep_alive_on_completion),
437 "final_attributes": sorted(self.final_attributes),
438 # We try to serialize a name reference, but if the decl isn't in methods
439 # then we can't be sure that will work so we serialize the whole decl.
440 "method_decls": [
441 (k, d.id if k in self.methods else d.serialize())
442 for k, d in self.method_decls.items()
443 ],
444 # We serialize method fullnames out and put methods in a separate dict
445 "methods": [(k, m.id) for k, m in self.methods.items()],
446 "glue_methods": [
447 ((cir.fullname, k), m.id) for (cir, k), m in self.glue_methods.items()
448 ],
449 # We serialize properties and property_types separately out of an
450 # abundance of caution about preserving dict ordering...
451 "property_types": [(k, t.serialize()) for k, t in self.property_types.items()],
452 "properties": list(self.properties),
453 "vtable": self.vtable,
454 "vtable_entries": serialize_vtable(self.vtable_entries),
455 "trait_vtables": [
456 (cir.fullname, serialize_vtable(v)) for cir, v in self.trait_vtables.items()
457 ],
458 # References to class IRs are all just names
459 "base": self.base.fullname if self.base else None,
460 "traits": [cir.fullname for cir in self.traits],
461 "mro": [cir.fullname for cir in self.mro],
462 "base_mro": [cir.fullname for cir in self.base_mro],
463 "children": (
464 [cir.fullname for cir in self.children] if self.children is not None else None
465 ),
466 "deletable": self.deletable,
467 "attrs_with_defaults": sorted(self.attrs_with_defaults),
468 "_always_initialized_attrs": sorted(self._always_initialized_attrs),
469 "_sometimes_initialized_attrs": sorted(self._sometimes_initialized_attrs),
470 "init_self_leak": self.init_self_leak,
471 "env_user_function": self.env_user_function.id if self.env_user_function else None,
472 "reuse_freed_instance": self.reuse_freed_instance,
473 "is_acyclic": self.is_acyclic,
474 "is_enum": self.is_enum,
475 "is_coroutine": self.coroutine_name,
476 }
477
478 @classmethod
479 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR:
480 fullname = data["module_name"] + "." + data["name"]
481 assert fullname in ctx.classes, "Class %s not in deser class map" % fullname
482 ir = ctx.classes[fullname]
483
484 ir.is_trait = data["is_trait"]
485 ir.is_generated = data["is_generated"]
486 ir.is_abstract = data["is_abstract"]
487 ir.is_ext_class = data["is_ext_class"]
488 ir.is_augmented = data["is_augmented"]
489 ir.is_final_class = data["is_final_class"]
490 ir.inherits_python = data["inherits_python"]
491 ir.has_dict = data["has_dict"]
492 ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"]
493 ir.needs_getseters = data["needs_getseters"]
494 ir._serializable = data["_serializable"]
495 ir.builtin_base = data["builtin_base"]
496 ir.ctor = FuncDecl.deserialize(data["ctor"], ctx)
497 ir.clear = FuncDecl.deserialize(data["clear"], ctx)
498 ir.clear_on_completion = FuncDecl.deserialize(data["clear_on_completion"], ctx)
499 ir.attributes = {k: deserialize_type(t, ctx) for k, t in data["attributes"]}
500 ir.attrs_to_keep_alive_on_completion = set(data["attrs_to_keep_alive_on_completion"])
501 ir.final_attributes = set(data["final_attributes"])
502 ir.method_decls = {
503 k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)
504 for k, v in data["method_decls"]
505 }
506 ir.methods = {k: ctx.functions[v] for k, v in data["methods"]}
507 ir.glue_methods = {
508 (ctx.classes[c], k): ctx.functions[v] for (c, k), v in data["glue_methods"]
509 }
510 ir.property_types = {k: deserialize_type(t, ctx) for k, t in data["property_types"]}
511 ir.properties = {
512 k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data["properties"]
513 }
514
515 ir.vtable = data["vtable"]
516 ir.vtable_entries = deserialize_vtable(data["vtable_entries"], ctx)
517 ir.trait_vtables = {
518 ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data["trait_vtables"]
519 }
520
521 base = data["base"]
522 ir.base = ctx.classes[base] if base else None
523 ir.traits = [ctx.classes[s] for s in data["traits"]]
524 ir.mro = [ctx.classes[s] for s in data["mro"]]
525 ir.base_mro = [ctx.classes[s] for s in data["base_mro"]]
526 ir.children = data["children"] and [ctx.classes[s] for s in data["children"]]
527 ir.deletable = data["deletable"]
528 ir.attrs_with_defaults = set(data["attrs_with_defaults"])
529 ir._always_initialized_attrs = set(data["_always_initialized_attrs"])
530 ir._sometimes_initialized_attrs = set(data["_sometimes_initialized_attrs"])
531 ir.init_self_leak = data["init_self_leak"]
532 ir.env_user_function = (
533 ctx.functions[data["env_user_function"]] if data["env_user_function"] else None
534 )
535 ir.reuse_freed_instance = data["reuse_freed_instance"]
536 ir.is_acyclic = data.get("is_acyclic", False)
537 ir.is_enum = data["is_enum"]
538 ir.coroutine_name = data["is_coroutine"]
539
540 return ir
541
542
543 class NonExtClassInfo:
544 """Information needed to construct a non-extension class (Python class).
545
546 Includes the class dictionary, a tuple of base classes,
547 the class annotations dictionary, and the metaclass.
548 """
549
550 def __init__(self, dict: Value, bases: Value, anns: Value, metaclass: Value) -> None:
551 self.dict = dict
552 self.bases = bases
553 self.anns = anns
554 self.metaclass = metaclass
555
556
557 def serialize_vtable_entry(entry: VTableMethod) -> JsonDict:
558 return {
559 ".class": "VTableMethod",
560 "cls": entry.cls.fullname,
561 "name": entry.name,
562 "method": entry.method.decl.id,
563 "shadow_method": entry.shadow_method.decl.id if entry.shadow_method else None,
564 }
565
566
567 def serialize_vtable(vtable: VTableEntries) -> list[JsonDict]:
568 return [serialize_vtable_entry(v) for v in vtable]
569
570
571 def deserialize_vtable_entry(data: JsonDict, ctx: DeserMaps) -> VTableMethod:
572 if data[".class"] == "VTableMethod":
573 return VTableMethod(
574 ctx.classes[data["cls"]],
575 data["name"],
576 ctx.functions[data["method"]],
577 ctx.functions[data["shadow_method"]] if data["shadow_method"] else None,
578 )
579 assert False, "Bogus vtable .class: %s" % data[".class"]
580
581
582 def deserialize_vtable(data: list[JsonDict], ctx: DeserMaps) -> VTableEntries:
583 return [deserialize_vtable_entry(x, ctx) for x in data]
584
585
586 def all_concrete_classes(class_ir: ClassIR) -> list[ClassIR] | None:
587 """Return all concrete classes among the class itself and its subclasses."""
588 concrete = class_ir.concrete_subclasses()
589 if concrete is None:
590 return None
591 if not (class_ir.is_abstract or class_ir.is_trait):
592 concrete.append(class_ir)
593 return concrete