| 1 |
"""Transform mypy AST functions to IR (and related things). |
| 2 |
|
| 3 |
Normal functions are translated into a list of basic blocks |
| 4 |
containing various IR ops (defined in mypyc.ir.ops). |
| 5 |
|
| 6 |
This also deals with generators, async functions and nested |
| 7 |
functions. All of these are transformed into callable classes. These |
| 8 |
have a custom __call__ method that implements the call, and state, such |
| 9 |
as an environment containing non-local variables, is stored in the |
| 10 |
instance of the callable class. |
| 11 |
""" |
| 12 |
|
| 13 |
from __future__ import annotations |
| 14 |
|
| 15 |
from collections import defaultdict |
| 16 |
from collections.abc import Sequence |
| 17 |
from typing import NamedTuple |
| 18 |
|
| 19 |
from mypy.nodes import ( |
| 20 |
ArgKind, |
| 21 |
ClassDef, |
| 22 |
Decorator, |
| 23 |
FuncBase, |
| 24 |
FuncDef, |
| 25 |
FuncItem, |
| 26 |
LambdaExpr, |
| 27 |
OverloadedFuncDef, |
| 28 |
TypeInfo, |
| 29 |
Var, |
| 30 |
) |
| 31 |
from mypy.types import CallableType, Type, UnboundType, get_proper_type |
| 32 |
from mypyc.common import FAST_PREFIX, LAMBDA_NAME, PROPSET_PREFIX, SELF_NAME |
| 33 |
from mypyc.ir.class_ir import ClassIR, NonExtClassInfo |
| 34 |
from mypyc.ir.func_ir import ( |
| 35 |
FUNC_CLASSMETHOD, |
| 36 |
FUNC_NORMAL, |
| 37 |
FUNC_STATICMETHOD, |
| 38 |
FuncDecl, |
| 39 |
FuncIR, |
| 40 |
FuncSignature, |
| 41 |
RuntimeArg, |
| 42 |
) |
| 43 |
from mypyc.ir.ops import ( |
| 44 |
BasicBlock, |
| 45 |
ComparisonOp, |
| 46 |
GetAttr, |
| 47 |
Integer, |
| 48 |
LoadLiteral, |
| 49 |
Register, |
| 50 |
Return, |
| 51 |
SetAttr, |
| 52 |
Unbox, |
| 53 |
Unreachable, |
| 54 |
Value, |
| 55 |
) |
| 56 |
from mypyc.ir.rtypes import ( |
| 57 |
RInstance, |
| 58 |
bool_rprimitive, |
| 59 |
c_int_rprimitive, |
| 60 |
dict_rprimitive, |
| 61 |
int_rprimitive, |
| 62 |
object_rprimitive, |
| 63 |
) |
| 64 |
from mypyc.irbuild.builder import IRBuilder, calculate_arg_defaults, gen_arg_defaults |
| 65 |
from mypyc.irbuild.callable_class import ( |
| 66 |
add_call_to_callable_class, |
| 67 |
add_get_to_callable_class, |
| 68 |
instantiate_callable_class, |
| 69 |
setup_callable_class, |
| 70 |
) |
| 71 |
from mypyc.irbuild.context import FuncInfo, GeneratorClass |
| 72 |
from mypyc.irbuild.env_class import ( |
| 73 |
add_vars_to_env, |
| 74 |
finalize_env_class, |
| 75 |
load_env_registers, |
| 76 |
setup_env_class, |
| 77 |
) |
| 78 |
from mypyc.irbuild.generator import gen_generator_func, gen_generator_func_body |
| 79 |
from mypyc.irbuild.targets import AssignmentTarget |
| 80 |
from mypyc.primitives.dict_ops import ( |
| 81 |
dict_get_method_with_none, |
| 82 |
dict_new_op, |
| 83 |
exact_dict_set_item_op, |
| 84 |
) |
| 85 |
from mypyc.primitives.generic_ops import generic_getattr, generic_setattr, py_setattr_op |
| 86 |
from mypyc.primitives.misc_ops import register_function |
| 87 |
from mypyc.sametype import is_same_method_signature, is_same_type |
| 88 |
|
| 89 |
# Top-level transform functions |
| 90 |
|
| 91 |
|
| 92 |
def transform_func_def(builder: IRBuilder, fdef: FuncDef) -> None: |
| 93 |
sig = builder.mapper.fdef_to_sig(fdef, builder.options.strict_dunders_typing) |
| 94 |
func_ir, func_reg = gen_func_item(builder, fdef, fdef.name, sig) |
| 95 |
|
| 96 |
# If the function that was visited was a nested function, then either look it up in our |
| 97 |
# current environment or define it if it was not already defined. |
| 98 |
if func_reg: |
| 99 |
builder.assign(get_func_target(builder, fdef), func_reg, fdef.line) |
| 100 |
maybe_insert_into_registry_dict(builder, fdef) |
| 101 |
builder.add_function(func_ir, fdef.line) |
| 102 |
|
| 103 |
|
| 104 |
def transform_overloaded_func_def(builder: IRBuilder, o: OverloadedFuncDef) -> None: |
| 105 |
# Handle regular overload case |
| 106 |
assert o.impl |
| 107 |
builder.accept(o.impl) |
| 108 |
|
| 109 |
|
| 110 |
def transform_decorator(builder: IRBuilder, dec: Decorator) -> None: |
| 111 |
sig = builder.mapper.fdef_to_sig(dec.func, builder.options.strict_dunders_typing) |
| 112 |
func_ir, func_reg = gen_func_item(builder, dec.func, dec.func.name, sig) |
| 113 |
decorated_func: Value | None = None |
| 114 |
if func_reg: |
| 115 |
decorated_func = load_decorated_func(builder, dec.func, func_reg) |
| 116 |
builder.assign(get_func_target(builder, dec.func), decorated_func, dec.func.line) |
| 117 |
# If the prebuild pass didn't put this function in the function to decorators map (for example |
| 118 |
# if this is a registered singledispatch implementation with no other decorators), we should |
| 119 |
# treat this function as a regular function, not a decorated function |
| 120 |
elif dec.func in builder.fdefs_to_decorators: |
| 121 |
# Obtain the function name in order to construct the name of the helper function. |
| 122 |
name = dec.func.fullname.split(".")[-1] |
| 123 |
|
| 124 |
# Load the callable object representing the non-decorated function, and decorate it. |
| 125 |
orig_func = builder.load_global_str(name, dec.line) |
| 126 |
decorated_func = load_decorated_func(builder, dec.func, orig_func) |
| 127 |
|
| 128 |
if decorated_func is not None: |
| 129 |
# Set the callable object representing the decorated function as a global. |
| 130 |
builder.call_c( |
| 131 |
exact_dict_set_item_op, |
| 132 |
[builder.load_globals_dict(), builder.load_str(dec.func.name), decorated_func], |
| 133 |
decorated_func.line, |
| 134 |
) |
| 135 |
|
| 136 |
maybe_insert_into_registry_dict(builder, dec.func) |
| 137 |
|
| 138 |
builder.functions.append(func_ir) |
| 139 |
|
| 140 |
|
| 141 |
def transform_lambda_expr(builder: IRBuilder, expr: LambdaExpr) -> Value: |
| 142 |
typ = get_proper_type(builder.types[expr]) |
| 143 |
assert isinstance(typ, CallableType), typ |
| 144 |
|
| 145 |
runtime_args = [] |
| 146 |
for arg, arg_type in zip(expr.arguments, typ.arg_types): |
| 147 |
arg.variable.type = arg_type |
| 148 |
runtime_args.append( |
| 149 |
RuntimeArg(arg.variable.name, builder.type_to_rtype(arg_type), arg.kind) |
| 150 |
) |
| 151 |
ret_type = builder.type_to_rtype(typ.ret_type) |
| 152 |
|
| 153 |
fsig = FuncSignature(runtime_args, ret_type) |
| 154 |
|
| 155 |
fname = f"{LAMBDA_NAME}{builder.lambda_counter}" |
| 156 |
builder.lambda_counter += 1 |
| 157 |
func_ir, func_reg = gen_func_item(builder, expr, fname, fsig) |
| 158 |
assert func_reg is not None |
| 159 |
|
| 160 |
builder.functions.append(func_ir) |
| 161 |
return func_reg |
| 162 |
|
| 163 |
|
| 164 |
# Internal functions |
| 165 |
|
| 166 |
|
| 167 |
def gen_func_item( |
| 168 |
builder: IRBuilder, |
| 169 |
fitem: FuncItem, |
| 170 |
name: str, |
| 171 |
sig: FuncSignature, |
| 172 |
cdef: ClassDef | None = None, |
| 173 |
make_ext_method: bool = False, |
| 174 |
) -> tuple[FuncIR, Value | None]: |
| 175 |
"""Generate and return the FuncIR for a given FuncDef. |
| 176 |
|
| 177 |
If the given FuncItem is a nested function, then we generate a |
| 178 |
callable class representing the function and use that instead of |
| 179 |
the actual function. if the given FuncItem contains a nested |
| 180 |
function, then we generate an environment class so that inner |
| 181 |
nested functions can access the environment of the given FuncDef. |
| 182 |
|
| 183 |
Consider the following nested function: |
| 184 |
|
| 185 |
def a() -> None: |
| 186 |
def b() -> None: |
| 187 |
def c() -> None: |
| 188 |
return None |
| 189 |
return None |
| 190 |
return None |
| 191 |
|
| 192 |
The classes generated would look something like the following. |
| 193 |
|
| 194 |
has pointer to +-------+ |
| 195 |
+--------------------------> | a_env | |
| 196 |
| +-------+ |
| 197 |
| ^ |
| 198 |
| | has pointer to |
| 199 |
+-------+ associated with +-------+ |
| 200 |
| b_obj | -------------------> | b_env | |
| 201 |
+-------+ +-------+ |
| 202 |
^ |
| 203 |
| |
| 204 |
+-------+ has pointer to | |
| 205 |
| c_obj | --------------------------+ |
| 206 |
+-------+ |
| 207 |
""" |
| 208 |
|
| 209 |
# TODO: do something about abstract methods. |
| 210 |
|
| 211 |
func_reg: Value | None = None |
| 212 |
|
| 213 |
# We treat lambdas as always being nested because we always generate |
| 214 |
# a class for lambdas, no matter where they are. (It would probably also |
| 215 |
# work to special case toplevel lambdas and generate a non-class function.) |
| 216 |
is_nested = fitem in builder.nested_fitems or isinstance(fitem, LambdaExpr) |
| 217 |
contains_nested = fitem in builder.encapsulating_funcs.keys() |
| 218 |
is_decorated = fitem in builder.fdefs_to_decorators |
| 219 |
is_singledispatch = fitem in builder.singledispatch_impls |
| 220 |
in_non_ext = False |
| 221 |
add_nested_funcs_to_env = has_nested_func_self_reference(builder, fitem) |
| 222 |
class_name = None |
| 223 |
if cdef: |
| 224 |
ir = builder.mapper.type_to_ir[cdef.info] |
| 225 |
in_non_ext = not ir.is_ext_class and not make_ext_method |
| 226 |
class_name = cdef.name |
| 227 |
|
| 228 |
if is_singledispatch: |
| 229 |
func_name = singledispatch_main_func_name(name) |
| 230 |
else: |
| 231 |
func_name = name |
| 232 |
|
| 233 |
fn_info = FuncInfo( |
| 234 |
fitem=fitem, |
| 235 |
name=func_name, |
| 236 |
class_name=class_name, |
| 237 |
namespace=gen_func_ns(builder), |
| 238 |
is_nested=is_nested, |
| 239 |
contains_nested=contains_nested, |
| 240 |
is_decorated=is_decorated, |
| 241 |
in_non_ext=in_non_ext, |
| 242 |
add_nested_funcs_to_env=add_nested_funcs_to_env, |
| 243 |
) |
| 244 |
is_generator = fn_info.is_generator |
| 245 |
builder.enter(fn_info, ret_type=sig.ret_type) |
| 246 |
|
| 247 |
if is_generator: |
| 248 |
fitem = builder.fn_info.fitem |
| 249 |
assert isinstance(fitem, FuncDef), fitem |
| 250 |
generator_class_ir = builder.mapper.fdef_to_generator[fitem] |
| 251 |
builder.fn_info.generator_class = GeneratorClass(generator_class_ir) |
| 252 |
|
| 253 |
# Functions that contain nested functions need an environment class to store variables that |
| 254 |
# are free in their nested functions. Generator functions need an environment class to |
| 255 |
# store a variable denoting the next instruction to be executed when the __next__ function |
| 256 |
# is called, along with all the variables inside the function itself. |
| 257 |
if contains_nested or ( |
| 258 |
is_generator and not builder.fn_info.can_merge_generator_and_env_classes() |
| 259 |
): |
| 260 |
setup_env_class(builder) |
| 261 |
|
| 262 |
if is_nested or in_non_ext: |
| 263 |
setup_callable_class(builder) |
| 264 |
|
| 265 |
if is_generator: |
| 266 |
# First generate a function that just constructs and returns a generator object. |
| 267 |
func_ir, func_reg = gen_generator_func( |
| 268 |
builder, |
| 269 |
lambda args, blocks, fn_info: gen_func_ir( |
| 270 |
builder, args, blocks, sig, fn_info, cdef, is_singledispatch |
| 271 |
), |
| 272 |
) |
| 273 |
|
| 274 |
# Re-enter the FuncItem and visit the body of the function this time. |
| 275 |
gen_generator_func_body(builder, fn_info, func_reg) |
| 276 |
else: |
| 277 |
func_ir, func_reg = gen_func_body(builder, sig, cdef, is_singledispatch) |
| 278 |
|
| 279 |
if is_singledispatch: |
| 280 |
# add the generated main singledispatch function |
| 281 |
builder.functions.append(func_ir) |
| 282 |
# create the dispatch function |
| 283 |
assert isinstance(fitem, FuncDef), fitem |
| 284 |
return gen_dispatch_func_ir(builder, fitem, fn_info.name, name, sig) |
| 285 |
|
| 286 |
return func_ir, func_reg |
| 287 |
|
| 288 |
|
| 289 |
def gen_func_body( |
| 290 |
builder: IRBuilder, sig: FuncSignature, cdef: ClassDef | None, is_singledispatch: bool |
| 291 |
) -> tuple[FuncIR, Value | None]: |
| 292 |
load_env_registers(builder) |
| 293 |
gen_arg_defaults(builder) |
| 294 |
if builder.fn_info.contains_nested: |
| 295 |
finalize_env_class(builder) |
| 296 |
add_vars_to_env(builder) |
| 297 |
builder.accept(builder.fn_info.fitem.body) |
| 298 |
builder.maybe_add_implicit_return() |
| 299 |
|
| 300 |
# Hang on to the local symbol table for a while, since we use it |
| 301 |
# to calculate argument defaults below. |
| 302 |
symtable = builder.symtables[-1] |
| 303 |
|
| 304 |
args, _, blocks, ret_type, fn_info = builder.leave() |
| 305 |
|
| 306 |
func_ir, func_reg = gen_func_ir(builder, args, blocks, sig, fn_info, cdef, is_singledispatch) |
| 307 |
|
| 308 |
# Evaluate argument defaults in the surrounding scope, since we |
| 309 |
# calculate them *once* when the function definition is evaluated. |
| 310 |
calculate_arg_defaults(builder, fn_info, func_reg, symtable) |
| 311 |
return func_ir, func_reg |
| 312 |
|
| 313 |
|
| 314 |
def has_nested_func_self_reference(builder: IRBuilder, fitem: FuncItem) -> bool: |
| 315 |
"""Does a nested function contain a self-reference in its body? |
| 316 |
|
| 317 |
If a nested function only has references in the surrounding function, |
| 318 |
we don't need to add it to the environment. |
| 319 |
""" |
| 320 |
if any(isinstance(sym, FuncBase) for sym in builder.free_variables.get(fitem, set())): |
| 321 |
return True |
| 322 |
return any( |
| 323 |
has_nested_func_self_reference(builder, nested) |
| 324 |
for nested in builder.encapsulating_funcs.get(fitem, []) |
| 325 |
) |
| 326 |
|
| 327 |
|
| 328 |
def gen_func_ir( |
| 329 |
builder: IRBuilder, |
| 330 |
args: list[Register], |
| 331 |
blocks: list[BasicBlock], |
| 332 |
sig: FuncSignature, |
| 333 |
fn_info: FuncInfo, |
| 334 |
cdef: ClassDef | None, |
| 335 |
is_singledispatch_main_func: bool = False, |
| 336 |
) -> tuple[FuncIR, Value | None]: |
| 337 |
"""Generate the FuncIR for a function. |
| 338 |
|
| 339 |
This takes the basic blocks and function info of a particular |
| 340 |
function and returns the IR. If the function is nested, |
| 341 |
also returns the register containing the instance of the |
| 342 |
corresponding callable class. |
| 343 |
""" |
| 344 |
func_reg: Value | None = None |
| 345 |
if fn_info.is_nested or fn_info.in_non_ext: |
| 346 |
func_ir = add_call_to_callable_class(builder, args, blocks, sig, fn_info) |
| 347 |
add_get_to_callable_class(builder, fn_info) |
| 348 |
func_reg = instantiate_callable_class(builder, fn_info) |
| 349 |
else: |
| 350 |
fitem = fn_info.fitem |
| 351 |
assert isinstance(fitem, FuncDef), fitem |
| 352 |
func_decl = builder.mapper.func_to_decl[fitem] |
| 353 |
if cdef and fn_info.name == FAST_PREFIX + func_decl.name: |
| 354 |
# Special-cased version of a method has a separate FuncDecl, use that one. |
| 355 |
func_decl = builder.mapper.type_to_ir[cdef.info].method_decls[fn_info.name] |
| 356 |
if fn_info.is_decorated or is_singledispatch_main_func: |
| 357 |
class_name = None if cdef is None else cdef.name |
| 358 |
func_decl = FuncDecl( |
| 359 |
fn_info.name, |
| 360 |
class_name, |
| 361 |
builder.module_name, |
| 362 |
sig, |
| 363 |
func_decl.kind, |
| 364 |
is_prop_getter=func_decl.is_prop_getter, |
| 365 |
is_prop_setter=func_decl.is_prop_setter, |
| 366 |
is_generator=func_decl.is_generator, |
| 367 |
is_coroutine=func_decl.is_coroutine, |
| 368 |
implicit=func_decl.implicit, |
| 369 |
internal=func_decl.internal, |
| 370 |
) |
| 371 |
func_ir = FuncIR(func_decl, args, blocks, fitem.line, traceback_name=fitem.name) |
| 372 |
else: |
| 373 |
func_ir = FuncIR(func_decl, args, blocks, fitem.line, traceback_name=fitem.name) |
| 374 |
return (func_ir, func_reg) |
| 375 |
|
| 376 |
|
| 377 |
def generate_getattr_wrapper(builder: IRBuilder, cdef: ClassDef, getattr: FuncDef) -> None: |
| 378 |
""" |
| 379 |
Generate a wrapper function for __getattr__ that can be put into the tp_getattro slot. |
| 380 |
The wrapper takes one argument besides self which is the attribute name. |
| 381 |
It first checks if the name matches any of the attributes of this class. |
| 382 |
If it does, it returns that attribute. If none match, it calls __getattr__. |
| 383 |
|
| 384 |
__getattr__ is not supported in classes that allow interpreted subclasses because the |
| 385 |
tp_getattro slot is inherited by subclasses and if the subclass overrides __getattr__, |
| 386 |
the override would be ignored in our wrapper. TODO: To support this, the wrapper would |
| 387 |
have to check type of self and if it's not the compiled class, resolve "__getattr__" against |
| 388 |
the type at runtime and call the returned method, like _Py_slot_tp_getattr_hook in cpython. |
| 389 |
|
| 390 |
__getattr__ is not supported in classes which inherit from non-native classes because those |
| 391 |
have __dict__ which currently has some strange interactions when class attributes and |
| 392 |
variables are assigned through __dict__ vs. through regular attribute access. Allowing |
| 393 |
__getattr__ on top of that could be problematic. |
| 394 |
""" |
| 395 |
name = getattr.name + "__wrapper" |
| 396 |
ir = builder.mapper.type_to_ir[cdef.info] |
| 397 |
line = getattr.line |
| 398 |
|
| 399 |
error_base = f'"__getattr__" not supported in class "{cdef.name}" because ' |
| 400 |
if ir.allow_interpreted_subclasses: |
| 401 |
builder.error(error_base + "it allows interpreted subclasses", line) |
| 402 |
if ir.inherits_python: |
| 403 |
builder.error(error_base + "it inherits from a non-native class", line) |
| 404 |
|
| 405 |
with builder.enter_method(ir, name, object_rprimitive, internal=True): |
| 406 |
attr_arg = builder.add_argument("attr", object_rprimitive) |
| 407 |
generic_getattr_result = builder.call_c(generic_getattr, [builder.self(), attr_arg], line) |
| 408 |
|
| 409 |
return_generic, call_getattr = BasicBlock(), BasicBlock() |
| 410 |
null = Integer(0, object_rprimitive, line) |
| 411 |
got_generic = builder.add( |
| 412 |
ComparisonOp(generic_getattr_result, null, ComparisonOp.NEQ, line) |
| 413 |
) |
| 414 |
builder.add_bool_branch(got_generic, return_generic, call_getattr) |
| 415 |
|
| 416 |
builder.activate_block(return_generic) |
| 417 |
builder.add(Return(generic_getattr_result, line)) |
| 418 |
|
| 419 |
builder.activate_block(call_getattr) |
| 420 |
# No attribute matched so call user-provided __getattr__. |
| 421 |
getattr_result = builder.gen_method_call( |
| 422 |
builder.self(), getattr.name, [attr_arg], object_rprimitive, line |
| 423 |
) |
| 424 |
builder.add(Return(getattr_result, line)) |
| 425 |
|
| 426 |
|
| 427 |
def generate_setattr_wrapper(builder: IRBuilder, cdef: ClassDef, setattr: FuncDef) -> None: |
| 428 |
""" |
| 429 |
Generate a wrapper function for __setattr__ that can be put into the tp_setattro slot. |
| 430 |
The wrapper takes two arguments besides self - attribute name and the new value. |
| 431 |
Returns 0 on success and -1 on failure. Restrictions are similar to the __getattr__ |
| 432 |
wrapper above. |
| 433 |
|
| 434 |
The wrapper calls the user-defined __setattr__ when the value to set is not NULL. |
| 435 |
When it's NULL, this means that the call to tp_setattro comes from a del statement, |
| 436 |
so it calls __delattr__ instead. If __delattr__ is not overridden in the native class, |
| 437 |
this will call the base implementation in object which doesn't work without __dict__. |
| 438 |
""" |
| 439 |
name = setattr.name + "__wrapper" |
| 440 |
ir = builder.mapper.type_to_ir[cdef.info] |
| 441 |
line = setattr.line |
| 442 |
|
| 443 |
error_base = f'"__setattr__" not supported in class "{cdef.name}" because ' |
| 444 |
if ir.allow_interpreted_subclasses: |
| 445 |
builder.error(error_base + "it allows interpreted subclasses", line) |
| 446 |
if ir.inherits_python: |
| 447 |
builder.error(error_base + "it inherits from a non-native class", line) |
| 448 |
|
| 449 |
with builder.enter_method(ir, name, c_int_rprimitive, internal=True): |
| 450 |
attr_arg = builder.add_argument("attr", object_rprimitive) |
| 451 |
value_arg = builder.add_argument("value", object_rprimitive) |
| 452 |
|
| 453 |
call_delattr, call_setattr = BasicBlock(), BasicBlock() |
| 454 |
null = Integer(0, object_rprimitive, line) |
| 455 |
is_delattr = builder.add(ComparisonOp(value_arg, null, ComparisonOp.EQ, line)) |
| 456 |
builder.add_bool_branch(is_delattr, call_delattr, call_setattr) |
| 457 |
|
| 458 |
builder.activate_block(call_delattr) |
| 459 |
delattr_symbol = cdef.info.get("__delattr__") |
| 460 |
delattr = delattr_symbol.node if delattr_symbol else None |
| 461 |
delattr_override = delattr is not None and not delattr.fullname.startswith("builtins.") |
| 462 |
if delattr_override: |
| 463 |
builder.gen_method_call(builder.self(), "__delattr__", [attr_arg], None, line) |
| 464 |
else: |
| 465 |
# Call internal function that cpython normally calls when deleting an attribute. |
| 466 |
# Cannot call object.__delattr__ here because it calls PyObject_SetAttr internally |
| 467 |
# which in turn calls our wrapper and recurses infinitely. |
| 468 |
# Note that since native classes don't have __dict__, this will raise AttributeError |
| 469 |
# for dynamic attributes. |
| 470 |
builder.call_c(generic_setattr, [builder.self(), attr_arg, null], line) |
| 471 |
builder.add(Return(Integer(0, c_int_rprimitive), line)) |
| 472 |
|
| 473 |
builder.activate_block(call_setattr) |
| 474 |
builder.gen_method_call(builder.self(), setattr.name, [attr_arg, value_arg], None, line) |
| 475 |
builder.add(Return(Integer(0, c_int_rprimitive), line)) |
| 476 |
|
| 477 |
|
| 478 |
def handle_ext_method(builder: IRBuilder, cdef: ClassDef, fdef: FuncDef) -> None: |
| 479 |
# Perform the function of visit_method for methods inside extension classes. |
| 480 |
name = fdef.name |
| 481 |
class_ir = builder.mapper.type_to_ir[cdef.info] |
| 482 |
sig = builder.mapper.fdef_to_sig(fdef, builder.options.strict_dunders_typing) |
| 483 |
func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef) |
| 484 |
builder.functions.append(func_ir) |
| 485 |
|
| 486 |
if is_decorated(builder, fdef): |
| 487 |
# Obtain the function name in order to construct the name of the helper function. |
| 488 |
_, _, name = fdef.fullname.rpartition(".") |
| 489 |
# Read the PyTypeObject representing the class, get the callable object |
| 490 |
# representing the non-decorated method |
| 491 |
typ = builder.load_native_type_object(cdef.fullname) |
| 492 |
orig_func = builder.py_get_attr(typ, name, fdef.line) |
| 493 |
|
| 494 |
# Decorate the non-decorated method |
| 495 |
decorated_func = load_decorated_func(builder, fdef, orig_func) |
| 496 |
|
| 497 |
# Set the callable object representing the decorated method as an attribute of the |
| 498 |
# extension class. |
| 499 |
builder.primitive_op( |
| 500 |
py_setattr_op, [typ, builder.load_str(name), decorated_func], fdef.line |
| 501 |
) |
| 502 |
|
| 503 |
if fdef.is_property: |
| 504 |
# If there is a property setter, it will be processed after the getter, |
| 505 |
# We populate the optional setter field with none for now. |
| 506 |
assert name not in class_ir.properties |
| 507 |
class_ir.properties[name] = (func_ir, None) |
| 508 |
|
| 509 |
elif fdef in builder.prop_setters: |
| 510 |
# The respective property getter must have been processed already |
| 511 |
assert name in class_ir.properties |
| 512 |
getter_ir, _ = class_ir.properties[name] |
| 513 |
class_ir.properties[name] = (getter_ir, func_ir) |
| 514 |
|
| 515 |
class_ir.methods[func_ir.decl.name] = func_ir |
| 516 |
|
| 517 |
# If this overrides a parent class method with a different type, we need |
| 518 |
# to generate a glue method to mediate between them. |
| 519 |
for base in class_ir.mro[1:]: |
| 520 |
if ( |
| 521 |
name in base.method_decls |
| 522 |
and name != "__init__" |
| 523 |
and not is_same_method_signature( |
| 524 |
class_ir.method_decls[name].sig, base.method_decls[name].sig |
| 525 |
) |
| 526 |
): |
| 527 |
# TODO: Support contravariant subtyping in the input argument for |
| 528 |
# property setters. Need to make a special glue method for handling this, |
| 529 |
# similar to gen_glue_property. |
| 530 |
|
| 531 |
f = gen_glue(builder, base.method_decls[name].sig, func_ir, class_ir, base, fdef) |
| 532 |
class_ir.glue_methods[(base, name)] = f |
| 533 |
builder.functions.append(f) |
| 534 |
|
| 535 |
# If the class allows interpreted children, create glue |
| 536 |
# methods that dispatch via the Python API. These will go in a |
| 537 |
# "shadow vtable" that will be assigned to interpreted |
| 538 |
# children. |
| 539 |
if class_ir.allow_interpreted_subclasses: |
| 540 |
f = gen_glue(builder, func_ir.sig, func_ir, class_ir, class_ir, fdef, do_py_ops=True) |
| 541 |
# Use func_ir.decl.name (unique) rather than fdef.name, because for properties |
| 542 |
# the getter and setter share the same fdef.name but have distinct decl names |
| 543 |
# (e.g. "prop" vs "__mypyc_setter__prop"). Using fdef.name would cause the |
| 544 |
# setter's glue to overwrite the getter's glue in the shadow vtable. |
| 545 |
class_ir.glue_methods[(class_ir, func_ir.decl.name)] = f |
| 546 |
builder.functions.append(f) |
| 547 |
|
| 548 |
if fdef.name == "__getattr__": |
| 549 |
generate_getattr_wrapper(builder, cdef, fdef) |
| 550 |
elif fdef.name == "__setattr__": |
| 551 |
generate_setattr_wrapper(builder, cdef, fdef) |
| 552 |
elif fdef.name == "__delattr__": |
| 553 |
setattr = cdef.info.get("__setattr__") |
| 554 |
if not setattr or not setattr.node or setattr.node.fullname.startswith("builtins."): |
| 555 |
builder.error( |
| 556 |
'"__delattr__" supported only in classes that also override "__setattr__", ' |
| 557 |
+ "or inherit from a native class that overrides it.", |
| 558 |
fdef.line, |
| 559 |
) |
| 560 |
|
| 561 |
|
| 562 |
def handle_non_ext_method( |
| 563 |
builder: IRBuilder, non_ext: NonExtClassInfo, cdef: ClassDef, fdef: FuncDef |
| 564 |
) -> None: |
| 565 |
# Perform the function of visit_method for methods inside non-extension classes. |
| 566 |
name = fdef.name |
| 567 |
sig = builder.mapper.fdef_to_sig(fdef, builder.options.strict_dunders_typing) |
| 568 |
func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef) |
| 569 |
assert func_reg is not None |
| 570 |
builder.functions.append(func_ir) |
| 571 |
|
| 572 |
if is_decorated(builder, fdef): |
| 573 |
# The undecorated method is a generated callable class |
| 574 |
orig_func = func_reg |
| 575 |
func_reg = load_decorated_func(builder, fdef, orig_func) |
| 576 |
|
| 577 |
# TODO: Support property setters in non-extension classes |
| 578 |
if fdef.is_property: |
| 579 |
prop = builder.load_module_attr_by_fullname("builtins.property", fdef.line) |
| 580 |
func_reg = builder.py_call(prop, [func_reg], fdef.line) |
| 581 |
|
| 582 |
elif builder.mapper.func_to_decl[fdef].kind == FUNC_CLASSMETHOD: |
| 583 |
cls_meth = builder.load_module_attr_by_fullname("builtins.classmethod", fdef.line) |
| 584 |
func_reg = builder.py_call(cls_meth, [func_reg], fdef.line) |
| 585 |
|
| 586 |
elif builder.mapper.func_to_decl[fdef].kind == FUNC_STATICMETHOD: |
| 587 |
stat_meth = builder.load_module_attr_by_fullname("builtins.staticmethod", fdef.line) |
| 588 |
func_reg = builder.py_call(stat_meth, [func_reg], fdef.line) |
| 589 |
|
| 590 |
builder.add_to_non_ext_dict(non_ext, name, func_reg, fdef.line) |
| 591 |
|
| 592 |
# If we identified that this non-extension class method can be special-cased for |
| 593 |
# direct access during prepare phase, generate a "static" version of it. |
| 594 |
class_ir = builder.mapper.type_to_ir[cdef.info] |
| 595 |
name = FAST_PREFIX + fdef.name |
| 596 |
if name in class_ir.method_decls: |
| 597 |
func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef, make_ext_method=True) |
| 598 |
class_ir.methods[name] = func_ir |
| 599 |
builder.functions.append(func_ir) |
| 600 |
|
| 601 |
|
| 602 |
def gen_func_ns(builder: IRBuilder) -> str: |
| 603 |
"""Generate a namespace for a nested function using its outer function names.""" |
| 604 |
return "_".join( |
| 605 |
info.name + ("" if not info.class_name else "_" + info.class_name) |
| 606 |
for info in builder.fn_infos |
| 607 |
if info.name and info.name != "<module>" |
| 608 |
) |
| 609 |
|
| 610 |
|
| 611 |
def load_decorated_func(builder: IRBuilder, fdef: FuncDef, orig_func_reg: Value) -> Value: |
| 612 |
"""Apply decorators to a function. |
| 613 |
|
| 614 |
Given a decorated FuncDef and an instance of the callable class |
| 615 |
representing that FuncDef, apply the corresponding decorator |
| 616 |
functions on that decorated FuncDef and return the decorated |
| 617 |
function. |
| 618 |
""" |
| 619 |
if not is_decorated(builder, fdef): |
| 620 |
# If there are no decorators associated with the function, then just return the |
| 621 |
# original function. |
| 622 |
return orig_func_reg |
| 623 |
|
| 624 |
decorators = builder.fdefs_to_decorators[fdef] |
| 625 |
func_reg = orig_func_reg |
| 626 |
for d in reversed(decorators): |
| 627 |
decorator = d.accept(builder.visitor) |
| 628 |
assert isinstance(decorator, Value), decorator |
| 629 |
func_reg = builder.py_call(decorator, [func_reg], func_reg.line) |
| 630 |
return func_reg |
| 631 |
|
| 632 |
|
| 633 |
def is_decorated(builder: IRBuilder, fdef: FuncDef) -> bool: |
| 634 |
return fdef in builder.fdefs_to_decorators |
| 635 |
|
| 636 |
|
| 637 |
def gen_glue( |
| 638 |
builder: IRBuilder, |
| 639 |
base_sig: FuncSignature, |
| 640 |
target: FuncIR, |
| 641 |
cls: ClassIR, |
| 642 |
base: ClassIR, |
| 643 |
fdef: FuncItem, |
| 644 |
*, |
| 645 |
do_py_ops: bool = False, |
| 646 |
) -> FuncIR: |
| 647 |
"""Generate glue methods that mediate between different method types in subclasses. |
| 648 |
|
| 649 |
Works on both properties and methods. See gen_glue_methods below |
| 650 |
for more details. |
| 651 |
|
| 652 |
If do_py_ops is True, then the glue methods should use generic |
| 653 |
C API operations instead of direct calls, to enable generating |
| 654 |
"shadow" glue methods that work with interpreted subclasses. |
| 655 |
""" |
| 656 |
if fdef.is_property: |
| 657 |
return gen_glue_property(builder, base_sig, target, cls, base, fdef.line, do_py_ops) |
| 658 |
if do_py_ops and target.name.startswith(PROPSET_PREFIX): |
| 659 |
return gen_glue_property_setter(builder, base_sig, target, cls, base, fdef.line) |
| 660 |
return gen_glue_method(builder, base_sig, target, cls, base, fdef.line, do_py_ops) |
| 661 |
|
| 662 |
|
| 663 |
class ArgInfo(NamedTuple): |
| 664 |
args: list[Value] |
| 665 |
arg_names: list[str | None] |
| 666 |
arg_kinds: list[ArgKind] |
| 667 |
|
| 668 |
|
| 669 |
def get_args(builder: IRBuilder, rt_args: Sequence[RuntimeArg], line: int) -> ArgInfo: |
| 670 |
# The environment operates on Vars, so we make some up |
| 671 |
fake_vars = [(Var(arg.name), arg.type) for arg in rt_args] |
| 672 |
args = [ |
| 673 |
builder.read(builder.add_local_reg(var, type, is_arg=True), line) |
| 674 |
for var, type in fake_vars |
| 675 |
] |
| 676 |
arg_names = [ |
| 677 |
arg.name if arg.kind.is_named() or (arg.kind.is_optional() and not arg.pos_only) else None |
| 678 |
for arg in rt_args |
| 679 |
] |
| 680 |
arg_kinds = [arg.kind for arg in rt_args] |
| 681 |
return ArgInfo(args, arg_names, arg_kinds) |
| 682 |
|
| 683 |
|
| 684 |
def gen_glue_method( |
| 685 |
builder: IRBuilder, |
| 686 |
base_sig: FuncSignature, |
| 687 |
target: FuncIR, |
| 688 |
cls: ClassIR, |
| 689 |
base: ClassIR, |
| 690 |
line: int, |
| 691 |
do_pycall: bool, |
| 692 |
) -> FuncIR: |
| 693 |
"""Generate glue methods that mediate between different method types in subclasses. |
| 694 |
|
| 695 |
For example, if we have: |
| 696 |
|
| 697 |
class A: |
| 698 |
def f(builder: IRBuilder, x: int) -> object: ... |
| 699 |
|
| 700 |
then it is totally permissible to have a subclass |
| 701 |
|
| 702 |
class B(A): |
| 703 |
def f(builder: IRBuilder, x: object) -> int: ... |
| 704 |
|
| 705 |
since '(object) -> int' is a subtype of '(int) -> object' by the usual |
| 706 |
contra/co-variant function subtyping rules. |
| 707 |
|
| 708 |
The trickiness here is that int and object have different |
| 709 |
runtime representations in mypyc, so A.f and B.f have |
| 710 |
different signatures at the native C level. To deal with this, |
| 711 |
we need to generate glue methods that mediate between the |
| 712 |
different versions by coercing the arguments and return |
| 713 |
values. |
| 714 |
|
| 715 |
If do_pycall is True, then make the call using the C API |
| 716 |
instead of a native call. |
| 717 |
""" |
| 718 |
check_native_override(builder, base_sig, target.decl.sig, line) |
| 719 |
|
| 720 |
builder.enter() |
| 721 |
builder.ret_types[-1] = base_sig.ret_type |
| 722 |
|
| 723 |
rt_args = list(base_sig.args) |
| 724 |
if target.decl.kind == FUNC_NORMAL: |
| 725 |
rt_args[0] = RuntimeArg(base_sig.args[0].name, RInstance(cls)) |
| 726 |
|
| 727 |
arg_info = get_args(builder, rt_args, line) |
| 728 |
args, arg_kinds, arg_names = arg_info.args, arg_info.arg_kinds, arg_info.arg_names |
| 729 |
|
| 730 |
bitmap_args = None |
| 731 |
if base_sig.num_bitmap_args: |
| 732 |
args = args[: -base_sig.num_bitmap_args] |
| 733 |
arg_kinds = arg_kinds[: -base_sig.num_bitmap_args] |
| 734 |
arg_names = arg_names[: -base_sig.num_bitmap_args] |
| 735 |
bitmap_args = list(builder.builder.args[-base_sig.num_bitmap_args :]) |
| 736 |
|
| 737 |
# We can do a passthrough *args/**kwargs with a native call, but if the |
| 738 |
# args need to get distributed out to arguments, we just let python handle it |
| 739 |
if any(kind.is_star() for kind in arg_kinds) and any( |
| 740 |
not arg.kind.is_star() for arg in target.decl.sig.args |
| 741 |
): |
| 742 |
do_pycall = True |
| 743 |
|
| 744 |
if do_pycall: |
| 745 |
if target.decl.kind == FUNC_STATICMETHOD: |
| 746 |
# FIXME: this won't work if we can do interpreted subclasses |
| 747 |
first = builder.builder.get_native_type(cls) |
| 748 |
st = 0 |
| 749 |
else: |
| 750 |
first = args[0] |
| 751 |
st = 1 |
| 752 |
retval = builder.builder.py_method_call( |
| 753 |
first, target.name, args[st:], line, arg_kinds[st:], arg_names[st:] |
| 754 |
) |
| 755 |
else: |
| 756 |
retval = builder.builder.call( |
| 757 |
target.decl, args, arg_kinds, arg_names, line, bitmap_args=bitmap_args |
| 758 |
) |
| 759 |
retval = builder.coerce(retval, base_sig.ret_type, line) |
| 760 |
builder.add(Return(retval)) |
| 761 |
|
| 762 |
arg_regs, _, blocks, ret_type, _ = builder.leave() |
| 763 |
if base_sig.num_bitmap_args: |
| 764 |
rt_args = rt_args[: -base_sig.num_bitmap_args] |
| 765 |
return FuncIR( |
| 766 |
FuncDecl( |
| 767 |
target.name + "__" + base.name + "_glue", |
| 768 |
cls.name, |
| 769 |
builder.module_name, |
| 770 |
FuncSignature(rt_args, ret_type), |
| 771 |
target.decl.kind, |
| 772 |
is_coroutine=target.decl.is_coroutine, |
| 773 |
), |
| 774 |
arg_regs, |
| 775 |
blocks, |
| 776 |
) |
| 777 |
|
| 778 |
|
| 779 |
def check_native_override( |
| 780 |
builder: IRBuilder, base_sig: FuncSignature, sub_sig: FuncSignature, line: int |
| 781 |
) -> None: |
| 782 |
"""Report an error if an override changes signature in unsupported ways. |
| 783 |
|
| 784 |
Glue methods can work around many signature changes but not all of them. |
| 785 |
""" |
| 786 |
for base_arg, sub_arg in zip(base_sig.real_args(), sub_sig.real_args()): |
| 787 |
if base_arg.type.error_overlap: |
| 788 |
if not base_arg.optional and sub_arg.optional and base_sig.num_bitmap_args: |
| 789 |
# This would change the meanings of bits in the argument defaults |
| 790 |
# bitmap, which we don't support. We'd need to do tricky bit |
| 791 |
# manipulations to support this generally. |
| 792 |
builder.error( |
| 793 |
"An argument with type " |
| 794 |
+ f'"{base_arg.type}" cannot be given a default value in a method override', |
| 795 |
line, |
| 796 |
) |
| 797 |
if base_arg.type.error_overlap or sub_arg.type.error_overlap: |
| 798 |
if not is_same_type(base_arg.type, sub_arg.type): |
| 799 |
# This would change from signaling a default via an error value to |
| 800 |
# signaling a default via bitmap, which we don't support. |
| 801 |
builder.error( |
| 802 |
"Incompatible argument type " |
| 803 |
+ f'"{sub_arg.type}" (base class has type "{base_arg.type}")', |
| 804 |
line, |
| 805 |
) |
| 806 |
|
| 807 |
|
| 808 |
def gen_glue_property( |
| 809 |
builder: IRBuilder, |
| 810 |
sig: FuncSignature, |
| 811 |
target: FuncIR, |
| 812 |
cls: ClassIR, |
| 813 |
base: ClassIR, |
| 814 |
line: int, |
| 815 |
do_pygetattr: bool, |
| 816 |
) -> FuncIR: |
| 817 |
"""Generate glue methods for properties that mediate between different subclass types. |
| 818 |
|
| 819 |
Similarly to methods, properties of derived types can be covariantly subtyped. Thus, |
| 820 |
properties also require glue. However, this only requires the return type to change. |
| 821 |
Further, instead of a method call, an attribute get is performed. |
| 822 |
|
| 823 |
If do_pygetattr is True, then get the attribute using the Python C |
| 824 |
API instead of a native call. |
| 825 |
""" |
| 826 |
builder.enter() |
| 827 |
|
| 828 |
rt_arg = RuntimeArg(SELF_NAME, RInstance(cls)) |
| 829 |
self_target = builder.add_self_to_env(cls) |
| 830 |
arg = builder.read(self_target, line) |
| 831 |
builder.ret_types[-1] = sig.ret_type |
| 832 |
if do_pygetattr: |
| 833 |
retval = builder.py_get_attr(arg, target.name, line) |
| 834 |
else: |
| 835 |
retval = builder.add(GetAttr(arg, target.name, line)) |
| 836 |
retbox = builder.coerce(retval, sig.ret_type, line) |
| 837 |
builder.add(Return(retbox)) |
| 838 |
|
| 839 |
args, _, blocks, return_type, _ = builder.leave() |
| 840 |
return FuncIR( |
| 841 |
FuncDecl( |
| 842 |
target.name + "__" + base.name + "_glue", |
| 843 |
cls.name, |
| 844 |
builder.module_name, |
| 845 |
FuncSignature([rt_arg], return_type), |
| 846 |
), |
| 847 |
args, |
| 848 |
blocks, |
| 849 |
) |
| 850 |
|
| 851 |
|
| 852 |
def gen_glue_property_setter( |
| 853 |
builder: IRBuilder, sig: FuncSignature, target: FuncIR, cls: ClassIR, base: ClassIR, line: int |
| 854 |
) -> FuncIR: |
| 855 |
"""Generate a shadow glue method for a property setter. |
| 856 |
|
| 857 |
For interpreted subclasses, property setters can't be called via the |
| 858 |
internal __mypyc_setter__<name> method. Instead, use Python's setattr |
| 859 |
to set the property via the standard descriptor protocol. |
| 860 |
""" |
| 861 |
builder.enter() |
| 862 |
builder.ret_types[-1] = sig.ret_type |
| 863 |
|
| 864 |
rt_args = list(sig.args) |
| 865 |
rt_args[0] = RuntimeArg(sig.args[0].name, RInstance(cls)) |
| 866 |
|
| 867 |
arg_info = get_args(builder, rt_args, line) |
| 868 |
args = arg_info.args |
| 869 |
|
| 870 |
self_arg = args[0] |
| 871 |
value_arg = args[1] |
| 872 |
|
| 873 |
# Extract the property name from "__mypyc_setter__<name>" |
| 874 |
assert target.name.startswith(PROPSET_PREFIX) |
| 875 |
prop_name = target.name[len(PROPSET_PREFIX) :] |
| 876 |
|
| 877 |
builder.primitive_op( |
| 878 |
py_setattr_op, |
| 879 |
[ |
| 880 |
self_arg, |
| 881 |
builder.load_str(prop_name), |
| 882 |
builder.coerce(value_arg, object_rprimitive, line), |
| 883 |
], |
| 884 |
line, |
| 885 |
) |
| 886 |
retval = builder.coerce(builder.none(), sig.ret_type, line) |
| 887 |
builder.add(Return(retval)) |
| 888 |
|
| 889 |
arg_regs, _, blocks, return_type, _ = builder.leave() |
| 890 |
return FuncIR( |
| 891 |
FuncDecl( |
| 892 |
target.name + "__" + base.name + "_glue", |
| 893 |
cls.name, |
| 894 |
builder.module_name, |
| 895 |
FuncSignature(rt_args, return_type), |
| 896 |
), |
| 897 |
arg_regs, |
| 898 |
blocks, |
| 899 |
) |
| 900 |
|
| 901 |
|
| 902 |
def get_func_target(builder: IRBuilder, fdef: FuncDef) -> AssignmentTarget: |
| 903 |
"""Given a FuncDef, return the target for the instance of its callable class. |
| 904 |
|
| 905 |
If the function was not already defined somewhere, then define it |
| 906 |
and add it to the current environment. |
| 907 |
""" |
| 908 |
if orig := fdef.original_def: |
| 909 |
if isinstance(orig, Decorator): |
| 910 |
orig = orig.func |
| 911 |
# Get the target associated with the previously defined FuncDef. |
| 912 |
return builder.lookup(orig) |
| 913 |
|
| 914 |
if builder.fn_info.is_generator or builder.fn_info.add_nested_funcs_to_env: |
| 915 |
return builder.lookup(fdef) |
| 916 |
|
| 917 |
return builder.add_local_reg(fdef, object_rprimitive) |
| 918 |
|
| 919 |
|
| 920 |
def load_type(builder: IRBuilder, typ: TypeInfo, unbounded_type: Type | None, line: int) -> Value: |
| 921 |
# typ.fullname contains the module where the class object was defined. However, it is possible |
| 922 |
# that the class object's module was not imported in the file currently being compiled. So, we |
| 923 |
# use unbounded_type.name (if provided by caller) to load the class object through one of the |
| 924 |
# imported modules. |
| 925 |
# Example: for `json.JSONDecoder`, typ.fullname is `json.decoder.JSONDecoder` but the Python |
| 926 |
# file may import `json` not `json.decoder`. |
| 927 |
# Another corner case: The Python file being compiled imports mod1 and has a type hint |
| 928 |
# `mod1.OuterClass.InnerClass`. But, mod1/__init__.py might import OuterClass like this: |
| 929 |
# `from mod2.mod3 import OuterClass`. In this case, typ.fullname is |
| 930 |
# `mod2.mod3.OuterClass.InnerClass` and `unbounded_type.name` is `mod1.OuterClass.InnerClass`. |
| 931 |
# So, we must use unbounded_type.name to load the class object. |
| 932 |
# See issue mypyc/mypyc#1087. |
| 933 |
if typ in builder.mapper.type_to_ir: |
| 934 |
class_ir = builder.mapper.type_to_ir[typ] |
| 935 |
class_obj = builder.builder.get_native_type(class_ir) |
| 936 |
elif builtin := builder.load_builtin(typ.fullname, line): |
| 937 |
class_obj = builtin |
| 938 |
elif isinstance(unbounded_type, UnboundType): |
| 939 |
path_parts = unbounded_type.name.split(".") |
| 940 |
class_obj = builder.load_global_str(path_parts[0], line) |
| 941 |
for attr in path_parts[1:]: |
| 942 |
class_obj = builder.py_get_attr(class_obj, attr, line) |
| 943 |
else: |
| 944 |
class_obj = builder.load_global_str(typ.name, line) |
| 945 |
|
| 946 |
return class_obj |
| 947 |
|
| 948 |
|
| 949 |
def load_func(builder: IRBuilder, func_name: str, fullname: str | None, line: int) -> Value: |
| 950 |
if fullname and not fullname.startswith(builder.current_module): |
| 951 |
# we're calling a function in a different module |
| 952 |
|
| 953 |
# We can't use load_module_attr_by_fullname here because we need to load the function using |
| 954 |
# func_name, not the name specified by fullname (which can be different for underscore |
| 955 |
# function) |
| 956 |
module = fullname.rsplit(".")[0] |
| 957 |
loaded_module = builder.load_module(module) |
| 958 |
|
| 959 |
func = builder.py_get_attr(loaded_module, func_name, line) |
| 960 |
else: |
| 961 |
func = builder.load_global_str(func_name, line) |
| 962 |
return func |
| 963 |
|
| 964 |
|
| 965 |
def generate_singledispatch_dispatch_function( |
| 966 |
builder: IRBuilder, main_singledispatch_function_name: str, fitem: FuncDef |
| 967 |
) -> None: |
| 968 |
line = fitem.line |
| 969 |
current_func_decl = builder.mapper.func_to_decl[fitem] |
| 970 |
arg_info = get_args(builder, current_func_decl.sig.args, line) |
| 971 |
|
| 972 |
dispatch_func_obj = builder.self() |
| 973 |
|
| 974 |
arg_type = builder.builder.get_type_of_obj(arg_info.args[0], line) |
| 975 |
dispatch_cache = builder.builder.get_attr( |
| 976 |
dispatch_func_obj, "dispatch_cache", dict_rprimitive, line |
| 977 |
) |
| 978 |
call_find_impl, use_cache, call_func = BasicBlock(), BasicBlock(), BasicBlock() |
| 979 |
get_result = builder.primitive_op(dict_get_method_with_none, [dispatch_cache, arg_type], line) |
| 980 |
is_not_none = builder.translate_is_op(get_result, builder.none_object(), "is not", line) |
| 981 |
impl_to_use = Register(object_rprimitive) |
| 982 |
builder.add_bool_branch(is_not_none, use_cache, call_find_impl) |
| 983 |
|
| 984 |
builder.activate_block(use_cache) |
| 985 |
builder.assign(impl_to_use, get_result, line) |
| 986 |
builder.goto(call_func) |
| 987 |
|
| 988 |
builder.activate_block(call_find_impl) |
| 989 |
find_impl = builder.load_module_attr_by_fullname("functools._find_impl", line) |
| 990 |
registry = load_singledispatch_registry(builder, dispatch_func_obj, line) |
| 991 |
uncached_impl = builder.py_call(find_impl, [arg_type, registry], line) |
| 992 |
builder.call_c(exact_dict_set_item_op, [dispatch_cache, arg_type, uncached_impl], line) |
| 993 |
builder.assign(impl_to_use, uncached_impl, line) |
| 994 |
builder.goto(call_func) |
| 995 |
|
| 996 |
builder.activate_block(call_func) |
| 997 |
gen_calls_to_correct_impl(builder, impl_to_use, arg_info, fitem, line) |
| 998 |
|
| 999 |
|
| 1000 |
def gen_calls_to_correct_impl( |
| 1001 |
builder: IRBuilder, impl_to_use: Value, arg_info: ArgInfo, fitem: FuncDef, line: int |
| 1002 |
) -> None: |
| 1003 |
current_func_decl = builder.mapper.func_to_decl[fitem] |
| 1004 |
|
| 1005 |
def gen_native_func_call_and_return(fdef: FuncDef) -> None: |
| 1006 |
func_decl = builder.mapper.func_to_decl[fdef] |
| 1007 |
ret_val = builder.builder.call( |
| 1008 |
func_decl, arg_info.args, arg_info.arg_kinds, arg_info.arg_names, line |
| 1009 |
) |
| 1010 |
coerced = builder.coerce(ret_val, current_func_decl.sig.ret_type, line) |
| 1011 |
builder.add(Return(coerced)) |
| 1012 |
|
| 1013 |
int_type_obj = builder.load_builtin("builtins.int", line) |
| 1014 |
assert int_type_obj |
| 1015 |
is_int = builder.builder.type_is_op(impl_to_use, int_type_obj, line) |
| 1016 |
|
| 1017 |
native_call, non_native_call = BasicBlock(), BasicBlock() |
| 1018 |
builder.add_bool_branch(is_int, native_call, non_native_call) |
| 1019 |
builder.activate_block(native_call) |
| 1020 |
|
| 1021 |
passed_id = builder.add(Unbox(impl_to_use, int_rprimitive, line)) |
| 1022 |
|
| 1023 |
native_ids = get_native_impl_ids(builder, fitem) |
| 1024 |
for impl, i in native_ids.items(): |
| 1025 |
call_impl, next_impl = BasicBlock(), BasicBlock() |
| 1026 |
|
| 1027 |
current_id = builder.load_int(i) |
| 1028 |
cond = builder.binary_op(passed_id, current_id, "==", line) |
| 1029 |
builder.add_bool_branch(cond, call_impl, next_impl) |
| 1030 |
|
| 1031 |
# Call the registered implementation |
| 1032 |
builder.activate_block(call_impl) |
| 1033 |
|
| 1034 |
gen_native_func_call_and_return(impl) |
| 1035 |
builder.activate_block(next_impl) |
| 1036 |
|
| 1037 |
# We've already handled all the possible integer IDs, so we should never get here |
| 1038 |
builder.add(Unreachable()) |
| 1039 |
|
| 1040 |
builder.activate_block(non_native_call) |
| 1041 |
ret_val = builder.py_call( |
| 1042 |
impl_to_use, arg_info.args, line, arg_info.arg_kinds, arg_info.arg_names |
| 1043 |
) |
| 1044 |
coerced = builder.coerce(ret_val, current_func_decl.sig.ret_type, line) |
| 1045 |
builder.add(Return(coerced)) |
| 1046 |
|
| 1047 |
|
| 1048 |
def gen_dispatch_func_ir( |
| 1049 |
builder: IRBuilder, fitem: FuncDef, main_func_name: str, dispatch_name: str, sig: FuncSignature |
| 1050 |
) -> tuple[FuncIR, Value]: |
| 1051 |
"""Create a dispatch function (a function that checks the first argument type and dispatches |
| 1052 |
to the correct implementation) |
| 1053 |
""" |
| 1054 |
builder.enter(FuncInfo(fitem, dispatch_name)) |
| 1055 |
setup_callable_class(builder) |
| 1056 |
builder.fn_info.callable_class.ir.attributes["registry"] = dict_rprimitive |
| 1057 |
builder.fn_info.callable_class.ir.attributes["dispatch_cache"] = dict_rprimitive |
| 1058 |
builder.fn_info.callable_class.ir.has_dict = True |
| 1059 |
builder.fn_info.callable_class.ir.needs_getseters = True |
| 1060 |
generate_singledispatch_callable_class_ctor(builder) |
| 1061 |
|
| 1062 |
generate_singledispatch_dispatch_function(builder, main_func_name, fitem) |
| 1063 |
args, _, blocks, _, fn_info = builder.leave() |
| 1064 |
dispatch_callable_class = add_call_to_callable_class(builder, args, blocks, sig, fn_info) |
| 1065 |
builder.functions.append(dispatch_callable_class) |
| 1066 |
add_get_to_callable_class(builder, fn_info) |
| 1067 |
add_register_method_to_callable_class(builder, fn_info) |
| 1068 |
func_reg = instantiate_callable_class(builder, fn_info) |
| 1069 |
dispatch_func_ir = generate_dispatch_glue_native_function( |
| 1070 |
builder, fitem, dispatch_callable_class.decl, dispatch_name |
| 1071 |
) |
| 1072 |
|
| 1073 |
return dispatch_func_ir, func_reg |
| 1074 |
|
| 1075 |
|
| 1076 |
def generate_dispatch_glue_native_function( |
| 1077 |
builder: IRBuilder, fitem: FuncDef, callable_class_decl: FuncDecl, dispatch_name: str |
| 1078 |
) -> FuncIR: |
| 1079 |
line = fitem.line |
| 1080 |
builder.enter() |
| 1081 |
# We store the callable class in the globals dict for this function |
| 1082 |
callable_class = builder.load_global_str(dispatch_name, line) |
| 1083 |
decl = builder.mapper.func_to_decl[fitem] |
| 1084 |
arg_info = get_args(builder, decl.sig.args, line) |
| 1085 |
args = [callable_class] + arg_info.args |
| 1086 |
arg_kinds = [ArgKind.ARG_POS] + arg_info.arg_kinds |
| 1087 |
arg_names = arg_info.arg_names |
| 1088 |
arg_names.insert(0, "self") |
| 1089 |
ret_val = builder.builder.call(callable_class_decl, args, arg_kinds, arg_names, line) |
| 1090 |
builder.add(Return(ret_val)) |
| 1091 |
arg_regs, _, blocks, _, fn_info = builder.leave() |
| 1092 |
return FuncIR(decl, arg_regs, blocks) |
| 1093 |
|
| 1094 |
|
| 1095 |
def generate_singledispatch_callable_class_ctor(builder: IRBuilder) -> None: |
| 1096 |
"""Create an __init__ that sets registry and dispatch_cache to empty dicts""" |
| 1097 |
line = builder.fn_info.fitem.line |
| 1098 |
class_ir = builder.fn_info.callable_class.ir |
| 1099 |
with builder.enter_method(class_ir, "__init__", bool_rprimitive): |
| 1100 |
empty_dict = builder.call_c(dict_new_op, [], line) |
| 1101 |
builder.add(SetAttr(builder.self(), "registry", empty_dict, line)) |
| 1102 |
cache_dict = builder.call_c(dict_new_op, [], line) |
| 1103 |
dispatch_cache_str = builder.load_str("dispatch_cache") |
| 1104 |
# use the py_setattr_op instead of SetAttr so that it also gets added to our __dict__ |
| 1105 |
builder.primitive_op(py_setattr_op, [builder.self(), dispatch_cache_str, cache_dict], line) |
| 1106 |
# the generated C code seems to expect that __init__ returns a char, so just return 1 |
| 1107 |
builder.add(Return(Integer(1, bool_rprimitive, line), line)) |
| 1108 |
|
| 1109 |
|
| 1110 |
def add_register_method_to_callable_class(builder: IRBuilder, fn_info: FuncInfo) -> None: |
| 1111 |
line = fn_info.fitem.line |
| 1112 |
with builder.enter_method(fn_info.callable_class.ir, "register", object_rprimitive): |
| 1113 |
cls_arg = builder.add_argument("cls", object_rprimitive) |
| 1114 |
func_arg = builder.add_argument("func", object_rprimitive, ArgKind.ARG_OPT) |
| 1115 |
ret_val = builder.call_c(register_function, [builder.self(), cls_arg, func_arg], line) |
| 1116 |
builder.add(Return(ret_val, line)) |
| 1117 |
|
| 1118 |
|
| 1119 |
def load_singledispatch_registry(builder: IRBuilder, dispatch_func_obj: Value, line: int) -> Value: |
| 1120 |
return builder.builder.get_attr(dispatch_func_obj, "registry", dict_rprimitive, line) |
| 1121 |
|
| 1122 |
|
| 1123 |
def singledispatch_main_func_name(orig_name: str) -> str: |
| 1124 |
return f"__mypyc_singledispatch_main_function_{orig_name}__" |
| 1125 |
|
| 1126 |
|
| 1127 |
def maybe_insert_into_registry_dict(builder: IRBuilder, fitem: FuncDef) -> None: |
| 1128 |
line = fitem.line |
| 1129 |
is_singledispatch_main_func = fitem in builder.singledispatch_impls |
| 1130 |
# dict of singledispatch_func to list of register_types (fitem is the function to register) |
| 1131 |
to_register: defaultdict[FuncDef, list[TypeInfo]] = defaultdict(list) |
| 1132 |
for main_func, impls in builder.singledispatch_impls.items(): |
| 1133 |
for dispatch_type, impl in impls: |
| 1134 |
if fitem == impl: |
| 1135 |
to_register[main_func].append(dispatch_type) |
| 1136 |
|
| 1137 |
if not to_register and not is_singledispatch_main_func: |
| 1138 |
return |
| 1139 |
|
| 1140 |
if is_singledispatch_main_func: |
| 1141 |
main_func_name = singledispatch_main_func_name(fitem.name) |
| 1142 |
main_func_obj = load_func(builder, main_func_name, fitem.fullname, line) |
| 1143 |
|
| 1144 |
loaded_object_type = builder.load_module_attr_by_fullname("builtins.object", line) |
| 1145 |
registry_dict = builder.builder.make_dict([(loaded_object_type, main_func_obj)], line) |
| 1146 |
|
| 1147 |
dispatch_func_obj = builder.load_global_str(fitem.name, line) |
| 1148 |
builder.primitive_op( |
| 1149 |
py_setattr_op, [dispatch_func_obj, builder.load_str("registry"), registry_dict], line |
| 1150 |
) |
| 1151 |
|
| 1152 |
for singledispatch_func, types in to_register.items(): |
| 1153 |
# TODO: avoid recomputing the native IDs for all the functions every time we find a new |
| 1154 |
# function |
| 1155 |
native_ids = get_native_impl_ids(builder, singledispatch_func) |
| 1156 |
if fitem not in native_ids: |
| 1157 |
to_insert = load_func(builder, fitem.name, fitem.fullname, line) |
| 1158 |
else: |
| 1159 |
current_id = native_ids[fitem] |
| 1160 |
load_literal = LoadLiteral(current_id, object_rprimitive) |
| 1161 |
to_insert = builder.add(load_literal) |
| 1162 |
# TODO: avoid reloading the registry here if we just created it |
| 1163 |
dispatch_func_obj = load_func( |
| 1164 |
builder, singledispatch_func.name, singledispatch_func.fullname, line |
| 1165 |
) |
| 1166 |
registry = load_singledispatch_registry(builder, dispatch_func_obj, line) |
| 1167 |
for typ in types: |
| 1168 |
loaded_type = load_type(builder, typ, None, line) |
| 1169 |
builder.call_c(exact_dict_set_item_op, [registry, loaded_type, to_insert], line) |
| 1170 |
dispatch_cache = builder.builder.get_attr( |
| 1171 |
dispatch_func_obj, "dispatch_cache", dict_rprimitive, line |
| 1172 |
) |
| 1173 |
builder.gen_method_call(dispatch_cache, "clear", [], None, line) |
| 1174 |
|
| 1175 |
|
| 1176 |
def get_native_impl_ids(builder: IRBuilder, singledispatch_func: FuncDef) -> dict[FuncDef, int]: |
| 1177 |
"""Return a dict of registered implementation to native implementation ID for all |
| 1178 |
implementations |
| 1179 |
""" |
| 1180 |
impls = builder.singledispatch_impls[singledispatch_func] |
| 1181 |
return {impl: i for i, (typ, impl) in enumerate(impls) if not is_decorated(builder, impl)} |
| 1182 |
|
| 1183 |
|
| 1184 |
def gen_property_getter_ir( |
| 1185 |
builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool |
| 1186 |
) -> FuncIR: |
| 1187 |
"""Generate an implicit trivial property getter for an attribute. |
| 1188 |
|
| 1189 |
These are used if an attribute can also be accessed as a property. |
| 1190 |
""" |
| 1191 |
name = func_decl.name |
| 1192 |
builder.enter(name) |
| 1193 |
self_reg = builder.add_argument("self", func_decl.sig.args[0].type) |
| 1194 |
line = func_decl._line or -1 |
| 1195 |
if not is_trait: |
| 1196 |
value = builder.builder.get_attr(self_reg, name, func_decl.sig.ret_type, line) |
| 1197 |
builder.add(Return(value, line)) |
| 1198 |
else: |
| 1199 |
builder.add(Unreachable()) |
| 1200 |
args, _, blocks, ret_type, fn_info = builder.leave() |
| 1201 |
return FuncIR(func_decl, args, blocks) |
| 1202 |
|
| 1203 |
|
| 1204 |
def gen_property_setter_ir( |
| 1205 |
builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool |
| 1206 |
) -> FuncIR: |
| 1207 |
"""Generate an implicit trivial property setter for an attribute. |
| 1208 |
|
| 1209 |
These are used if an attribute can also be accessed as a property. |
| 1210 |
""" |
| 1211 |
name = func_decl.name |
| 1212 |
builder.enter(name) |
| 1213 |
self_reg = builder.add_argument("self", func_decl.sig.args[0].type) |
| 1214 |
value_reg = builder.add_argument("value", func_decl.sig.args[1].type) |
| 1215 |
assert name.startswith(PROPSET_PREFIX) |
| 1216 |
attr_name = name[len(PROPSET_PREFIX) :] |
| 1217 |
line = func_decl._line or -1 |
| 1218 |
if not is_trait: |
| 1219 |
builder.add(SetAttr(self_reg, attr_name, value_reg, line)) |
| 1220 |
builder.add(Return(builder.none(), line)) |
| 1221 |
args, _, blocks, ret_type, fn_info = builder.leave() |
| 1222 |
return FuncIR(func_decl, args, blocks, line) |