| 1 |
"""Maintain a mapping from mypy concepts to IR/compiled concepts.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from mypy.nodes import ARG_STAR, ARG_STAR2, GDEF, ArgKind, FuncDef, RefExpr, SymbolNode, TypeInfo |
| 6 |
from mypy.types import ( |
| 7 |
AnyType, |
| 8 |
CallableType, |
| 9 |
Instance, |
| 10 |
LiteralType, |
| 11 |
NoneTyp, |
| 12 |
Overloaded, |
| 13 |
PartialType, |
| 14 |
TupleType, |
| 15 |
Type, |
| 16 |
TypedDictType, |
| 17 |
TypeType, |
| 18 |
TypeVarLikeType, |
| 19 |
UnboundType, |
| 20 |
UninhabitedType, |
| 21 |
UnionType, |
| 22 |
find_unpack_in_list, |
| 23 |
get_proper_type, |
| 24 |
) |
| 25 |
from mypyc.ir.class_ir import ClassIR |
| 26 |
from mypyc.ir.func_ir import FuncDecl, FuncSignature, RuntimeArg |
| 27 |
from mypyc.ir.rtypes import ( |
| 28 |
KNOWN_NATIVE_TYPES, |
| 29 |
RInstance, |
| 30 |
RTuple, |
| 31 |
RType, |
| 32 |
RUnion, |
| 33 |
RVec, |
| 34 |
bool_rprimitive, |
| 35 |
bytearray_rprimitive, |
| 36 |
bytes_rprimitive, |
| 37 |
dict_rprimitive, |
| 38 |
float_rprimitive, |
| 39 |
frozenset_rprimitive, |
| 40 |
int16_rprimitive, |
| 41 |
int32_rprimitive, |
| 42 |
int64_rprimitive, |
| 43 |
int_rprimitive, |
| 44 |
list_rprimitive, |
| 45 |
none_rprimitive, |
| 46 |
object_rprimitive, |
| 47 |
range_rprimitive, |
| 48 |
set_rprimitive, |
| 49 |
str_rprimitive, |
| 50 |
tuple_rprimitive, |
| 51 |
uint8_rprimitive, |
| 52 |
) |
| 53 |
|
| 54 |
|
| 55 |
class Mapper: |
| 56 |
"""Keep track of mappings from mypy concepts to IR concepts. |
| 57 |
|
| 58 |
For example, we keep track of how the mypy TypeInfos of compiled |
| 59 |
classes map to class IR objects. |
| 60 |
|
| 61 |
This state is shared across all modules being compiled in all |
| 62 |
compilation groups. |
| 63 |
""" |
| 64 |
|
| 65 |
def __init__(self, group_map: dict[str, str | None]) -> None: |
| 66 |
self.group_map = group_map |
| 67 |
self.type_to_ir: dict[TypeInfo, ClassIR] = {} |
| 68 |
self.func_to_decl: dict[SymbolNode, FuncDecl] = {} |
| 69 |
self.symbol_fullnames: set[str] = set() |
| 70 |
# The corresponding generator class that implements a generator/async function |
| 71 |
self.fdef_to_generator: dict[FuncDef, ClassIR] = {} |
| 72 |
|
| 73 |
def type_to_rtype(self, typ: Type | None) -> RType: |
| 74 |
if typ is None: |
| 75 |
return object_rprimitive |
| 76 |
|
| 77 |
typ = get_proper_type(typ) |
| 78 |
if isinstance(typ, Instance): |
| 79 |
if typ.type.is_newtype: |
| 80 |
# Unwrap NewType to its base type for rprimitive mapping |
| 81 |
assert len(typ.type.bases) == 1, typ.type.bases |
| 82 |
return self.type_to_rtype(typ.type.bases[0]) |
| 83 |
if typ.type.fullname == "builtins.int": |
| 84 |
return int_rprimitive |
| 85 |
elif typ.type.fullname == "builtins.float": |
| 86 |
return float_rprimitive |
| 87 |
elif typ.type.fullname == "builtins.bool": |
| 88 |
return bool_rprimitive |
| 89 |
elif typ.type.fullname == "builtins.str": |
| 90 |
return str_rprimitive |
| 91 |
elif typ.type.fullname == "builtins.bytes": |
| 92 |
return bytes_rprimitive |
| 93 |
elif typ.type.fullname == "builtins.bytearray": |
| 94 |
return bytearray_rprimitive |
| 95 |
elif typ.type.fullname == "builtins.list": |
| 96 |
return list_rprimitive |
| 97 |
# Dict subclasses are at least somewhat common and we |
| 98 |
# specifically support them, so make sure that dict operations |
| 99 |
# get optimized on them. |
| 100 |
elif any(cls.fullname == "builtins.dict" for cls in typ.type.mro): |
| 101 |
return dict_rprimitive |
| 102 |
elif typ.type.fullname == "builtins.set": |
| 103 |
return set_rprimitive |
| 104 |
elif typ.type.fullname == "builtins.frozenset": |
| 105 |
return frozenset_rprimitive |
| 106 |
elif typ.type.fullname == "builtins.tuple": |
| 107 |
return tuple_rprimitive # Varying-length tuple |
| 108 |
elif typ.type.fullname == "builtins.range": |
| 109 |
return range_rprimitive |
| 110 |
elif typ.type in self.type_to_ir: |
| 111 |
inst = RInstance(self.type_to_ir[typ.type]) |
| 112 |
# Treat protocols as Union[protocol, object], so that we can do fast |
| 113 |
# method calls in the cases where the protocol is explicitly inherited from |
| 114 |
# and fall back to generic operations when it isn't. |
| 115 |
if typ.type.is_protocol: |
| 116 |
return RUnion([inst, object_rprimitive]) |
| 117 |
else: |
| 118 |
return inst |
| 119 |
elif typ.type.fullname == "mypy_extensions.i64": |
| 120 |
return int64_rprimitive |
| 121 |
elif typ.type.fullname == "mypy_extensions.i32": |
| 122 |
return int32_rprimitive |
| 123 |
elif typ.type.fullname == "mypy_extensions.i16": |
| 124 |
return int16_rprimitive |
| 125 |
elif typ.type.fullname == "mypy_extensions.u8": |
| 126 |
return uint8_rprimitive |
| 127 |
elif typ.type.fullname == "librt.vecs.vec": |
| 128 |
return RVec(self.type_to_rtype(typ.args[0])) |
| 129 |
elif typ.type.fullname in KNOWN_NATIVE_TYPES: |
| 130 |
return KNOWN_NATIVE_TYPES[typ.type.fullname] |
| 131 |
else: |
| 132 |
return object_rprimitive |
| 133 |
elif isinstance(typ, TupleType): |
| 134 |
# Use our unboxed tuples for raw tuples but fall back to |
| 135 |
# being boxed for NamedTuple or for variadic tuples. |
| 136 |
if ( |
| 137 |
typ.partial_fallback.type.fullname == "builtins.tuple" |
| 138 |
and find_unpack_in_list(typ.items) is None |
| 139 |
): |
| 140 |
return RTuple([self.type_to_rtype(t) for t in typ.items]) |
| 141 |
else: |
| 142 |
return tuple_rprimitive |
| 143 |
elif isinstance(typ, CallableType): |
| 144 |
return object_rprimitive |
| 145 |
elif isinstance(typ, NoneTyp): |
| 146 |
return none_rprimitive |
| 147 |
elif isinstance(typ, UnionType): |
| 148 |
return RUnion.make_simplified_union([self.type_to_rtype(item) for item in typ.items]) |
| 149 |
elif isinstance(typ, AnyType): |
| 150 |
return object_rprimitive |
| 151 |
elif isinstance(typ, TypeType): |
| 152 |
return object_rprimitive |
| 153 |
elif isinstance(typ, TypeVarLikeType): |
| 154 |
# Erase type variable to upper bound. |
| 155 |
# TODO: Erase to union if object has value restriction? |
| 156 |
return self.type_to_rtype(typ.upper_bound) |
| 157 |
elif isinstance(typ, PartialType): |
| 158 |
assert typ.var.type is not None |
| 159 |
return self.type_to_rtype(typ.var.type) |
| 160 |
elif isinstance(typ, Overloaded): |
| 161 |
return object_rprimitive |
| 162 |
elif isinstance(typ, TypedDictType): |
| 163 |
return dict_rprimitive |
| 164 |
elif isinstance(typ, LiteralType): |
| 165 |
return self.type_to_rtype(typ.fallback) |
| 166 |
elif isinstance(typ, (UninhabitedType, UnboundType)): |
| 167 |
# Sure, whatever! |
| 168 |
return object_rprimitive |
| 169 |
|
| 170 |
# I think we've covered everything that is supposed to |
| 171 |
# actually show up, so anything else is a bug somewhere. |
| 172 |
assert False, "unexpected type %s" % type(typ) |
| 173 |
|
| 174 |
def get_arg_rtype(self, typ: Type, kind: ArgKind) -> RType: |
| 175 |
if kind == ARG_STAR: |
| 176 |
return tuple_rprimitive |
| 177 |
elif kind == ARG_STAR2: |
| 178 |
return dict_rprimitive |
| 179 |
else: |
| 180 |
return self.type_to_rtype(typ) |
| 181 |
|
| 182 |
def fdef_to_sig(self, fdef: FuncDef, strict_dunders_typing: bool) -> FuncSignature: |
| 183 |
if isinstance(fdef.type, CallableType): |
| 184 |
arg_types = [ |
| 185 |
self.get_arg_rtype(typ, kind) |
| 186 |
for typ, kind in zip(fdef.type.arg_types, fdef.type.arg_kinds) |
| 187 |
] |
| 188 |
arg_pos_onlys = [name is None for name in fdef.type.arg_names] |
| 189 |
ret = self.type_to_rtype(fdef.type.ret_type) |
| 190 |
else: |
| 191 |
# Handle unannotated functions |
| 192 |
arg_types = [object_rprimitive for _ in fdef.arguments] |
| 193 |
arg_pos_onlys = [arg.pos_only for arg in fdef.arguments] |
| 194 |
# We at least know the return type for __init__ methods will be None. |
| 195 |
is_init_method = fdef.name == "__init__" and bool(fdef.info) |
| 196 |
if is_init_method: |
| 197 |
ret = none_rprimitive |
| 198 |
else: |
| 199 |
ret = object_rprimitive |
| 200 |
|
| 201 |
# mypyc FuncSignatures (unlike mypy types) want to have a name |
| 202 |
# present even when the argument is position only, since it is |
| 203 |
# the sole way that FuncDecl arguments are tracked. This is |
| 204 |
# generally fine except in some cases (like for computing |
| 205 |
# init_sig) we need to produce FuncSignatures from a |
| 206 |
# deserialized FuncDef that lacks arguments. We won't ever |
| 207 |
# need to use those inside of a FuncIR, so we just make up |
| 208 |
# some crap. |
| 209 |
if hasattr(fdef, "arguments"): |
| 210 |
arg_names = [arg.variable.name for arg in fdef.arguments] |
| 211 |
else: |
| 212 |
arg_names = [name or "" for name in fdef.arg_names] |
| 213 |
|
| 214 |
args = [ |
| 215 |
RuntimeArg(arg_name, arg_type, arg_kind, arg_pos_only) |
| 216 |
for arg_name, arg_kind, arg_type, arg_pos_only in zip( |
| 217 |
arg_names, fdef.arg_kinds, arg_types, arg_pos_onlys |
| 218 |
) |
| 219 |
] |
| 220 |
|
| 221 |
if not strict_dunders_typing: |
| 222 |
# We force certain dunder methods to return objects to support letting them |
| 223 |
# return NotImplemented. It also avoids some pointless boxing and unboxing, |
| 224 |
# since tp_richcompare needs an object anyways. |
| 225 |
# However, it also prevents some optimizations. |
| 226 |
if fdef.name in ("__eq__", "__ne__", "__lt__", "__gt__", "__le__", "__ge__"): |
| 227 |
ret = object_rprimitive |
| 228 |
|
| 229 |
return FuncSignature(args, ret) |
| 230 |
|
| 231 |
def is_native_module(self, module: str) -> bool: |
| 232 |
"""Is the given module one compiled by mypyc?""" |
| 233 |
return module in self.group_map |
| 234 |
|
| 235 |
def is_native_ref_expr(self, expr: RefExpr) -> bool: |
| 236 |
if expr.node is None: |
| 237 |
return False |
| 238 |
if "." in expr.node.fullname: |
| 239 |
name = expr.node.fullname.rpartition(".")[0] |
| 240 |
return self.is_native_module(name) or name in self.symbol_fullnames |
| 241 |
return True |
| 242 |
|
| 243 |
def is_native_module_ref_expr(self, expr: RefExpr) -> bool: |
| 244 |
return self.is_native_ref_expr(expr) and expr.kind == GDEF |