diff --git a/mypyc/codegen/emitmodule.py b/mypyc/codegen/emitmodule.py index 0f5093f3a258..cc63fba4bb73 100644 --- a/mypyc/codegen/emitmodule.py +++ b/mypyc/codegen/emitmodule.py @@ -79,7 +79,7 @@ from mypyc.irbuild.main import build_ir from mypyc.irbuild.mapper import Mapper from mypyc.irbuild.prepare import load_type_map -from mypyc.irbuild.util import is_decorated_class, is_extension_class, is_trait +from mypyc.irbuild.util import get_mypyc_attrs, is_decorated_class, is_extension_class, is_trait from mypyc.namegen import NameGenerator, exported_name from mypyc.options import CompilerOptions from mypyc.transform.borrow_generator_attrs import borrow_generator_attrs @@ -118,6 +118,9 @@ # A list of (file name, file contents) pairs. FileContents = list[tuple[str, str]] +# The kind of a class that other modules depend on (see class_kinds). +ClassKind = tuple[str, bool, bool, bool, dict[str, str]] + class MarkedDeclaration: """Add a mark, useful for topological sort.""" @@ -141,8 +144,11 @@ class MypycPlugin(Plugin): other modules use a class: @mypyc_attr(native_class=False) and @trait decide what kind of class mypyc generates, and a decorator that can replace the class changes what its name refers to (see - ClassIR.is_decorated). So we make the kinds of a module's classes - part of its interface. + ClassIR.is_decorated). Most other mypyc_attr attributes also affect + subclasses, such as weakrefs (object layout), serializable (inherited) + and acyclic (required in base classes). So we make the kinds of a + module's classes, including all their mypyc_attr attributes, part of + its interface. """ def __init__( @@ -160,7 +166,7 @@ def __init__( def report_config_data( self, ctx: ReportConfigContext - ) -> tuple[str | None, list[str], list[tuple[str, bool, bool, bool]]] | None: + ) -> tuple[str | None, list[str], list[ClassKind]] | None: # The config data we report is the group map entry for the module, # followed by the kinds of its classes (see class_kinds). # If the data is being used to check validity, we do additional checks @@ -210,12 +216,10 @@ def report_config_data( return None # The module hasn't been parsed yet, so take the class kinds from the - # cached IR. It was built from the source the cache is for. - kinds = sorted( - (c["name"], c["is_ext_class"], c["is_trait"], c["is_decorated"]) - for c in ir_data["ir"]["classes"] - if not c["is_generated"] - ) + # IR cache. They were computed from the source the cache is for. + if "class_kinds" not in ir_data: + return None + kinds = [tuple(kind) for kind in ir_data["class_kinds"]] return (*self.group_map[id], kinds) def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: @@ -245,23 +249,30 @@ def get_additional_indirect_deps(self, file: MypyFile) -> set[str]: return mods -def class_kinds(tree: MypyFile, options: Options) -> list[tuple[str, bool, bool, bool]]: - """Return (name, is_ext_class, is_trait, is_decorated) for each class in a module. +def class_kinds(tree: MypyFile, options: Options) -> list[ClassKind]: + """Return the kind of each class in a module. - These match the ClassIR flags that build_type_map sets. + The kind of a class is (name, is_ext_class, is_trait, is_decorated, + mypyc_attrs). The flags match the ClassIR flags that build_type_map sets. + The mypyc_attr values are stored using repr(), since an invalid value + isn't always JSON serializable. """ # Any errors are reported when the module is compiled. errors = Errors(options) - return sorted( + return [ ( node.name, is_extension_class(tree.path, node, errors), is_trait(node), is_decorated_class(node), + { + key: repr(value) + for key, value in get_mypyc_attrs(node, tree.path, errors)[0].items() + }, ) for node in tree.defs if isinstance(node, ClassDef) - ) + ] def parse_and_typecheck( @@ -510,6 +521,8 @@ def write_cache( * The hashes of all the source file outputs for the group the module is in. This is so that the module will be recompiled if the source outputs are missing. + * The kinds of the classes in the module (see class_kinds), so + that MypycPlugin can check them without parsing the module. """ hashes = {} @@ -532,6 +545,7 @@ def write_cache( "ir": module.serialize(), "meta_hash": hash_digest(meta_data), "src_hashes": hashes[group_map[id]], + "class_kinds": class_kinds(result.files[id], result.manager.options), } result.manager.metastore.write(newpath, json_dumps(ir_data)) diff --git a/mypyc/test-data/run-multimodule.test b/mypyc/test-data/run-multimodule.test index 4ac44dbe3b65..2c97b71f2f5f 100644 --- a/mypyc/test-data/run-multimodule.test +++ b/mypyc/test-data/run-multimodule.test @@ -1806,12 +1806,18 @@ import native NT(x=4) {'x': 5} -[case testIncrementalCompilationTogglingNonExtClass] -# Mypy ignores mypyc_attr, so making C a non-native class (or a native class -# again) doesn't change the interface of other.py. native.py must still be -# recompiled, since it constructs C and accesses its attributes differently. +[case testIncrementalCompilationTogglingMypycAttrs] +# Mypy ignores mypyc_attr, so toggling it doesn't change the interface of +# other.py, but native.py must still be recompiled: +# - native_class=False (steps 2 and 4): native.py constructs C and accesses its +# attributes differently. +# - weakrefs=True (step 5): adds a weak reference list to A, which changes the +# object layout of B. +# - serializable=True (step 6): B inherits the flag, and then B.__new__ must not +# call __init__, since copy.copy() calls it without arguments. +# - acyclic=True (step 7): a class can only be acyclic if its base classes are. # In step 3 other.py is unchanged, so it must stay fresh. -from other import C +from other import A, C def make(x: int) -> C: return C(x) @@ -1819,6 +1825,12 @@ def make(x: int) -> C: def get(c: C) -> int: return c.x +class B(A): + def __init__(self, y: int) -> None: + super().__init__() + self.y = y + self.t = "b" + [file other.py] from mypy_extensions import mypyc_attr @@ -1826,6 +1838,14 @@ class C: def __init__(self, x: int) -> None: self.x = x +class A: + def __init__(self) -> None: + self.x = 1 + self.s = "a" + +def get_x(a: A) -> int: + return a.x + [file other.py.2] from mypy_extensions import mypyc_attr @@ -1834,8 +1854,16 @@ class C: def __init__(self, x: int) -> None: self.x = x +class A: + def __init__(self) -> None: + self.x = 1 + self.s = "a" + +def get_x(a: A) -> int: + return a.x + [file native.py.3] -from other import C +from other import A, C def make(x: int) -> C: return C(x + 1) @@ -1843,6 +1871,12 @@ def make(x: int) -> C: def get(c: C) -> int: return c.x +class B(A): + def __init__(self, y: int) -> None: + super().__init__() + self.y = y + self.t = "b" + [file other.py.4] from mypy_extensions import mypyc_attr @@ -1850,23 +1884,103 @@ class C: def __init__(self, x: int) -> None: self.x = x +class A: + def __init__(self) -> None: + self.x = 1 + self.s = "a" + +def get_x(a: A) -> int: + return a.x + +[file other.py.5] +from mypy_extensions import mypyc_attr + +class C: + def __init__(self, x: int) -> None: + self.x = x + +@mypyc_attr(weakrefs=True) +class A: + def __init__(self) -> None: + self.x = 1 + self.s = "a" + +def get_x(a: A) -> int: + return a.x + +[file other.py.6] +from mypy_extensions import mypyc_attr + +class C: + def __init__(self, x: int) -> None: + self.x = x + +@mypyc_attr(weakrefs=True, serializable=True) +class A: + def __init__(self) -> None: + self.x = 1 + self.s = "a" + +def get_x(a: A) -> int: + return a.x + +[file other.py.7] +from mypy_extensions import mypyc_attr + +class C: + def __init__(self, x: int) -> None: + self.x = x + +@mypyc_attr(weakrefs=True, serializable=True, acyclic=True) +class A: + def __init__(self) -> None: + self.x = 1 + self.s = "a" + +def get_x(a: A) -> int: + return a.x + [file driver.py] -from native import get, make +import copy +import gc +import weakref +from native import B, get, make +from other import A, get_x c = make(3) -print(get(c), hasattr(c, "__dict__")) +b = B(2) +try: + weak = weakref.ref(b)() is b +except TypeError: + weak = False +try: + b2 = copy.copy(b) +except TypeError: + copied = False +else: + copied = (b2.x, b2.s, b2.y, b2.t) == (1, "a", 2, "b") +print(get(c), hasattr(c, "__dict__"), get_x(b), b.s, b.y, b.t, weak, copied, gc.is_tracked(A())) [out] -3 False +3 False 1 a 2 b False False True [out2] -3 True +3 True 1 a 2 b False False True [out3] -4 True +4 True 1 a 2 b False False True [out4] -4 False +4 False 1 a 2 b False False True +[out5] +4 False 1 a 2 b True False True +[out6] +4 False 1 a 2 b True True True +[out7] +4 False 1 a 2 b True True False [rechecked native, other] [rechecked2 native] [rechecked3 native, other] +[rechecked4 native, other] +[rechecked5 native, other] +[rechecked6 native, other] [case testIncrementalCompilationTogglingTrait] # Mypy also ignores @trait. Making T a trait changes how other.py calls m(),