Debian Codegraph @

mypyc/test/test_serialization.py

raw
1 """Functions to check that serialization round-tripped properly."""
2
3 # This file is named test_serialization.py even though it doesn't
4 # contain its own tests so that pytest will rewrite the asserts...
5
6 from __future__ import annotations
7
8 from collections.abc import Iterable
9 from typing import Any
10
11 from mypyc.ir.class_ir import ClassIR
12 from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature
13 from mypyc.ir.module_ir import ModuleIR, deserialize_modules
14 from mypyc.ir.ops import DeserMaps
15 from mypyc.ir.rtypes import RType
16 from mypyc.sametype import is_same_signature, is_same_type
17
18
19 def get_dict(x: Any) -> dict[str, Any]:
20 if hasattr(x, "__mypyc_attrs__"):
21 return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}
22 else:
23 return dict(x.__dict__)
24
25
26 def get_function_dict(x: FuncIR) -> dict[str, Any]:
27 """Get a dict of function attributes safe to compare across serialization"""
28 d = get_dict(x)
29 d.pop("blocks", None)
30 d.pop("env", None)
31 return d
32
33
34 def assert_blobs_same(x: Any, y: Any, trail: tuple[Any, ...]) -> None:
35 """Compare two blobs of IR as best we can.
36
37 FuncDecls, FuncIRs, and ClassIRs are compared by fullname to avoid
38 infinite recursion.
39 (More detailed comparisons should be done manually.)
40
41 Types and signatures are compared using mypyc.sametype.
42
43 Containers are compared recursively.
44
45 Anything else is compared with ==.
46
47 The `trail` argument is used in error messages.
48 """
49
50 assert type(x) is type(y), (f"Type mismatch at {trail}", type(x), type(y))
51 if isinstance(x, (FuncDecl, FuncIR, ClassIR)):
52 assert x.fullname == y.fullname, f"Name mismatch at {trail}"
53 elif isinstance(x, dict):
54 assert len(x.keys()) == len(y.keys()), f"Keys mismatch at {trail}"
55 for (xk, xv), (yk, yv) in zip(x.items(), y.items()):
56 assert_blobs_same(xk, yk, trail + ("keys",))
57 assert_blobs_same(xv, yv, trail + (xk,))
58 elif isinstance(x, Iterable) and not isinstance(x, (str, set)):
59 # Special case iterables to generate better assert error messages.
60 # We can't use this for sets since the ordering is unpredictable,
61 # and strings should be treated as atomic values.
62 for i, (xv, yv) in enumerate(zip(x, y)):
63 assert_blobs_same(xv, yv, trail + (i,))
64 elif isinstance(x, RType):
65 assert is_same_type(x, y), f"RType mismatch at {trail}"
66 elif isinstance(x, FuncSignature):
67 assert is_same_signature(x, y), f"Signature mismatch at {trail}"
68 else:
69 assert x == y, f"Value mismatch at {trail}"
70
71
72 def assert_modules_same(ir1: ModuleIR, ir2: ModuleIR) -> None:
73 """Assert that two module IRs are the same (*).
74
75 * Or rather, as much as we care about preserving across
76 serialization. We drop the actual IR bodies of functions but try
77 to preserve everything else.
78 """
79 assert ir1.fullname == ir2.fullname
80
81 assert ir1.imports == ir2.imports
82
83 for cls1, cls2 in zip(ir1.classes, ir2.classes):
84 assert_blobs_same(get_dict(cls1), get_dict(cls2), (ir1.fullname, cls1.fullname))
85
86 for fn1, fn2 in zip(ir1.functions, ir2.functions):
87 assert_blobs_same(
88 get_function_dict(fn1), get_function_dict(fn2), (ir1.fullname, fn1.fullname)
89 )
90 assert_blobs_same(get_dict(fn1.decl), get_dict(fn2.decl), (ir1.fullname, fn1.fullname))
91
92 assert_blobs_same(ir1.final_names, ir2.final_names, (ir1.fullname, "final_names"))
93
94 assert ir1.dependencies == ir2.dependencies
95
96
97 def check_serialization_roundtrip(irs: dict[str, ModuleIR]) -> None:
98 """Check that we can serialize modules out and deserialize them to the same thing."""
99 serialized = {k: ir.serialize() for k, ir in irs.items()}
100
101 ctx = DeserMaps({}, {})
102 irs2 = deserialize_modules(serialized, ctx)
103 assert irs.keys() == irs2.keys()
104
105 for k in irs:
106 assert_modules_same(irs[k], irs2[k])