Debian Codegraph @

mypyc/sametype.py

raw
1 """Same type check for RTypes."""
2
3 from __future__ import annotations
4
5 from mypyc.ir.func_ir import FuncSignature
6 from mypyc.ir.rtypes import (
7 RArray,
8 RInstance,
9 RPrimitive,
10 RStruct,
11 RTuple,
12 RType,
13 RTypeVisitor,
14 RUnion,
15 RVec,
16 RVoid,
17 )
18
19
20 def is_same_type(a: RType, b: RType) -> bool:
21 return a.accept(SameTypeVisitor(b))
22
23
24 def is_same_signature(a: FuncSignature, b: FuncSignature) -> bool:
25 return (
26 len(a.args) == len(b.args)
27 and is_same_type(a.ret_type, b.ret_type)
28 and all(
29 is_same_type(t1.type, t2.type) and t1.name == t2.name for t1, t2 in zip(a.args, b.args)
30 )
31 )
32
33
34 def is_same_method_signature(a: FuncSignature, b: FuncSignature) -> bool:
35 return (
36 len(a.args) == len(b.args)
37 and is_same_type(a.ret_type, b.ret_type)
38 and all(
39 is_same_type(t1.type, t2.type)
40 and ((t1.pos_only and t2.pos_only) or t1.name == t2.name)
41 and t1.optional == t2.optional
42 for t1, t2 in zip(a.args[1:], b.args[1:])
43 )
44 )
45
46
47 class SameTypeVisitor(RTypeVisitor[bool]):
48 def __init__(self, right: RType) -> None:
49 self.right = right
50
51 def visit_rinstance(self, left: RInstance) -> bool:
52 return isinstance(self.right, RInstance) and left.name == self.right.name
53
54 def visit_rvec(self, left: RVec) -> bool:
55 return isinstance(self.right, RVec) and left.item_type == self.right.item_type
56
57 def visit_runion(self, left: RUnion) -> bool:
58 if isinstance(self.right, RUnion):
59 items = list(self.right.items)
60 for left_item in left.items:
61 for j, right_item in enumerate(items):
62 if is_same_type(left_item, right_item):
63 del items[j]
64 break
65 else:
66 return False
67 return not items
68 return False
69
70 def visit_rprimitive(self, left: RPrimitive) -> bool:
71 return left is self.right
72
73 def visit_rtuple(self, left: RTuple) -> bool:
74 return (
75 isinstance(self.right, RTuple)
76 and len(self.right.types) == len(left.types)
77 and all(is_same_type(t1, t2) for t1, t2 in zip(left.types, self.right.types))
78 )
79
80 def visit_rstruct(self, left: RStruct) -> bool:
81 return isinstance(self.right, RStruct) and self.right.name == left.name
82
83 def visit_rarray(self, left: RArray) -> bool:
84 return left == self.right
85
86 def visit_rvoid(self, left: RVoid) -> bool:
87 return isinstance(self.right, RVoid)