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, 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 # Attributes defined in the class (not inherited)
147 self.attributes: dict[str, RType] = {}
148 # Deletable attributes
149 self.deletable: list[str] = []
150 # We populate method_types with the signatures of every method before
151 # we generate methods, and we rely on this information being present.
152 self.method_decls: dict[str, FuncDecl] = {}
153 # Map of methods that are actually present in an extension class
154 self.methods: dict[str, FuncIR] = {}
155 # Glue methods for boxing/unboxing when a class changes the type
156 # while overriding a method. Maps from (parent class overridden, method)
157 # to IR of glue method.
158 self.glue_methods: dict[tuple[ClassIR, str], FuncIR] = {}
159
160 # Properties are accessed like attributes, but have behavior like method calls.
161 # They don't belong in the methods dictionary, since we don't want to expose them to
162 # Python's method API. But we want to put them into our own vtable as methods, so that
163 # they are properly handled and overridden. The property dictionary values are a tuple
164 # containing a property getter and an optional property setter.
165 self.properties: dict[str, tuple[FuncIR, FuncIR | None]] = {}
166 # We generate these in prepare_class_def so that we have access to them when generating
167 # other methods and properties that rely on these types.
168 self.property_types: dict[str, RType] = {}
169
170 self.vtable: dict[str, int] | None = None
171 self.vtable_entries: VTableEntries = []
172 self.trait_vtables: dict[ClassIR, VTableEntries] = {}
173 # N.B: base might not actually quite be the direct base.
174 # It is the nearest concrete base, but we allow a trait in between.
175 self.base: ClassIR | None = None
176 self.traits: list[ClassIR] = []
177 # Supply a working mro for most generated classes. Real classes will need to
178 # fix it up.
179 self.mro: list[ClassIR] = [self]
180 # base_mro is the chain of concrete (non-trait) ancestors
181 self.base_mro: list[ClassIR] = [self]
182
183 # Direct subclasses of this class (use subclasses() to also include non-direct ones)
184 # None if separate compilation prevents this from working.
185 #
186 # Often it's better to use has_no_subclasses() or subclasses() instead.
187 self.children: list[ClassIR] | None = []
188
189 # Instance attributes that are initialized in the class body.
190 self.attrs_with_defaults: set[str] = set()
191
192 # Attributes that are always initialized in __init__ or class body
193 # (inferred in mypyc.analysis.attrdefined using interprocedural analysis).
194 # These can never raise AttributeError when accessed. If an attribute
195 # is *not* always initialized, we normally use the error value for
196 # an undefined value. If the attribute byte has an overlapping error value
197 # (the error_overlap attribute is true for the RType), we use a bitmap
198 # to track if the attribute is defined instead (see bitmap_attrs).
199 self._always_initialized_attrs: set[str] = set()
200
201 # Attributes that are sometimes initialized in __init__
202 self._sometimes_initialized_attrs: set[str] = set()
203
204 # If True, __init__ can make 'self' visible to unanalyzed/arbitrary code
205 self.init_self_leak = False
206
207 # Definedness of these attributes is backed by a bitmap. Index in the list
208 # indicates the bit number. Includes inherited attributes. We need the
209 # bitmap for types such as native ints (i64 etc.) that can't have a dedicated
210 # error value that doesn't overlap a valid value. The bitmap is used if the
211 # value of an attribute is the same as the error value.
212 self.bitmap_attrs: list[str] = []
213
214 # If this is a generator environment class, what is the actual method for it
215 self.env_user_function: FuncIR | None = None
216
217 # If True, keep one freed, cleared instance available for immediate reuse to
218 # speed up allocations. This helps if many objects are freed quickly, before
219 # other instances of the same class are allocated. This is effectively a
220 # per-type free "list" of up to length 1.
221 self.reuse_freed_instance = False
222
223 # If True, the class does not participate in cyclic garbage collection.
224 # This can improve performance but is only safe if instances can never
225 # be part of reference cycles. Derived from @mypyc_attr(acyclic=True).
226 self.is_acyclic = False
227
228 # Is this a class inheriting from enum.Enum? Such classes can be special-cased.
229 self.is_enum = False
230
231 # Name of the function if this a callable class representing a coroutine.
232 self.coroutine_name: str | None = None
233
234 def __repr__(self) -> str:
235 return (
236 "ClassIR("
237 "name={self.name}, module_name={self.module_name}, "
238 "is_trait={self.is_trait}, is_generated={self.is_generated}, "
239 "is_abstract={self.is_abstract}, is_ext_class={self.is_ext_class}, "
240 "is_final_class={self.is_final_class}"
241 ")".format(self=self)
242 )
243
244 @property
245 def fullname(self) -> str:
246 return f"{self.module_name}.{self.name}"
247
248 def real_base(self) -> ClassIR | None:
249 """Return the actual concrete base class, if there is one."""
250 if len(self.mro) > 1 and not self.mro[1].is_trait:
251 return self.mro[1]
252 return None
253
254 def vtable_entry(self, name: str) -> int:
255 assert self.vtable is not None, "vtable not computed yet"
256 assert name in self.vtable, f"{self.name!r} has no attribute {name!r}"
257 return self.vtable[name]
258
259 def attr_details(self, name: str) -> tuple[RType, ClassIR]:
260 for ir in self.mro:
261 if name in ir.attributes:
262 return ir.attributes[name], ir
263 if name in ir.property_types:
264 return ir.property_types[name], ir
265 raise KeyError(f"{self.name!r} has no attribute {name!r}")
266
267 def attr_type(self, name: str) -> RType:
268 return self.attr_details(name)[0]
269
270 def method_decl(self, name: str) -> FuncDecl:
271 for ir in self.mro:
272 if name in ir.method_decls:
273 return ir.method_decls[name]
274 raise KeyError(f"{self.name!r} has no attribute {name!r}")
275
276 def method_sig(self, name: str) -> FuncSignature:
277 return self.method_decl(name).sig
278
279 def has_method(self, name: str) -> bool:
280 try:
281 self.method_decl(name)
282 except KeyError:
283 return False
284 return True
285
286 def is_method_final(self, name: str) -> bool:
287 subs = self.subclasses()
288 if subs is None:
289 return self.is_final_class
290
291 if self.has_method(name):
292 method_decl = self.method_decl(name)
293 for subc in subs:
294 if subc.method_decl(name) != method_decl:
295 return False
296 return True
297 else:
298 return not any(subc.has_method(name) for subc in subs)
299
300 def has_attr(self, name: str) -> bool:
301 try:
302 self.attr_type(name)
303 except KeyError:
304 return False
305 return True
306
307 def is_deletable(self, name: str) -> bool:
308 return any(name in ir.deletable for ir in self.mro)
309
310 def is_always_defined(self, name: str) -> bool:
311 if self.is_deletable(name):
312 return False
313 return name in self._always_initialized_attrs
314
315 def name_prefix(self, names: NameGenerator) -> str:
316 return names.private_name(self.module_name, self.name)
317
318 def struct_name(self, names: NameGenerator) -> str:
319 return f"{exported_name(self.fullname)}Object"
320
321 def get_method_and_class(
322 self, name: str, *, prefer_method: bool = False
323 ) -> tuple[FuncIR, ClassIR] | None:
324 for ir in self.mro:
325 if name in ir.methods:
326 func_ir = ir.methods[name]
327 if not prefer_method and func_ir.decl.implicit:
328 # This is an implicit accessor, so there is also an attribute definition
329 # which the caller prefers. This happens if an attribute overrides a
330 # property.
331 return None
332 return func_ir, ir
333
334 return None
335
336 def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None:
337 res = self.get_method_and_class(name, prefer_method=prefer_method)
338 return res[0] if res else None
339
340 def has_method_decl(self, name: str) -> bool:
341 return any(name in ir.method_decls for ir in self.mro)
342
343 def has_no_subclasses(self) -> bool:
344 return self.children == [] and not self.allow_interpreted_subclasses
345
346 def subclasses(self) -> set[ClassIR] | None:
347 """Return all subclasses of this class, both direct and indirect.
348
349 Return None if it is impossible to identify all subclasses, for example
350 because we are performing separate compilation.
351 """
352 if self.children is None or self.allow_interpreted_subclasses:
353 return None
354 result = set(self.children)
355 for child in self.children:
356 if child.children:
357 child_subs = child.subclasses()
358 if child_subs is None:
359 return None
360 result.update(child_subs)
361 return result
362
363 def concrete_subclasses(self) -> list[ClassIR] | None:
364 """Return all concrete (i.e. non-trait and non-abstract) subclasses.
365
366 Include both direct and indirect subclasses. Place classes with no children first.
367 """
368 subs = self.subclasses()
369 if subs is None:
370 return None
371 concrete = {c for c in subs if not (c.is_trait or c.is_abstract)}
372 # We place classes with no children first because they are more likely
373 # to appear in various isinstance() checks. We then sort leaves by name
374 # to get stable order.
375 return sorted(concrete, key=lambda c: (len(c.children or []), c.name))
376
377 def is_serializable(self) -> bool:
378 return any(ci._serializable for ci in self.mro)
379
380 def serialize(self) -> JsonDict:
381 return {
382 "name": self.name,
383 "module_name": self.module_name,
384 "is_trait": self.is_trait,
385 "is_ext_class": self.is_ext_class,
386 "is_abstract": self.is_abstract,
387 "is_generated": self.is_generated,
388 "is_augmented": self.is_augmented,
389 "is_final_class": self.is_final_class,
390 "inherits_python": self.inherits_python,
391 "has_dict": self.has_dict,
392 "allow_interpreted_subclasses": self.allow_interpreted_subclasses,
393 "needs_getseters": self.needs_getseters,
394 "_serializable": self._serializable,
395 "builtin_base": self.builtin_base,
396 "ctor": self.ctor.serialize(),
397 # We serialize dicts as lists to ensure order is preserved
398 "attributes": [(k, t.serialize()) for k, t in self.attributes.items()],
399 # We try to serialize a name reference, but if the decl isn't in methods
400 # then we can't be sure that will work so we serialize the whole decl.
401 "method_decls": [
402 (k, d.id if k in self.methods else d.serialize())
403 for k, d in self.method_decls.items()
404 ],
405 # We serialize method fullnames out and put methods in a separate dict
406 "methods": [(k, m.id) for k, m in self.methods.items()],
407 "glue_methods": [
408 ((cir.fullname, k), m.id) for (cir, k), m in self.glue_methods.items()
409 ],
410 # We serialize properties and property_types separately out of an
411 # abundance of caution about preserving dict ordering...
412 "property_types": [(k, t.serialize()) for k, t in self.property_types.items()],
413 "properties": list(self.properties),
414 "vtable": self.vtable,
415 "vtable_entries": serialize_vtable(self.vtable_entries),
416 "trait_vtables": [
417 (cir.fullname, serialize_vtable(v)) for cir, v in self.trait_vtables.items()
418 ],
419 # References to class IRs are all just names
420 "base": self.base.fullname if self.base else None,
421 "traits": [cir.fullname for cir in self.traits],
422 "mro": [cir.fullname for cir in self.mro],
423 "base_mro": [cir.fullname for cir in self.base_mro],
424 "children": (
425 [cir.fullname for cir in self.children] if self.children is not None else None
426 ),
427 "deletable": self.deletable,
428 "attrs_with_defaults": sorted(self.attrs_with_defaults),
429 "_always_initialized_attrs": sorted(self._always_initialized_attrs),
430 "_sometimes_initialized_attrs": sorted(self._sometimes_initialized_attrs),
431 "init_self_leak": self.init_self_leak,
432 "env_user_function": self.env_user_function.id if self.env_user_function else None,
433 "reuse_freed_instance": self.reuse_freed_instance,
434 "is_acyclic": self.is_acyclic,
435 "is_enum": self.is_enum,
436 "is_coroutine": self.coroutine_name,
437 }
438
439 @classmethod
440 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR:
441 fullname = data["module_name"] + "." + data["name"]
442 assert fullname in ctx.classes, "Class %s not in deser class map" % fullname
443 ir = ctx.classes[fullname]
444
445 ir.is_trait = data["is_trait"]
446 ir.is_generated = data["is_generated"]
447 ir.is_abstract = data["is_abstract"]
448 ir.is_ext_class = data["is_ext_class"]
449 ir.is_augmented = data["is_augmented"]
450 ir.is_final_class = data["is_final_class"]
451 ir.inherits_python = data["inherits_python"]
452 ir.has_dict = data["has_dict"]
453 ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"]
454 ir.needs_getseters = data["needs_getseters"]
455 ir._serializable = data["_serializable"]
456 ir.builtin_base = data["builtin_base"]
457 ir.ctor = FuncDecl.deserialize(data["ctor"], ctx)
458 ir.attributes = {k: deserialize_type(t, ctx) for k, t in data["attributes"]}
459 ir.method_decls = {
460 k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)
461 for k, v in data["method_decls"]
462 }
463 ir.methods = {k: ctx.functions[v] for k, v in data["methods"]}
464 ir.glue_methods = {
465 (ctx.classes[c], k): ctx.functions[v] for (c, k), v in data["glue_methods"]
466 }
467 ir.property_types = {k: deserialize_type(t, ctx) for k, t in data["property_types"]}
468 ir.properties = {
469 k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data["properties"]
470 }
471
472 ir.vtable = data["vtable"]
473 ir.vtable_entries = deserialize_vtable(data["vtable_entries"], ctx)
474 ir.trait_vtables = {
475 ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data["trait_vtables"]
476 }
477
478 base = data["base"]
479 ir.base = ctx.classes[base] if base else None
480 ir.traits = [ctx.classes[s] for s in data["traits"]]
481 ir.mro = [ctx.classes[s] for s in data["mro"]]
482 ir.base_mro = [ctx.classes[s] for s in data["base_mro"]]
483 ir.children = data["children"] and [ctx.classes[s] for s in data["children"]]
484 ir.deletable = data["deletable"]
485 ir.attrs_with_defaults = set(data["attrs_with_defaults"])
486 ir._always_initialized_attrs = set(data["_always_initialized_attrs"])
487 ir._sometimes_initialized_attrs = set(data["_sometimes_initialized_attrs"])
488 ir.init_self_leak = data["init_self_leak"]
489 ir.env_user_function = (
490 ctx.functions[data["env_user_function"]] if data["env_user_function"] else None
491 )
492 ir.reuse_freed_instance = data["reuse_freed_instance"]
493 ir.is_acyclic = data.get("is_acyclic", False)
494 ir.is_enum = data["is_enum"]
495 ir.coroutine_name = data["is_coroutine"]
496
497 return ir
498
499
500 class NonExtClassInfo:
501 """Information needed to construct a non-extension class (Python class).
502
503 Includes the class dictionary, a tuple of base classes,
504 the class annotations dictionary, and the metaclass.
505 """
506
507 def __init__(self, dict: Value, bases: Value, anns: Value, metaclass: Value) -> None:
508 self.dict = dict
509 self.bases = bases
510 self.anns = anns
511 self.metaclass = metaclass
512
513
514 def serialize_vtable_entry(entry: VTableMethod) -> JsonDict:
515 return {
516 ".class": "VTableMethod",
517 "cls": entry.cls.fullname,
518 "name": entry.name,
519 "method": entry.method.decl.id,
520 "shadow_method": entry.shadow_method.decl.id if entry.shadow_method else None,
521 }
522
523
524 def serialize_vtable(vtable: VTableEntries) -> list[JsonDict]:
525 return [serialize_vtable_entry(v) for v in vtable]
526
527
528 def deserialize_vtable_entry(data: JsonDict, ctx: DeserMaps) -> VTableMethod:
529 if data[".class"] == "VTableMethod":
530 return VTableMethod(
531 ctx.classes[data["cls"]],
532 data["name"],
533 ctx.functions[data["method"]],
534 ctx.functions[data["shadow_method"]] if data["shadow_method"] else None,
535 )
536 assert False, "Bogus vtable .class: %s" % data[".class"]
537
538
539 def deserialize_vtable(data: list[JsonDict], ctx: DeserMaps) -> VTableEntries:
540 return [deserialize_vtable_entry(x, ctx) for x in data]
541
542
543 def all_concrete_classes(class_ir: ClassIR) -> list[ClassIR] | None:
544 """Return all concrete classes among the class itself and its subclasses."""
545 concrete = class_ir.concrete_subclasses()
546 if concrete is None:
547 return None
548 if not (class_ir.is_abstract or class_ir.is_trait):
549 concrete.append(class_ir)
550 return concrete