union[x, ..., y]
| 1114 | |
| 1115 | @final |
| 1116 | class RUnion(RType): |
| 1117 | """union[x, ..., y]""" |
| 1118 | |
| 1119 | is_unboxed = False |
| 1120 | |
| 1121 | def __init__(self, items: list[RType]) -> None: |
| 1122 | self.name = "union" |
| 1123 | self.items = items |
| 1124 | self.items_set = frozenset(items) |
| 1125 | self._ctype = "PyObject *" |
| 1126 | |
| 1127 | @staticmethod |
| 1128 | def make_simplified_union(items: list[RType]) -> RType: |
| 1129 | """Return a normalized union that covers the given items. |
| 1130 | |
| 1131 | Flatten nested unions and remove duplicate items. |
| 1132 | |
| 1133 | Overlapping items are *not* simplified. For example, |
| 1134 | [object, str] will not be simplified. |
| 1135 | """ |
| 1136 | items = flatten_nested_unions(items) |
| 1137 | assert items |
| 1138 | |
| 1139 | unique_items = dict.fromkeys(items) |
| 1140 | if len(unique_items) > 1: |
| 1141 | return RUnion(list(unique_items)) |
| 1142 | else: |
| 1143 | return next(iter(unique_items)) |
| 1144 | |
| 1145 | def accept(self, visitor: RTypeVisitor[T]) -> T: |
| 1146 | return visitor.visit_runion(self) |
| 1147 | |
| 1148 | @property |
| 1149 | def may_be_immortal(self) -> bool: |
| 1150 | return any(item.may_be_immortal for item in self.items) |
| 1151 | |
| 1152 | def __repr__(self) -> str: |
| 1153 | return "<RUnion %s>" % ", ".join(str(item) for item in self.items) |
| 1154 | |
| 1155 | def __str__(self) -> str: |
| 1156 | return "union[%s]" % ", ".join(str(item) for item in self.items) |
| 1157 | |
| 1158 | # We compare based on the set because order in a union doesn't matter |
| 1159 | def __eq__(self, other: object) -> TypeGuard[RUnion]: |
| 1160 | return isinstance(other, RUnion) and self.items_set == other.items_set |
| 1161 | |
| 1162 | def __hash__(self) -> int: |
| 1163 | return hash(("union", self.items_set)) |
| 1164 | |
| 1165 | def serialize(self) -> JsonDict: |
| 1166 | types = [x.serialize() for x in self.items] |
| 1167 | return {".class": "RUnion", "types": types} |
| 1168 | |
| 1169 | @classmethod |
| 1170 | def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RUnion: |
| 1171 | types = [deserialize_type(t, ctx) for t in data["types"]] |
| 1172 | return RUnion(types) |
| 1173 |
no outgoing calls
searching dependent graphs…