mapper.py 8.1 KB

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