function.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. """Transform mypy AST functions to IR (and related things).
  2. Normal functions are translated into a list of basic blocks
  3. containing various IR ops (defined in mypyc.ir.ops).
  4. This also deals with generators, async functions and nested
  5. functions. All of these are transformed into callable classes. These
  6. have a custom __call__ method that implements the call, and state, such
  7. as an environment containing non-local variables, is stored in the
  8. instance of the callable class.
  9. """
  10. from __future__ import annotations
  11. from collections import defaultdict
  12. from typing import NamedTuple, Sequence
  13. from mypy.nodes import (
  14. ArgKind,
  15. ClassDef,
  16. Decorator,
  17. FuncDef,
  18. FuncItem,
  19. LambdaExpr,
  20. OverloadedFuncDef,
  21. SymbolNode,
  22. TypeInfo,
  23. Var,
  24. )
  25. from mypy.types import CallableType, get_proper_type
  26. from mypyc.common import LAMBDA_NAME, PROPSET_PREFIX, SELF_NAME
  27. from mypyc.ir.class_ir import ClassIR, NonExtClassInfo
  28. from mypyc.ir.func_ir import (
  29. FUNC_CLASSMETHOD,
  30. FUNC_NORMAL,
  31. FUNC_STATICMETHOD,
  32. FuncDecl,
  33. FuncIR,
  34. FuncSignature,
  35. RuntimeArg,
  36. )
  37. from mypyc.ir.ops import (
  38. BasicBlock,
  39. GetAttr,
  40. InitStatic,
  41. Integer,
  42. LoadAddress,
  43. LoadLiteral,
  44. Register,
  45. Return,
  46. SetAttr,
  47. Unbox,
  48. Unreachable,
  49. Value,
  50. )
  51. from mypyc.ir.rtypes import (
  52. RInstance,
  53. bool_rprimitive,
  54. dict_rprimitive,
  55. int_rprimitive,
  56. object_rprimitive,
  57. )
  58. from mypyc.irbuild.builder import IRBuilder, SymbolTarget, gen_arg_defaults
  59. from mypyc.irbuild.callable_class import (
  60. add_call_to_callable_class,
  61. add_get_to_callable_class,
  62. instantiate_callable_class,
  63. setup_callable_class,
  64. )
  65. from mypyc.irbuild.context import FuncInfo, ImplicitClass
  66. from mypyc.irbuild.env_class import (
  67. finalize_env_class,
  68. load_env_registers,
  69. load_outer_envs,
  70. setup_env_class,
  71. setup_func_for_recursive_call,
  72. )
  73. from mypyc.irbuild.generator import (
  74. add_methods_to_generator_class,
  75. add_raise_exception_blocks_to_generator_class,
  76. create_switch_for_generator_class,
  77. gen_generator_func,
  78. populate_switch_for_generator_class,
  79. setup_env_for_generator_class,
  80. )
  81. from mypyc.irbuild.targets import AssignmentTarget
  82. from mypyc.irbuild.util import is_constant
  83. from mypyc.primitives.dict_ops import dict_get_method_with_none, dict_new_op, dict_set_item_op
  84. from mypyc.primitives.generic_ops import py_setattr_op
  85. from mypyc.primitives.misc_ops import register_function
  86. from mypyc.primitives.registry import builtin_names
  87. from mypyc.sametype import is_same_method_signature, is_same_type
  88. # Top-level transform functions
  89. def transform_func_def(builder: IRBuilder, fdef: FuncDef) -> None:
  90. func_ir, func_reg = gen_func_item(builder, fdef, fdef.name, builder.mapper.fdef_to_sig(fdef))
  91. # If the function that was visited was a nested function, then either look it up in our
  92. # current environment or define it if it was not already defined.
  93. if func_reg:
  94. builder.assign(get_func_target(builder, fdef), func_reg, fdef.line)
  95. maybe_insert_into_registry_dict(builder, fdef)
  96. builder.functions.append(func_ir)
  97. def transform_overloaded_func_def(builder: IRBuilder, o: OverloadedFuncDef) -> None:
  98. # Handle regular overload case
  99. assert o.impl
  100. builder.accept(o.impl)
  101. def transform_decorator(builder: IRBuilder, dec: Decorator) -> None:
  102. func_ir, func_reg = gen_func_item(
  103. builder, dec.func, dec.func.name, builder.mapper.fdef_to_sig(dec.func)
  104. )
  105. decorated_func: Value | None = None
  106. if func_reg:
  107. decorated_func = load_decorated_func(builder, dec.func, func_reg)
  108. builder.assign(get_func_target(builder, dec.func), decorated_func, dec.func.line)
  109. # If the prebuild pass didn't put this function in the function to decorators map (for example
  110. # if this is a registered singledispatch implementation with no other decorators), we should
  111. # treat this function as a regular function, not a decorated function
  112. elif dec.func in builder.fdefs_to_decorators:
  113. # Obtain the function name in order to construct the name of the helper function.
  114. name = dec.func.fullname.split(".")[-1]
  115. # Load the callable object representing the non-decorated function, and decorate it.
  116. orig_func = builder.load_global_str(name, dec.line)
  117. decorated_func = load_decorated_func(builder, dec.func, orig_func)
  118. if decorated_func is not None:
  119. # Set the callable object representing the decorated function as a global.
  120. builder.call_c(
  121. dict_set_item_op,
  122. [builder.load_globals_dict(), builder.load_str(dec.func.name), decorated_func],
  123. decorated_func.line,
  124. )
  125. maybe_insert_into_registry_dict(builder, dec.func)
  126. builder.functions.append(func_ir)
  127. def transform_lambda_expr(builder: IRBuilder, expr: LambdaExpr) -> Value:
  128. typ = get_proper_type(builder.types[expr])
  129. assert isinstance(typ, CallableType)
  130. runtime_args = []
  131. for arg, arg_type in zip(expr.arguments, typ.arg_types):
  132. arg.variable.type = arg_type
  133. runtime_args.append(
  134. RuntimeArg(arg.variable.name, builder.type_to_rtype(arg_type), arg.kind)
  135. )
  136. ret_type = builder.type_to_rtype(typ.ret_type)
  137. fsig = FuncSignature(runtime_args, ret_type)
  138. fname = f"{LAMBDA_NAME}{builder.lambda_counter}"
  139. builder.lambda_counter += 1
  140. func_ir, func_reg = gen_func_item(builder, expr, fname, fsig)
  141. assert func_reg is not None
  142. builder.functions.append(func_ir)
  143. return func_reg
  144. # Internal functions
  145. def gen_func_item(
  146. builder: IRBuilder,
  147. fitem: FuncItem,
  148. name: str,
  149. sig: FuncSignature,
  150. cdef: ClassDef | None = None,
  151. ) -> tuple[FuncIR, Value | None]:
  152. """Generate and return the FuncIR for a given FuncDef.
  153. If the given FuncItem is a nested function, then we generate a
  154. callable class representing the function and use that instead of
  155. the actual function. if the given FuncItem contains a nested
  156. function, then we generate an environment class so that inner
  157. nested functions can access the environment of the given FuncDef.
  158. Consider the following nested function:
  159. def a() -> None:
  160. def b() -> None:
  161. def c() -> None:
  162. return None
  163. return None
  164. return None
  165. The classes generated would look something like the following.
  166. has pointer to +-------+
  167. +--------------------------> | a_env |
  168. | +-------+
  169. | ^
  170. | | has pointer to
  171. +-------+ associated with +-------+
  172. | b_obj | -------------------> | b_env |
  173. +-------+ +-------+
  174. ^
  175. |
  176. +-------+ has pointer to |
  177. | c_obj | --------------------------+
  178. +-------+
  179. """
  180. # TODO: do something about abstract methods.
  181. func_reg: Value | None = None
  182. # We treat lambdas as always being nested because we always generate
  183. # a class for lambdas, no matter where they are. (It would probably also
  184. # work to special case toplevel lambdas and generate a non-class function.)
  185. is_nested = fitem in builder.nested_fitems or isinstance(fitem, LambdaExpr)
  186. contains_nested = fitem in builder.encapsulating_funcs.keys()
  187. is_decorated = fitem in builder.fdefs_to_decorators
  188. is_singledispatch = fitem in builder.singledispatch_impls
  189. in_non_ext = False
  190. class_name = None
  191. if cdef:
  192. ir = builder.mapper.type_to_ir[cdef.info]
  193. in_non_ext = not ir.is_ext_class
  194. class_name = cdef.name
  195. if is_singledispatch:
  196. func_name = singledispatch_main_func_name(name)
  197. else:
  198. func_name = name
  199. builder.enter(
  200. FuncInfo(
  201. fitem,
  202. func_name,
  203. class_name,
  204. gen_func_ns(builder),
  205. is_nested,
  206. contains_nested,
  207. is_decorated,
  208. in_non_ext,
  209. )
  210. )
  211. # Functions that contain nested functions need an environment class to store variables that
  212. # are free in their nested functions. Generator functions need an environment class to
  213. # store a variable denoting the next instruction to be executed when the __next__ function
  214. # is called, along with all the variables inside the function itself.
  215. if builder.fn_info.contains_nested or builder.fn_info.is_generator:
  216. setup_env_class(builder)
  217. if builder.fn_info.is_nested or builder.fn_info.in_non_ext:
  218. setup_callable_class(builder)
  219. if builder.fn_info.is_generator:
  220. # Do a first-pass and generate a function that just returns a generator object.
  221. gen_generator_func(builder)
  222. args, _, blocks, ret_type, fn_info = builder.leave()
  223. func_ir, func_reg = gen_func_ir(
  224. builder, args, blocks, sig, fn_info, cdef, is_singledispatch
  225. )
  226. # Re-enter the FuncItem and visit the body of the function this time.
  227. builder.enter(fn_info)
  228. setup_env_for_generator_class(builder)
  229. load_outer_envs(builder, builder.fn_info.generator_class)
  230. if builder.fn_info.is_nested and isinstance(fitem, FuncDef):
  231. setup_func_for_recursive_call(builder, fitem, builder.fn_info.generator_class)
  232. create_switch_for_generator_class(builder)
  233. add_raise_exception_blocks_to_generator_class(builder, fitem.line)
  234. else:
  235. load_env_registers(builder)
  236. gen_arg_defaults(builder)
  237. if builder.fn_info.contains_nested and not builder.fn_info.is_generator:
  238. finalize_env_class(builder)
  239. builder.ret_types[-1] = sig.ret_type
  240. # Add all variables and functions that are declared/defined within this
  241. # function and are referenced in functions nested within this one to this
  242. # function's environment class so the nested functions can reference
  243. # them even if they are declared after the nested function's definition.
  244. # Note that this is done before visiting the body of this function.
  245. env_for_func: FuncInfo | ImplicitClass = builder.fn_info
  246. if builder.fn_info.is_generator:
  247. env_for_func = builder.fn_info.generator_class
  248. elif builder.fn_info.is_nested or builder.fn_info.in_non_ext:
  249. env_for_func = builder.fn_info.callable_class
  250. if builder.fn_info.fitem in builder.free_variables:
  251. # Sort the variables to keep things deterministic
  252. for var in sorted(builder.free_variables[builder.fn_info.fitem], key=lambda x: x.name):
  253. if isinstance(var, Var):
  254. rtype = builder.type_to_rtype(var.type)
  255. builder.add_var_to_env_class(var, rtype, env_for_func, reassign=False)
  256. if builder.fn_info.fitem in builder.encapsulating_funcs:
  257. for nested_fn in builder.encapsulating_funcs[builder.fn_info.fitem]:
  258. if isinstance(nested_fn, FuncDef):
  259. # The return type is 'object' instead of an RInstance of the
  260. # callable class because differently defined functions with
  261. # the same name and signature across conditional blocks
  262. # will generate different callable classes, so the callable
  263. # class that gets instantiated must be generic.
  264. builder.add_var_to_env_class(
  265. nested_fn, object_rprimitive, env_for_func, reassign=False
  266. )
  267. builder.accept(fitem.body)
  268. builder.maybe_add_implicit_return()
  269. if builder.fn_info.is_generator:
  270. populate_switch_for_generator_class(builder)
  271. # Hang on to the local symbol table for a while, since we use it
  272. # to calculate argument defaults below.
  273. symtable = builder.symtables[-1]
  274. args, _, blocks, ret_type, fn_info = builder.leave()
  275. if fn_info.is_generator:
  276. add_methods_to_generator_class(builder, fn_info, sig, args, blocks, fitem.is_coroutine)
  277. else:
  278. func_ir, func_reg = gen_func_ir(
  279. builder, args, blocks, sig, fn_info, cdef, is_singledispatch
  280. )
  281. # Evaluate argument defaults in the surrounding scope, since we
  282. # calculate them *once* when the function definition is evaluated.
  283. calculate_arg_defaults(builder, fn_info, func_reg, symtable)
  284. if is_singledispatch:
  285. # add the generated main singledispatch function
  286. builder.functions.append(func_ir)
  287. # create the dispatch function
  288. assert isinstance(fitem, FuncDef)
  289. return gen_dispatch_func_ir(builder, fitem, fn_info.name, name, sig)
  290. return func_ir, func_reg
  291. def gen_func_ir(
  292. builder: IRBuilder,
  293. args: list[Register],
  294. blocks: list[BasicBlock],
  295. sig: FuncSignature,
  296. fn_info: FuncInfo,
  297. cdef: ClassDef | None,
  298. is_singledispatch_main_func: bool = False,
  299. ) -> tuple[FuncIR, Value | None]:
  300. """Generate the FuncIR for a function.
  301. This takes the basic blocks and function info of a particular
  302. function and returns the IR. If the function is nested,
  303. also returns the register containing the instance of the
  304. corresponding callable class.
  305. """
  306. func_reg: Value | None = None
  307. if fn_info.is_nested or fn_info.in_non_ext:
  308. func_ir = add_call_to_callable_class(builder, args, blocks, sig, fn_info)
  309. add_get_to_callable_class(builder, fn_info)
  310. func_reg = instantiate_callable_class(builder, fn_info)
  311. else:
  312. assert isinstance(fn_info.fitem, FuncDef)
  313. func_decl = builder.mapper.func_to_decl[fn_info.fitem]
  314. if fn_info.is_decorated or is_singledispatch_main_func:
  315. class_name = None if cdef is None else cdef.name
  316. func_decl = FuncDecl(
  317. fn_info.name,
  318. class_name,
  319. builder.module_name,
  320. sig,
  321. func_decl.kind,
  322. func_decl.is_prop_getter,
  323. func_decl.is_prop_setter,
  324. )
  325. func_ir = FuncIR(
  326. func_decl, args, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name
  327. )
  328. else:
  329. func_ir = FuncIR(
  330. func_decl, args, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name
  331. )
  332. return (func_ir, func_reg)
  333. def handle_ext_method(builder: IRBuilder, cdef: ClassDef, fdef: FuncDef) -> None:
  334. # Perform the function of visit_method for methods inside extension classes.
  335. name = fdef.name
  336. class_ir = builder.mapper.type_to_ir[cdef.info]
  337. func_ir, func_reg = gen_func_item(builder, fdef, name, builder.mapper.fdef_to_sig(fdef), cdef)
  338. builder.functions.append(func_ir)
  339. if is_decorated(builder, fdef):
  340. # Obtain the function name in order to construct the name of the helper function.
  341. _, _, name = fdef.fullname.rpartition(".")
  342. # Read the PyTypeObject representing the class, get the callable object
  343. # representing the non-decorated method
  344. typ = builder.load_native_type_object(cdef.fullname)
  345. orig_func = builder.py_get_attr(typ, name, fdef.line)
  346. # Decorate the non-decorated method
  347. decorated_func = load_decorated_func(builder, fdef, orig_func)
  348. # Set the callable object representing the decorated method as an attribute of the
  349. # extension class.
  350. builder.call_c(py_setattr_op, [typ, builder.load_str(name), decorated_func], fdef.line)
  351. if fdef.is_property:
  352. # If there is a property setter, it will be processed after the getter,
  353. # We populate the optional setter field with none for now.
  354. assert name not in class_ir.properties
  355. class_ir.properties[name] = (func_ir, None)
  356. elif fdef in builder.prop_setters:
  357. # The respective property getter must have been processed already
  358. assert name in class_ir.properties
  359. getter_ir, _ = class_ir.properties[name]
  360. class_ir.properties[name] = (getter_ir, func_ir)
  361. class_ir.methods[func_ir.decl.name] = func_ir
  362. # If this overrides a parent class method with a different type, we need
  363. # to generate a glue method to mediate between them.
  364. for base in class_ir.mro[1:]:
  365. if (
  366. name in base.method_decls
  367. and name != "__init__"
  368. and not is_same_method_signature(
  369. class_ir.method_decls[name].sig, base.method_decls[name].sig
  370. )
  371. ):
  372. # TODO: Support contravariant subtyping in the input argument for
  373. # property setters. Need to make a special glue method for handling this,
  374. # similar to gen_glue_property.
  375. f = gen_glue(builder, base.method_decls[name].sig, func_ir, class_ir, base, fdef)
  376. class_ir.glue_methods[(base, name)] = f
  377. builder.functions.append(f)
  378. # If the class allows interpreted children, create glue
  379. # methods that dispatch via the Python API. These will go in a
  380. # "shadow vtable" that will be assigned to interpreted
  381. # children.
  382. if class_ir.allow_interpreted_subclasses:
  383. f = gen_glue(builder, func_ir.sig, func_ir, class_ir, class_ir, fdef, do_py_ops=True)
  384. class_ir.glue_methods[(class_ir, name)] = f
  385. builder.functions.append(f)
  386. def handle_non_ext_method(
  387. builder: IRBuilder, non_ext: NonExtClassInfo, cdef: ClassDef, fdef: FuncDef
  388. ) -> None:
  389. # Perform the function of visit_method for methods inside non-extension classes.
  390. name = fdef.name
  391. func_ir, func_reg = gen_func_item(builder, fdef, name, builder.mapper.fdef_to_sig(fdef), cdef)
  392. assert func_reg is not None
  393. builder.functions.append(func_ir)
  394. if is_decorated(builder, fdef):
  395. # The undecorated method is a generated callable class
  396. orig_func = func_reg
  397. func_reg = load_decorated_func(builder, fdef, orig_func)
  398. # TODO: Support property setters in non-extension classes
  399. if fdef.is_property:
  400. prop = builder.load_module_attr_by_fullname("builtins.property", fdef.line)
  401. func_reg = builder.py_call(prop, [func_reg], fdef.line)
  402. elif builder.mapper.func_to_decl[fdef].kind == FUNC_CLASSMETHOD:
  403. cls_meth = builder.load_module_attr_by_fullname("builtins.classmethod", fdef.line)
  404. func_reg = builder.py_call(cls_meth, [func_reg], fdef.line)
  405. elif builder.mapper.func_to_decl[fdef].kind == FUNC_STATICMETHOD:
  406. stat_meth = builder.load_module_attr_by_fullname("builtins.staticmethod", fdef.line)
  407. func_reg = builder.py_call(stat_meth, [func_reg], fdef.line)
  408. builder.add_to_non_ext_dict(non_ext, name, func_reg, fdef.line)
  409. def calculate_arg_defaults(
  410. builder: IRBuilder,
  411. fn_info: FuncInfo,
  412. func_reg: Value | None,
  413. symtable: dict[SymbolNode, SymbolTarget],
  414. ) -> None:
  415. """Calculate default argument values and store them.
  416. They are stored in statics for top level functions and in
  417. the function objects for nested functions (while constants are
  418. still stored computed on demand).
  419. """
  420. fitem = fn_info.fitem
  421. for arg in fitem.arguments:
  422. # Constant values don't get stored but just recomputed
  423. if arg.initializer and not is_constant(arg.initializer):
  424. value = builder.coerce(
  425. builder.accept(arg.initializer), symtable[arg.variable].type, arg.line
  426. )
  427. if not fn_info.is_nested:
  428. name = fitem.fullname + "." + arg.variable.name
  429. builder.add(InitStatic(value, name, builder.module_name))
  430. else:
  431. assert func_reg is not None
  432. builder.add(SetAttr(func_reg, arg.variable.name, value, arg.line))
  433. def gen_func_ns(builder: IRBuilder) -> str:
  434. """Generate a namespace for a nested function using its outer function names."""
  435. return "_".join(
  436. info.name + ("" if not info.class_name else "_" + info.class_name)
  437. for info in builder.fn_infos
  438. if info.name and info.name != "<module>"
  439. )
  440. def load_decorated_func(builder: IRBuilder, fdef: FuncDef, orig_func_reg: Value) -> Value:
  441. """Apply decorators to a function.
  442. Given a decorated FuncDef and an instance of the callable class
  443. representing that FuncDef, apply the corresponding decorator
  444. functions on that decorated FuncDef and return the decorated
  445. function.
  446. """
  447. if not is_decorated(builder, fdef):
  448. # If there are no decorators associated with the function, then just return the
  449. # original function.
  450. return orig_func_reg
  451. decorators = builder.fdefs_to_decorators[fdef]
  452. func_reg = orig_func_reg
  453. for d in reversed(decorators):
  454. decorator = d.accept(builder.visitor)
  455. assert isinstance(decorator, Value)
  456. func_reg = builder.py_call(decorator, [func_reg], func_reg.line)
  457. return func_reg
  458. def is_decorated(builder: IRBuilder, fdef: FuncDef) -> bool:
  459. return fdef in builder.fdefs_to_decorators
  460. def gen_glue(
  461. builder: IRBuilder,
  462. base_sig: FuncSignature,
  463. target: FuncIR,
  464. cls: ClassIR,
  465. base: ClassIR,
  466. fdef: FuncItem,
  467. *,
  468. do_py_ops: bool = False,
  469. ) -> FuncIR:
  470. """Generate glue methods that mediate between different method types in subclasses.
  471. Works on both properties and methods. See gen_glue_methods below
  472. for more details.
  473. If do_py_ops is True, then the glue methods should use generic
  474. C API operations instead of direct calls, to enable generating
  475. "shadow" glue methods that work with interpreted subclasses.
  476. """
  477. if fdef.is_property:
  478. return gen_glue_property(builder, base_sig, target, cls, base, fdef.line, do_py_ops)
  479. else:
  480. return gen_glue_method(builder, base_sig, target, cls, base, fdef.line, do_py_ops)
  481. class ArgInfo(NamedTuple):
  482. args: list[Value]
  483. arg_names: list[str | None]
  484. arg_kinds: list[ArgKind]
  485. def get_args(builder: IRBuilder, rt_args: Sequence[RuntimeArg], line: int) -> ArgInfo:
  486. # The environment operates on Vars, so we make some up
  487. fake_vars = [(Var(arg.name), arg.type) for arg in rt_args]
  488. args = [
  489. builder.read(builder.add_local_reg(var, type, is_arg=True), line)
  490. for var, type in fake_vars
  491. ]
  492. arg_names = [
  493. arg.name if arg.kind.is_named() or (arg.kind.is_optional() and not arg.pos_only) else None
  494. for arg in rt_args
  495. ]
  496. arg_kinds = [arg.kind for arg in rt_args]
  497. return ArgInfo(args, arg_names, arg_kinds)
  498. def gen_glue_method(
  499. builder: IRBuilder,
  500. base_sig: FuncSignature,
  501. target: FuncIR,
  502. cls: ClassIR,
  503. base: ClassIR,
  504. line: int,
  505. do_pycall: bool,
  506. ) -> FuncIR:
  507. """Generate glue methods that mediate between different method types in subclasses.
  508. For example, if we have:
  509. class A:
  510. def f(builder: IRBuilder, x: int) -> object: ...
  511. then it is totally permissible to have a subclass
  512. class B(A):
  513. def f(builder: IRBuilder, x: object) -> int: ...
  514. since '(object) -> int' is a subtype of '(int) -> object' by the usual
  515. contra/co-variant function subtyping rules.
  516. The trickiness here is that int and object have different
  517. runtime representations in mypyc, so A.f and B.f have
  518. different signatures at the native C level. To deal with this,
  519. we need to generate glue methods that mediate between the
  520. different versions by coercing the arguments and return
  521. values.
  522. If do_pycall is True, then make the call using the C API
  523. instead of a native call.
  524. """
  525. check_native_override(builder, base_sig, target.decl.sig, line)
  526. builder.enter()
  527. builder.ret_types[-1] = base_sig.ret_type
  528. rt_args = list(base_sig.args)
  529. if target.decl.kind == FUNC_NORMAL:
  530. rt_args[0] = RuntimeArg(base_sig.args[0].name, RInstance(cls))
  531. arg_info = get_args(builder, rt_args, line)
  532. args, arg_kinds, arg_names = arg_info.args, arg_info.arg_kinds, arg_info.arg_names
  533. bitmap_args = None
  534. if base_sig.num_bitmap_args:
  535. args = args[: -base_sig.num_bitmap_args]
  536. arg_kinds = arg_kinds[: -base_sig.num_bitmap_args]
  537. arg_names = arg_names[: -base_sig.num_bitmap_args]
  538. bitmap_args = list(builder.builder.args[-base_sig.num_bitmap_args :])
  539. # We can do a passthrough *args/**kwargs with a native call, but if the
  540. # args need to get distributed out to arguments, we just let python handle it
  541. if any(kind.is_star() for kind in arg_kinds) and any(
  542. not arg.kind.is_star() for arg in target.decl.sig.args
  543. ):
  544. do_pycall = True
  545. if do_pycall:
  546. if target.decl.kind == FUNC_STATICMETHOD:
  547. # FIXME: this won't work if we can do interpreted subclasses
  548. first = builder.builder.get_native_type(cls)
  549. st = 0
  550. else:
  551. first = args[0]
  552. st = 1
  553. retval = builder.builder.py_method_call(
  554. first, target.name, args[st:], line, arg_kinds[st:], arg_names[st:]
  555. )
  556. else:
  557. retval = builder.builder.call(
  558. target.decl, args, arg_kinds, arg_names, line, bitmap_args=bitmap_args
  559. )
  560. retval = builder.coerce(retval, base_sig.ret_type, line)
  561. builder.add(Return(retval))
  562. arg_regs, _, blocks, ret_type, _ = builder.leave()
  563. if base_sig.num_bitmap_args:
  564. rt_args = rt_args[: -base_sig.num_bitmap_args]
  565. return FuncIR(
  566. FuncDecl(
  567. target.name + "__" + base.name + "_glue",
  568. cls.name,
  569. builder.module_name,
  570. FuncSignature(rt_args, ret_type),
  571. target.decl.kind,
  572. ),
  573. arg_regs,
  574. blocks,
  575. )
  576. def check_native_override(
  577. builder: IRBuilder, base_sig: FuncSignature, sub_sig: FuncSignature, line: int
  578. ) -> None:
  579. """Report an error if an override changes signature in unsupported ways.
  580. Glue methods can work around many signature changes but not all of them.
  581. """
  582. for base_arg, sub_arg in zip(base_sig.real_args(), sub_sig.real_args()):
  583. if base_arg.type.error_overlap:
  584. if not base_arg.optional and sub_arg.optional and base_sig.num_bitmap_args:
  585. # This would change the meanings of bits in the argument defaults
  586. # bitmap, which we don't support. We'd need to do tricky bit
  587. # manipulations to support this generally.
  588. builder.error(
  589. "An argument with type "
  590. + f'"{base_arg.type}" cannot be given a default value in a method override',
  591. line,
  592. )
  593. if base_arg.type.error_overlap or sub_arg.type.error_overlap:
  594. if not is_same_type(base_arg.type, sub_arg.type):
  595. # This would change from signaling a default via an error value to
  596. # signaling a default via bitmap, which we don't support.
  597. builder.error(
  598. "Incompatible argument type "
  599. + f'"{sub_arg.type}" (base class has type "{base_arg.type}")',
  600. line,
  601. )
  602. def gen_glue_property(
  603. builder: IRBuilder,
  604. sig: FuncSignature,
  605. target: FuncIR,
  606. cls: ClassIR,
  607. base: ClassIR,
  608. line: int,
  609. do_pygetattr: bool,
  610. ) -> FuncIR:
  611. """Generate glue methods for properties that mediate between different subclass types.
  612. Similarly to methods, properties of derived types can be covariantly subtyped. Thus,
  613. properties also require glue. However, this only requires the return type to change.
  614. Further, instead of a method call, an attribute get is performed.
  615. If do_pygetattr is True, then get the attribute using the Python C
  616. API instead of a native call.
  617. """
  618. builder.enter()
  619. rt_arg = RuntimeArg(SELF_NAME, RInstance(cls))
  620. self_target = builder.add_self_to_env(cls)
  621. arg = builder.read(self_target, line)
  622. builder.ret_types[-1] = sig.ret_type
  623. if do_pygetattr:
  624. retval = builder.py_get_attr(arg, target.name, line)
  625. else:
  626. retval = builder.add(GetAttr(arg, target.name, line))
  627. retbox = builder.coerce(retval, sig.ret_type, line)
  628. builder.add(Return(retbox))
  629. args, _, blocks, return_type, _ = builder.leave()
  630. return FuncIR(
  631. FuncDecl(
  632. target.name + "__" + base.name + "_glue",
  633. cls.name,
  634. builder.module_name,
  635. FuncSignature([rt_arg], return_type),
  636. ),
  637. args,
  638. blocks,
  639. )
  640. def get_func_target(builder: IRBuilder, fdef: FuncDef) -> AssignmentTarget:
  641. """Given a FuncDef, return the target for the instance of its callable class.
  642. If the function was not already defined somewhere, then define it
  643. and add it to the current environment.
  644. """
  645. if fdef.original_def:
  646. # Get the target associated with the previously defined FuncDef.
  647. return builder.lookup(fdef.original_def)
  648. if builder.fn_info.is_generator or builder.fn_info.contains_nested:
  649. return builder.lookup(fdef)
  650. return builder.add_local_reg(fdef, object_rprimitive)
  651. def load_type(builder: IRBuilder, typ: TypeInfo, line: int) -> Value:
  652. if typ in builder.mapper.type_to_ir:
  653. class_ir = builder.mapper.type_to_ir[typ]
  654. class_obj = builder.builder.get_native_type(class_ir)
  655. elif typ.fullname in builtin_names:
  656. builtin_addr_type, src = builtin_names[typ.fullname]
  657. class_obj = builder.add(LoadAddress(builtin_addr_type, src, line))
  658. else:
  659. class_obj = builder.load_global_str(typ.name, line)
  660. return class_obj
  661. def load_func(builder: IRBuilder, func_name: str, fullname: str | None, line: int) -> Value:
  662. if fullname and not fullname.startswith(builder.current_module):
  663. # we're calling a function in a different module
  664. # We can't use load_module_attr_by_fullname here because we need to load the function using
  665. # func_name, not the name specified by fullname (which can be different for underscore
  666. # function)
  667. module = fullname.rsplit(".")[0]
  668. loaded_module = builder.load_module(module)
  669. func = builder.py_get_attr(loaded_module, func_name, line)
  670. else:
  671. func = builder.load_global_str(func_name, line)
  672. return func
  673. def generate_singledispatch_dispatch_function(
  674. builder: IRBuilder, main_singledispatch_function_name: str, fitem: FuncDef
  675. ) -> None:
  676. line = fitem.line
  677. current_func_decl = builder.mapper.func_to_decl[fitem]
  678. arg_info = get_args(builder, current_func_decl.sig.args, line)
  679. dispatch_func_obj = builder.self()
  680. arg_type = builder.builder.get_type_of_obj(arg_info.args[0], line)
  681. dispatch_cache = builder.builder.get_attr(
  682. dispatch_func_obj, "dispatch_cache", dict_rprimitive, line
  683. )
  684. call_find_impl, use_cache, call_func = BasicBlock(), BasicBlock(), BasicBlock()
  685. get_result = builder.call_c(dict_get_method_with_none, [dispatch_cache, arg_type], line)
  686. is_not_none = builder.translate_is_op(get_result, builder.none_object(), "is not", line)
  687. impl_to_use = Register(object_rprimitive)
  688. builder.add_bool_branch(is_not_none, use_cache, call_find_impl)
  689. builder.activate_block(use_cache)
  690. builder.assign(impl_to_use, get_result, line)
  691. builder.goto(call_func)
  692. builder.activate_block(call_find_impl)
  693. find_impl = builder.load_module_attr_by_fullname("functools._find_impl", line)
  694. registry = load_singledispatch_registry(builder, dispatch_func_obj, line)
  695. uncached_impl = builder.py_call(find_impl, [arg_type, registry], line)
  696. builder.call_c(dict_set_item_op, [dispatch_cache, arg_type, uncached_impl], line)
  697. builder.assign(impl_to_use, uncached_impl, line)
  698. builder.goto(call_func)
  699. builder.activate_block(call_func)
  700. gen_calls_to_correct_impl(builder, impl_to_use, arg_info, fitem, line)
  701. def gen_calls_to_correct_impl(
  702. builder: IRBuilder, impl_to_use: Value, arg_info: ArgInfo, fitem: FuncDef, line: int
  703. ) -> None:
  704. current_func_decl = builder.mapper.func_to_decl[fitem]
  705. def gen_native_func_call_and_return(fdef: FuncDef) -> None:
  706. func_decl = builder.mapper.func_to_decl[fdef]
  707. ret_val = builder.builder.call(
  708. func_decl, arg_info.args, arg_info.arg_kinds, arg_info.arg_names, line
  709. )
  710. coerced = builder.coerce(ret_val, current_func_decl.sig.ret_type, line)
  711. builder.add(Return(coerced))
  712. typ, src = builtin_names["builtins.int"]
  713. int_type_obj = builder.add(LoadAddress(typ, src, line))
  714. is_int = builder.builder.type_is_op(impl_to_use, int_type_obj, line)
  715. native_call, non_native_call = BasicBlock(), BasicBlock()
  716. builder.add_bool_branch(is_int, native_call, non_native_call)
  717. builder.activate_block(native_call)
  718. passed_id = builder.add(Unbox(impl_to_use, int_rprimitive, line))
  719. native_ids = get_native_impl_ids(builder, fitem)
  720. for impl, i in native_ids.items():
  721. call_impl, next_impl = BasicBlock(), BasicBlock()
  722. current_id = builder.load_int(i)
  723. builder.builder.compare_tagged_condition(
  724. passed_id, current_id, "==", call_impl, next_impl, line
  725. )
  726. # Call the registered implementation
  727. builder.activate_block(call_impl)
  728. gen_native_func_call_and_return(impl)
  729. builder.activate_block(next_impl)
  730. # We've already handled all the possible integer IDs, so we should never get here
  731. builder.add(Unreachable())
  732. builder.activate_block(non_native_call)
  733. ret_val = builder.py_call(
  734. impl_to_use, arg_info.args, line, arg_info.arg_kinds, arg_info.arg_names
  735. )
  736. coerced = builder.coerce(ret_val, current_func_decl.sig.ret_type, line)
  737. builder.add(Return(coerced))
  738. def gen_dispatch_func_ir(
  739. builder: IRBuilder, fitem: FuncDef, main_func_name: str, dispatch_name: str, sig: FuncSignature
  740. ) -> tuple[FuncIR, Value]:
  741. """Create a dispatch function (a function that checks the first argument type and dispatches
  742. to the correct implementation)
  743. """
  744. builder.enter(FuncInfo(fitem, dispatch_name))
  745. setup_callable_class(builder)
  746. builder.fn_info.callable_class.ir.attributes["registry"] = dict_rprimitive
  747. builder.fn_info.callable_class.ir.attributes["dispatch_cache"] = dict_rprimitive
  748. builder.fn_info.callable_class.ir.has_dict = True
  749. builder.fn_info.callable_class.ir.needs_getseters = True
  750. generate_singledispatch_callable_class_ctor(builder)
  751. generate_singledispatch_dispatch_function(builder, main_func_name, fitem)
  752. args, _, blocks, _, fn_info = builder.leave()
  753. dispatch_callable_class = add_call_to_callable_class(builder, args, blocks, sig, fn_info)
  754. builder.functions.append(dispatch_callable_class)
  755. add_get_to_callable_class(builder, fn_info)
  756. add_register_method_to_callable_class(builder, fn_info)
  757. func_reg = instantiate_callable_class(builder, fn_info)
  758. dispatch_func_ir = generate_dispatch_glue_native_function(
  759. builder, fitem, dispatch_callable_class.decl, dispatch_name
  760. )
  761. return dispatch_func_ir, func_reg
  762. def generate_dispatch_glue_native_function(
  763. builder: IRBuilder, fitem: FuncDef, callable_class_decl: FuncDecl, dispatch_name: str
  764. ) -> FuncIR:
  765. line = fitem.line
  766. builder.enter()
  767. # We store the callable class in the globals dict for this function
  768. callable_class = builder.load_global_str(dispatch_name, line)
  769. decl = builder.mapper.func_to_decl[fitem]
  770. arg_info = get_args(builder, decl.sig.args, line)
  771. args = [callable_class] + arg_info.args
  772. arg_kinds = [ArgKind.ARG_POS] + arg_info.arg_kinds
  773. arg_names = arg_info.arg_names
  774. arg_names.insert(0, "self")
  775. ret_val = builder.builder.call(callable_class_decl, args, arg_kinds, arg_names, line)
  776. builder.add(Return(ret_val))
  777. arg_regs, _, blocks, _, fn_info = builder.leave()
  778. return FuncIR(decl, arg_regs, blocks)
  779. def generate_singledispatch_callable_class_ctor(builder: IRBuilder) -> None:
  780. """Create an __init__ that sets registry and dispatch_cache to empty dicts"""
  781. line = -1
  782. class_ir = builder.fn_info.callable_class.ir
  783. with builder.enter_method(class_ir, "__init__", bool_rprimitive):
  784. empty_dict = builder.call_c(dict_new_op, [], line)
  785. builder.add(SetAttr(builder.self(), "registry", empty_dict, line))
  786. cache_dict = builder.call_c(dict_new_op, [], line)
  787. dispatch_cache_str = builder.load_str("dispatch_cache")
  788. # use the py_setattr_op instead of SetAttr so that it also gets added to our __dict__
  789. builder.call_c(py_setattr_op, [builder.self(), dispatch_cache_str, cache_dict], line)
  790. # the generated C code seems to expect that __init__ returns a char, so just return 1
  791. builder.add(Return(Integer(1, bool_rprimitive, line), line))
  792. def add_register_method_to_callable_class(builder: IRBuilder, fn_info: FuncInfo) -> None:
  793. line = -1
  794. with builder.enter_method(fn_info.callable_class.ir, "register", object_rprimitive):
  795. cls_arg = builder.add_argument("cls", object_rprimitive)
  796. func_arg = builder.add_argument("func", object_rprimitive, ArgKind.ARG_OPT)
  797. ret_val = builder.call_c(register_function, [builder.self(), cls_arg, func_arg], line)
  798. builder.add(Return(ret_val, line))
  799. def load_singledispatch_registry(builder: IRBuilder, dispatch_func_obj: Value, line: int) -> Value:
  800. return builder.builder.get_attr(dispatch_func_obj, "registry", dict_rprimitive, line)
  801. def singledispatch_main_func_name(orig_name: str) -> str:
  802. return f"__mypyc_singledispatch_main_function_{orig_name}__"
  803. def get_registry_identifier(fitem: FuncDef) -> str:
  804. return f"__mypyc_singledispatch_registry_{fitem.fullname}__"
  805. def maybe_insert_into_registry_dict(builder: IRBuilder, fitem: FuncDef) -> None:
  806. line = fitem.line
  807. is_singledispatch_main_func = fitem in builder.singledispatch_impls
  808. # dict of singledispatch_func to list of register_types (fitem is the function to register)
  809. to_register: defaultdict[FuncDef, list[TypeInfo]] = defaultdict(list)
  810. for main_func, impls in builder.singledispatch_impls.items():
  811. for dispatch_type, impl in impls:
  812. if fitem == impl:
  813. to_register[main_func].append(dispatch_type)
  814. if not to_register and not is_singledispatch_main_func:
  815. return
  816. if is_singledispatch_main_func:
  817. main_func_name = singledispatch_main_func_name(fitem.name)
  818. main_func_obj = load_func(builder, main_func_name, fitem.fullname, line)
  819. loaded_object_type = builder.load_module_attr_by_fullname("builtins.object", line)
  820. registry_dict = builder.builder.make_dict([(loaded_object_type, main_func_obj)], line)
  821. dispatch_func_obj = builder.load_global_str(fitem.name, line)
  822. builder.call_c(
  823. py_setattr_op, [dispatch_func_obj, builder.load_str("registry"), registry_dict], line
  824. )
  825. for singledispatch_func, types in to_register.items():
  826. # TODO: avoid recomputing the native IDs for all the functions every time we find a new
  827. # function
  828. native_ids = get_native_impl_ids(builder, singledispatch_func)
  829. if fitem not in native_ids:
  830. to_insert = load_func(builder, fitem.name, fitem.fullname, line)
  831. else:
  832. current_id = native_ids[fitem]
  833. load_literal = LoadLiteral(current_id, object_rprimitive)
  834. to_insert = builder.add(load_literal)
  835. # TODO: avoid reloading the registry here if we just created it
  836. dispatch_func_obj = load_func(
  837. builder, singledispatch_func.name, singledispatch_func.fullname, line
  838. )
  839. registry = load_singledispatch_registry(builder, dispatch_func_obj, line)
  840. for typ in types:
  841. loaded_type = load_type(builder, typ, line)
  842. builder.call_c(dict_set_item_op, [registry, loaded_type, to_insert], line)
  843. dispatch_cache = builder.builder.get_attr(
  844. dispatch_func_obj, "dispatch_cache", dict_rprimitive, line
  845. )
  846. builder.gen_method_call(dispatch_cache, "clear", [], None, line)
  847. def get_native_impl_ids(builder: IRBuilder, singledispatch_func: FuncDef) -> dict[FuncDef, int]:
  848. """Return a dict of registered implementation to native implementation ID for all
  849. implementations
  850. """
  851. impls = builder.singledispatch_impls[singledispatch_func]
  852. return {impl: i for i, (typ, impl) in enumerate(impls) if not is_decorated(builder, impl)}
  853. def gen_property_getter_ir(
  854. builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool
  855. ) -> FuncIR:
  856. """Generate an implicit trivial property getter for an attribute.
  857. These are used if an attribute can also be accessed as a property.
  858. """
  859. name = func_decl.name
  860. builder.enter(name)
  861. self_reg = builder.add_argument("self", func_decl.sig.args[0].type)
  862. if not is_trait:
  863. value = builder.builder.get_attr(self_reg, name, func_decl.sig.ret_type, -1)
  864. builder.add(Return(value))
  865. else:
  866. builder.add(Unreachable())
  867. args, _, blocks, ret_type, fn_info = builder.leave()
  868. return FuncIR(func_decl, args, blocks)
  869. def gen_property_setter_ir(
  870. builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool
  871. ) -> FuncIR:
  872. """Generate an implicit trivial property setter for an attribute.
  873. These are used if an attribute can also be accessed as a property.
  874. """
  875. name = func_decl.name
  876. builder.enter(name)
  877. self_reg = builder.add_argument("self", func_decl.sig.args[0].type)
  878. value_reg = builder.add_argument("value", func_decl.sig.args[1].type)
  879. assert name.startswith(PROPSET_PREFIX)
  880. attr_name = name[len(PROPSET_PREFIX) :]
  881. if not is_trait:
  882. builder.add(SetAttr(self_reg, attr_name, value_reg, -1))
  883. builder.add(Return(builder.none()))
  884. args, _, blocks, ret_type, fn_info = builder.leave()
  885. return FuncIR(func_decl, args, blocks)