prepare.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. """Prepare for IR transform.
  2. This needs to run after type checking and before generating IR.
  3. For example, construct partially initialized FuncIR and ClassIR
  4. objects for all functions and classes. This allows us to bind
  5. references to functions and classes before we've generated full IR for
  6. functions or classes. The actual IR transform will then populate all
  7. the missing bits, such as function bodies (basic blocks).
  8. Also build a mapping from mypy TypeInfos to ClassIR objects.
  9. """
  10. from __future__ import annotations
  11. from collections import defaultdict
  12. from typing import Iterable, NamedTuple, Tuple
  13. from mypy.build import Graph
  14. from mypy.nodes import (
  15. ARG_STAR,
  16. ARG_STAR2,
  17. CallExpr,
  18. ClassDef,
  19. Decorator,
  20. Expression,
  21. FuncDef,
  22. MemberExpr,
  23. MypyFile,
  24. NameExpr,
  25. OverloadedFuncDef,
  26. RefExpr,
  27. SymbolNode,
  28. TypeInfo,
  29. Var,
  30. )
  31. from mypy.semanal import refers_to_fullname
  32. from mypy.traverser import TraverserVisitor
  33. from mypy.types import Instance, Type, get_proper_type
  34. from mypyc.common import PROPSET_PREFIX, get_id_from_name
  35. from mypyc.crash import catch_errors
  36. from mypyc.errors import Errors
  37. from mypyc.ir.class_ir import ClassIR
  38. from mypyc.ir.func_ir import (
  39. FUNC_CLASSMETHOD,
  40. FUNC_NORMAL,
  41. FUNC_STATICMETHOD,
  42. FuncDecl,
  43. FuncSignature,
  44. RuntimeArg,
  45. )
  46. from mypyc.ir.ops import DeserMaps
  47. from mypyc.ir.rtypes import RInstance, RType, dict_rprimitive, none_rprimitive, tuple_rprimitive
  48. from mypyc.irbuild.mapper import Mapper
  49. from mypyc.irbuild.util import (
  50. get_func_def,
  51. get_mypyc_attrs,
  52. is_dataclass,
  53. is_extension_class,
  54. is_trait,
  55. )
  56. from mypyc.options import CompilerOptions
  57. from mypyc.sametype import is_same_type
  58. def build_type_map(
  59. mapper: Mapper,
  60. modules: list[MypyFile],
  61. graph: Graph,
  62. types: dict[Expression, Type],
  63. options: CompilerOptions,
  64. errors: Errors,
  65. ) -> None:
  66. # Collect all classes defined in everything we are compiling
  67. classes = []
  68. for module in modules:
  69. module_classes = [node for node in module.defs if isinstance(node, ClassDef)]
  70. classes.extend([(module, cdef) for cdef in module_classes])
  71. # Collect all class mappings so that we can bind arbitrary class name
  72. # references even if there are import cycles.
  73. for module, cdef in classes:
  74. class_ir = ClassIR(
  75. cdef.name, module.fullname, is_trait(cdef), is_abstract=cdef.info.is_abstract
  76. )
  77. class_ir.is_ext_class = is_extension_class(cdef)
  78. if class_ir.is_ext_class:
  79. class_ir.deletable = cdef.info.deletable_attributes.copy()
  80. # If global optimizations are disabled, turn of tracking of class children
  81. if not options.global_opts:
  82. class_ir.children = None
  83. mapper.type_to_ir[cdef.info] = class_ir
  84. # Populate structural information in class IR for extension classes.
  85. for module, cdef in classes:
  86. with catch_errors(module.path, cdef.line):
  87. if mapper.type_to_ir[cdef.info].is_ext_class:
  88. prepare_class_def(module.path, module.fullname, cdef, errors, mapper)
  89. else:
  90. prepare_non_ext_class_def(module.path, module.fullname, cdef, errors, mapper)
  91. # Prepare implicit attribute accessors as needed if an attribute overrides a property.
  92. for module, cdef in classes:
  93. class_ir = mapper.type_to_ir[cdef.info]
  94. if class_ir.is_ext_class:
  95. prepare_implicit_property_accessors(cdef.info, class_ir, module.fullname, mapper)
  96. # Collect all the functions also. We collect from the symbol table
  97. # so that we can easily pick out the right copy of a function that
  98. # is conditionally defined.
  99. for module in modules:
  100. for func in get_module_func_defs(module):
  101. prepare_func_def(module.fullname, None, func, mapper)
  102. # TODO: what else?
  103. # Check for incompatible attribute definitions that were not
  104. # flagged by mypy but can't be supported when compiling.
  105. for module, cdef in classes:
  106. class_ir = mapper.type_to_ir[cdef.info]
  107. for attr in class_ir.attributes:
  108. for base_ir in class_ir.mro[1:]:
  109. if attr in base_ir.attributes:
  110. if not is_same_type(class_ir.attributes[attr], base_ir.attributes[attr]):
  111. node = cdef.info.names[attr].node
  112. assert node is not None
  113. kind = "trait" if base_ir.is_trait else "class"
  114. errors.error(
  115. f'Type of "{attr}" is incompatible with '
  116. f'definition in {kind} "{base_ir.name}"',
  117. module.path,
  118. node.line,
  119. )
  120. def is_from_module(node: SymbolNode, module: MypyFile) -> bool:
  121. return node.fullname == module.fullname + "." + node.name
  122. def load_type_map(mapper: Mapper, modules: list[MypyFile], deser_ctx: DeserMaps) -> None:
  123. """Populate a Mapper with deserialized IR from a list of modules."""
  124. for module in modules:
  125. for name, node in module.names.items():
  126. if isinstance(node.node, TypeInfo) and is_from_module(node.node, module):
  127. ir = deser_ctx.classes[node.node.fullname]
  128. mapper.type_to_ir[node.node] = ir
  129. mapper.func_to_decl[node.node] = ir.ctor
  130. for module in modules:
  131. for func in get_module_func_defs(module):
  132. func_id = get_id_from_name(func.name, func.fullname, func.line)
  133. mapper.func_to_decl[func] = deser_ctx.functions[func_id].decl
  134. def get_module_func_defs(module: MypyFile) -> Iterable[FuncDef]:
  135. """Collect all of the (non-method) functions declared in a module."""
  136. for name, node in module.names.items():
  137. # We need to filter out functions that are imported or
  138. # aliases. The best way to do this seems to be by
  139. # checking that the fullname matches.
  140. if isinstance(node.node, (FuncDef, Decorator, OverloadedFuncDef)) and is_from_module(
  141. node.node, module
  142. ):
  143. yield get_func_def(node.node)
  144. def prepare_func_def(
  145. module_name: str, class_name: str | None, fdef: FuncDef, mapper: Mapper
  146. ) -> FuncDecl:
  147. kind = (
  148. FUNC_STATICMETHOD
  149. if fdef.is_static
  150. else (FUNC_CLASSMETHOD if fdef.is_class else FUNC_NORMAL)
  151. )
  152. decl = FuncDecl(fdef.name, class_name, module_name, mapper.fdef_to_sig(fdef), kind)
  153. mapper.func_to_decl[fdef] = decl
  154. return decl
  155. def prepare_method_def(
  156. ir: ClassIR, module_name: str, cdef: ClassDef, mapper: Mapper, node: FuncDef | Decorator
  157. ) -> None:
  158. if isinstance(node, FuncDef):
  159. ir.method_decls[node.name] = prepare_func_def(module_name, cdef.name, node, mapper)
  160. elif isinstance(node, Decorator):
  161. # TODO: do something about abstract methods here. Currently, they are handled just like
  162. # normal methods.
  163. decl = prepare_func_def(module_name, cdef.name, node.func, mapper)
  164. if not node.decorators:
  165. ir.method_decls[node.name] = decl
  166. elif isinstance(node.decorators[0], MemberExpr) and node.decorators[0].name == "setter":
  167. # Make property setter name different than getter name so there are no
  168. # name clashes when generating C code, and property lookup at the IR level
  169. # works correctly.
  170. decl.name = PROPSET_PREFIX + decl.name
  171. decl.is_prop_setter = True
  172. # Making the argument implicitly positional-only avoids unnecessary glue methods
  173. decl.sig.args[1].pos_only = True
  174. ir.method_decls[PROPSET_PREFIX + node.name] = decl
  175. if node.func.is_property:
  176. assert node.func.type, f"Expected return type annotation for property '{node.name}'"
  177. decl.is_prop_getter = True
  178. ir.property_types[node.name] = decl.sig.ret_type
  179. def is_valid_multipart_property_def(prop: OverloadedFuncDef) -> bool:
  180. # Checks to ensure supported property decorator semantics
  181. if len(prop.items) != 2:
  182. return False
  183. getter = prop.items[0]
  184. setter = prop.items[1]
  185. return (
  186. isinstance(getter, Decorator)
  187. and isinstance(setter, Decorator)
  188. and getter.func.is_property
  189. and len(setter.decorators) == 1
  190. and isinstance(setter.decorators[0], MemberExpr)
  191. and setter.decorators[0].name == "setter"
  192. )
  193. def can_subclass_builtin(builtin_base: str) -> bool:
  194. # BaseException and dict are special cased.
  195. return builtin_base in (
  196. (
  197. "builtins.Exception",
  198. "builtins.LookupError",
  199. "builtins.IndexError",
  200. "builtins.Warning",
  201. "builtins.UserWarning",
  202. "builtins.ValueError",
  203. "builtins.object",
  204. )
  205. )
  206. def prepare_class_def(
  207. path: str, module_name: str, cdef: ClassDef, errors: Errors, mapper: Mapper
  208. ) -> None:
  209. """Populate the interface-level information in a class IR.
  210. This includes attribute and method declarations, and the MRO, among other things, but
  211. method bodies are generated in a later pass.
  212. """
  213. ir = mapper.type_to_ir[cdef.info]
  214. info = cdef.info
  215. attrs = get_mypyc_attrs(cdef)
  216. if attrs.get("allow_interpreted_subclasses") is True:
  217. ir.allow_interpreted_subclasses = True
  218. if attrs.get("serializable") is True:
  219. # Supports copy.copy and pickle (including subclasses)
  220. ir._serializable = True
  221. # Check for subclassing from builtin types
  222. for cls in info.mro:
  223. # Special case exceptions and dicts
  224. # XXX: How do we handle *other* things??
  225. if cls.fullname == "builtins.BaseException":
  226. ir.builtin_base = "PyBaseExceptionObject"
  227. elif cls.fullname == "builtins.dict":
  228. ir.builtin_base = "PyDictObject"
  229. elif cls.fullname.startswith("builtins."):
  230. if not can_subclass_builtin(cls.fullname):
  231. # Note that if we try to subclass a C extension class that
  232. # isn't in builtins, bad things will happen and we won't
  233. # catch it here! But this should catch a lot of the most
  234. # common pitfalls.
  235. errors.error(
  236. "Inheriting from most builtin types is unimplemented", path, cdef.line
  237. )
  238. # Set up the parent class
  239. bases = [mapper.type_to_ir[base.type] for base in info.bases if base.type in mapper.type_to_ir]
  240. if len(bases) > 1 and any(not c.is_trait for c in bases) and bases[0].is_trait:
  241. # If the first base is a non-trait, don't ever error here. While it is correct
  242. # to error if a trait comes before the next non-trait base (e.g. non-trait, trait,
  243. # non-trait), it's pointless, confusing noise from the bigger issue: multiple
  244. # inheritance is *not* supported.
  245. errors.error("Non-trait base must appear first in parent list", path, cdef.line)
  246. ir.traits = [c for c in bases if c.is_trait]
  247. mro = [] # All mypyc base classes
  248. base_mro = [] # Non-trait mypyc base classes
  249. for cls in info.mro:
  250. if cls not in mapper.type_to_ir:
  251. if cls.fullname != "builtins.object":
  252. ir.inherits_python = True
  253. continue
  254. base_ir = mapper.type_to_ir[cls]
  255. if not base_ir.is_trait:
  256. base_mro.append(base_ir)
  257. mro.append(base_ir)
  258. if cls.defn.removed_base_type_exprs or not base_ir.is_ext_class:
  259. ir.inherits_python = True
  260. base_idx = 1 if not ir.is_trait else 0
  261. if len(base_mro) > base_idx:
  262. ir.base = base_mro[base_idx]
  263. ir.mro = mro
  264. ir.base_mro = base_mro
  265. prepare_methods_and_attributes(cdef, ir, path, module_name, errors, mapper)
  266. prepare_init_method(cdef, ir, module_name, mapper)
  267. for base in bases:
  268. if base.children is not None:
  269. base.children.append(ir)
  270. if is_dataclass(cdef):
  271. ir.is_augmented = True
  272. def prepare_methods_and_attributes(
  273. cdef: ClassDef, ir: ClassIR, path: str, module_name: str, errors: Errors, mapper: Mapper
  274. ) -> None:
  275. """Populate attribute and method declarations."""
  276. info = cdef.info
  277. for name, node in info.names.items():
  278. # Currently all plugin generated methods are dummies and not included.
  279. if node.plugin_generated:
  280. continue
  281. if isinstance(node.node, Var):
  282. assert node.node.type, "Class member %s missing type" % name
  283. if not node.node.is_classvar and name not in ("__slots__", "__deletable__"):
  284. attr_rtype = mapper.type_to_rtype(node.node.type)
  285. if ir.is_trait and attr_rtype.error_overlap:
  286. # Traits don't have attribute definedness bitmaps, so use
  287. # property accessor methods to access attributes that need them.
  288. # We will generate accessor implementations that use the class bitmap
  289. # for any concrete subclasses.
  290. add_getter_declaration(ir, name, attr_rtype, module_name)
  291. add_setter_declaration(ir, name, attr_rtype, module_name)
  292. ir.attributes[name] = attr_rtype
  293. elif isinstance(node.node, (FuncDef, Decorator)):
  294. prepare_method_def(ir, module_name, cdef, mapper, node.node)
  295. elif isinstance(node.node, OverloadedFuncDef):
  296. # Handle case for property with both a getter and a setter
  297. if node.node.is_property:
  298. if is_valid_multipart_property_def(node.node):
  299. for item in node.node.items:
  300. prepare_method_def(ir, module_name, cdef, mapper, item)
  301. else:
  302. errors.error("Unsupported property decorator semantics", path, cdef.line)
  303. # Handle case for regular function overload
  304. else:
  305. assert node.node.impl
  306. prepare_method_def(ir, module_name, cdef, mapper, node.node.impl)
  307. if ir.builtin_base:
  308. ir.attributes.clear()
  309. def prepare_implicit_property_accessors(
  310. info: TypeInfo, ir: ClassIR, module_name: str, mapper: Mapper
  311. ) -> None:
  312. concrete_attributes = set()
  313. for base in ir.base_mro:
  314. for name, attr_rtype in base.attributes.items():
  315. concrete_attributes.add(name)
  316. add_property_methods_for_attribute_if_needed(
  317. info, ir, name, attr_rtype, module_name, mapper
  318. )
  319. for base in ir.mro[1:]:
  320. if base.is_trait:
  321. for name, attr_rtype in base.attributes.items():
  322. if name not in concrete_attributes:
  323. add_property_methods_for_attribute_if_needed(
  324. info, ir, name, attr_rtype, module_name, mapper
  325. )
  326. def add_property_methods_for_attribute_if_needed(
  327. info: TypeInfo,
  328. ir: ClassIR,
  329. attr_name: str,
  330. attr_rtype: RType,
  331. module_name: str,
  332. mapper: Mapper,
  333. ) -> None:
  334. """Add getter and/or setter for attribute if defined as property in a base class.
  335. Only add declarations. The body IR will be synthesized later during irbuild.
  336. """
  337. for base in info.mro[1:]:
  338. if base in mapper.type_to_ir:
  339. base_ir = mapper.type_to_ir[base]
  340. n = base.names.get(attr_name)
  341. if n is None:
  342. continue
  343. node = n.node
  344. if isinstance(node, Decorator) and node.name not in ir.method_decls:
  345. # Defined as a read-only property in base class/trait
  346. add_getter_declaration(ir, attr_name, attr_rtype, module_name)
  347. elif isinstance(node, OverloadedFuncDef) and is_valid_multipart_property_def(node):
  348. # Defined as a read-write property in base class/trait
  349. add_getter_declaration(ir, attr_name, attr_rtype, module_name)
  350. add_setter_declaration(ir, attr_name, attr_rtype, module_name)
  351. elif base_ir.is_trait and attr_rtype.error_overlap:
  352. add_getter_declaration(ir, attr_name, attr_rtype, module_name)
  353. add_setter_declaration(ir, attr_name, attr_rtype, module_name)
  354. def add_getter_declaration(
  355. ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str
  356. ) -> None:
  357. self_arg = RuntimeArg("self", RInstance(ir), pos_only=True)
  358. sig = FuncSignature([self_arg], attr_rtype)
  359. decl = FuncDecl(attr_name, ir.name, module_name, sig, FUNC_NORMAL)
  360. decl.is_prop_getter = True
  361. decl.implicit = True # Triggers synthesization
  362. ir.method_decls[attr_name] = decl
  363. ir.property_types[attr_name] = attr_rtype # TODO: Needed??
  364. def add_setter_declaration(
  365. ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str
  366. ) -> None:
  367. self_arg = RuntimeArg("self", RInstance(ir), pos_only=True)
  368. value_arg = RuntimeArg("value", attr_rtype, pos_only=True)
  369. sig = FuncSignature([self_arg, value_arg], none_rprimitive)
  370. setter_name = PROPSET_PREFIX + attr_name
  371. decl = FuncDecl(setter_name, ir.name, module_name, sig, FUNC_NORMAL)
  372. decl.is_prop_setter = True
  373. decl.implicit = True # Triggers synthesization
  374. ir.method_decls[setter_name] = decl
  375. def prepare_init_method(cdef: ClassDef, ir: ClassIR, module_name: str, mapper: Mapper) -> None:
  376. # Set up a constructor decl
  377. init_node = cdef.info["__init__"].node
  378. if not ir.is_trait and not ir.builtin_base and isinstance(init_node, FuncDef):
  379. init_sig = mapper.fdef_to_sig(init_node)
  380. defining_ir = mapper.type_to_ir.get(init_node.info)
  381. # If there is a nontrivial __init__ that wasn't defined in an
  382. # extension class, we need to make the constructor take *args,
  383. # **kwargs so it can call tp_init.
  384. if (
  385. defining_ir is None
  386. or not defining_ir.is_ext_class
  387. or cdef.info["__init__"].plugin_generated
  388. ) and init_node.info.fullname != "builtins.object":
  389. init_sig = FuncSignature(
  390. [
  391. init_sig.args[0],
  392. RuntimeArg("args", tuple_rprimitive, ARG_STAR),
  393. RuntimeArg("kwargs", dict_rprimitive, ARG_STAR2),
  394. ],
  395. init_sig.ret_type,
  396. )
  397. last_arg = len(init_sig.args) - init_sig.num_bitmap_args
  398. ctor_sig = FuncSignature(init_sig.args[1:last_arg], RInstance(ir))
  399. ir.ctor = FuncDecl(cdef.name, None, module_name, ctor_sig)
  400. mapper.func_to_decl[cdef.info] = ir.ctor
  401. def prepare_non_ext_class_def(
  402. path: str, module_name: str, cdef: ClassDef, errors: Errors, mapper: Mapper
  403. ) -> None:
  404. ir = mapper.type_to_ir[cdef.info]
  405. info = cdef.info
  406. for name, node in info.names.items():
  407. if isinstance(node.node, (FuncDef, Decorator)):
  408. prepare_method_def(ir, module_name, cdef, mapper, node.node)
  409. elif isinstance(node.node, OverloadedFuncDef):
  410. # Handle case for property with both a getter and a setter
  411. if node.node.is_property:
  412. if not is_valid_multipart_property_def(node.node):
  413. errors.error("Unsupported property decorator semantics", path, cdef.line)
  414. for item in node.node.items:
  415. prepare_method_def(ir, module_name, cdef, mapper, item)
  416. # Handle case for regular function overload
  417. else:
  418. prepare_method_def(ir, module_name, cdef, mapper, get_func_def(node.node))
  419. if any(cls in mapper.type_to_ir and mapper.type_to_ir[cls].is_ext_class for cls in info.mro):
  420. errors.error(
  421. "Non-extension classes may not inherit from extension classes", path, cdef.line
  422. )
  423. RegisterImplInfo = Tuple[TypeInfo, FuncDef]
  424. class SingledispatchInfo(NamedTuple):
  425. singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]]
  426. decorators_to_remove: dict[FuncDef, list[int]]
  427. def find_singledispatch_register_impls(
  428. modules: list[MypyFile], errors: Errors
  429. ) -> SingledispatchInfo:
  430. visitor = SingledispatchVisitor(errors)
  431. for module in modules:
  432. visitor.current_path = module.path
  433. module.accept(visitor)
  434. return SingledispatchInfo(visitor.singledispatch_impls, visitor.decorators_to_remove)
  435. class SingledispatchVisitor(TraverserVisitor):
  436. current_path: str
  437. def __init__(self, errors: Errors) -> None:
  438. super().__init__()
  439. # Map of main singledispatch function to list of registered implementations
  440. self.singledispatch_impls: defaultdict[FuncDef, list[RegisterImplInfo]] = defaultdict(list)
  441. # Map of decorated function to the indices of any decorators to remove
  442. self.decorators_to_remove: dict[FuncDef, list[int]] = {}
  443. self.errors: Errors = errors
  444. def visit_decorator(self, dec: Decorator) -> None:
  445. if dec.decorators:
  446. decorators_to_store = dec.decorators.copy()
  447. decorators_to_remove: list[int] = []
  448. # the index of the last non-register decorator before finding a register decorator
  449. # when going through decorators from top to bottom
  450. last_non_register: int | None = None
  451. for i, d in enumerate(decorators_to_store):
  452. impl = get_singledispatch_register_call_info(d, dec.func)
  453. if impl is not None:
  454. self.singledispatch_impls[impl.singledispatch_func].append(
  455. (impl.dispatch_type, dec.func)
  456. )
  457. decorators_to_remove.append(i)
  458. if last_non_register is not None:
  459. # found a register decorator after a non-register decorator, which we
  460. # don't support because we'd have to make a copy of the function before
  461. # calling the decorator so that we can call it later, which complicates
  462. # the implementation for something that is probably not commonly used
  463. self.errors.error(
  464. "Calling decorator after registering function not supported",
  465. self.current_path,
  466. decorators_to_store[last_non_register].line,
  467. )
  468. else:
  469. if refers_to_fullname(d, "functools.singledispatch"):
  470. decorators_to_remove.append(i)
  471. # make sure that we still treat the function as a singledispatch function
  472. # even if we don't find any registered implementations (which might happen
  473. # if all registered implementations are registered dynamically)
  474. self.singledispatch_impls.setdefault(dec.func, [])
  475. last_non_register = i
  476. if decorators_to_remove:
  477. # calling register on a function that tries to dispatch based on type annotations
  478. # raises a TypeError because compiled functions don't have an __annotations__
  479. # attribute
  480. self.decorators_to_remove[dec.func] = decorators_to_remove
  481. super().visit_decorator(dec)
  482. class RegisteredImpl(NamedTuple):
  483. singledispatch_func: FuncDef
  484. dispatch_type: TypeInfo
  485. def get_singledispatch_register_call_info(
  486. decorator: Expression, func: FuncDef
  487. ) -> RegisteredImpl | None:
  488. # @fun.register(complex)
  489. # def g(arg): ...
  490. if (
  491. isinstance(decorator, CallExpr)
  492. and len(decorator.args) == 1
  493. and isinstance(decorator.args[0], RefExpr)
  494. ):
  495. callee = decorator.callee
  496. dispatch_type = decorator.args[0].node
  497. if not isinstance(dispatch_type, TypeInfo):
  498. return None
  499. if isinstance(callee, MemberExpr):
  500. return registered_impl_from_possible_register_call(callee, dispatch_type)
  501. # @fun.register
  502. # def g(arg: int): ...
  503. elif isinstance(decorator, MemberExpr):
  504. # we don't know if this is a register call yet, so we can't be sure that the function
  505. # actually has arguments
  506. if not func.arguments:
  507. return None
  508. arg_type = get_proper_type(func.arguments[0].variable.type)
  509. if not isinstance(arg_type, Instance):
  510. return None
  511. info = arg_type.type
  512. return registered_impl_from_possible_register_call(decorator, info)
  513. return None
  514. def registered_impl_from_possible_register_call(
  515. expr: MemberExpr, dispatch_type: TypeInfo
  516. ) -> RegisteredImpl | None:
  517. if expr.name == "register" and isinstance(expr.expr, NameExpr):
  518. node = expr.expr.node
  519. if isinstance(node, Decorator):
  520. return RegisteredImpl(node.func, dispatch_type)
  521. return None