| 1 |
"""Generate a class that represents a nested function. |
| 2 |
|
| 3 |
The class defines __call__ for calling the function and allows access to |
| 4 |
non-local variables defined in outer scopes. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
from mypyc.common import CPYFUNCTION_NAME, ENV_ATTR_NAME, PROPSET_PREFIX, SELF_NAME |
| 10 |
from mypyc.ir.class_ir import ClassIR |
| 11 |
from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg |
| 12 |
from mypyc.ir.ops import BasicBlock, Call, GetAttr, Integer, Register, Return, SetAttr, Value |
| 13 |
from mypyc.ir.rtypes import RInstance, c_pointer_rprimitive, int_rprimitive, object_rprimitive |
| 14 |
from mypyc.irbuild.builder import IRBuilder |
| 15 |
from mypyc.irbuild.context import FuncInfo, ImplicitClass |
| 16 |
from mypyc.primitives.misc_ops import ( |
| 17 |
cpyfunction_get_annotations, |
| 18 |
cpyfunction_get_code, |
| 19 |
cpyfunction_get_defaults, |
| 20 |
cpyfunction_get_kwdefaults, |
| 21 |
cpyfunction_get_name, |
| 22 |
cpyfunction_set_annotations, |
| 23 |
cpyfunction_set_name, |
| 24 |
method_new_op, |
| 25 |
) |
| 26 |
|
| 27 |
|
| 28 |
def setup_callable_class(builder: IRBuilder) -> None: |
| 29 |
"""Generate an (incomplete) callable class representing a function. |
| 30 |
|
| 31 |
This can be a nested function or a function within a non-extension |
| 32 |
class. Also set up the 'self' variable for that class. |
| 33 |
|
| 34 |
This takes the most recently visited function and returns a |
| 35 |
ClassIR to represent that function. Each callable class contains |
| 36 |
an environment attribute which points to another ClassIR |
| 37 |
representing the environment class where some of its variables can |
| 38 |
be accessed. |
| 39 |
|
| 40 |
Note that some methods, such as '__call__', are not yet |
| 41 |
created here. Use additional functions, such as |
| 42 |
add_call_to_callable_class(), to add them. |
| 43 |
|
| 44 |
Return a newly constructed ClassIR representing the callable |
| 45 |
class for the nested function. |
| 46 |
""" |
| 47 |
# Check to see that the name has not already been taken. If so, |
| 48 |
# rename the class. We allow multiple uses of the same function |
| 49 |
# name because this is valid in if-else blocks. Example: |
| 50 |
# |
| 51 |
# if True: |
| 52 |
# def foo(): ----> foo_obj() |
| 53 |
# return True |
| 54 |
# else: |
| 55 |
# def foo(): ----> foo_obj_0() |
| 56 |
# return False |
| 57 |
name = base_name = f"{builder.fn_info.namespaced_name()}_obj" |
| 58 |
count = 0 |
| 59 |
while name in builder.callable_class_names: |
| 60 |
name = base_name + "_" + str(count) |
| 61 |
count += 1 |
| 62 |
builder.callable_class_names.add(name) |
| 63 |
|
| 64 |
# Define the actual callable class ClassIR, and set its |
| 65 |
# environment to point at the previously defined environment |
| 66 |
# class. |
| 67 |
callable_class_ir = ClassIR(name, builder.module_name, is_generated=True, is_final_class=True) |
| 68 |
callable_class_ir.reuse_freed_instance = True |
| 69 |
|
| 70 |
# The functools @wraps decorator attempts to call setattr on |
| 71 |
# nested functions, so we create a dict for these nested |
| 72 |
# functions. |
| 73 |
# https://github.com/python/cpython/blob/3.7/Lib/functools.py#L58 |
| 74 |
if builder.fn_info.is_nested: |
| 75 |
callable_class_ir.has_dict = True |
| 76 |
|
| 77 |
# If the enclosing class doesn't contain nested (which will happen if |
| 78 |
# this is a toplevel lambda), don't set up an environment. |
| 79 |
if builder.fn_infos[-2].contains_nested: |
| 80 |
callable_class_ir.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_infos[-2].env_class) |
| 81 |
callable_class_ir.mro = [callable_class_ir] |
| 82 |
builder.fn_info.callable_class = ImplicitClass(callable_class_ir) |
| 83 |
builder.classes.append(callable_class_ir) |
| 84 |
|
| 85 |
# Add a 'self' variable to the environment of the callable class, |
| 86 |
# and store that variable in a register to be accessed later. |
| 87 |
self_target = builder.add_self_to_env(callable_class_ir) |
| 88 |
builder.fn_info.callable_class.self_reg = builder.read(self_target, builder.fn_info.fitem.line) |
| 89 |
|
| 90 |
if not builder.fn_info.in_non_ext and builder.fn_info.is_coroutine: |
| 91 |
add_coroutine_properties(builder, callable_class_ir, builder.fn_info.name) |
| 92 |
|
| 93 |
|
| 94 |
def add_coroutine_properties( |
| 95 |
builder: IRBuilder, callable_class_ir: ClassIR, coroutine_name: str |
| 96 |
) -> None: |
| 97 |
"""Adds properties to the class to make it look like a regular python function. |
| 98 |
Needed to make introspection functions like inspect.iscoroutinefunction work. |
| 99 |
""" |
| 100 |
callable_class_ir.coroutine_name = coroutine_name |
| 101 |
callable_class_ir.attributes[CPYFUNCTION_NAME] = object_rprimitive |
| 102 |
|
| 103 |
properties = { |
| 104 |
"__name__": cpyfunction_get_name, |
| 105 |
"__code__": cpyfunction_get_code, |
| 106 |
"__annotations__": cpyfunction_get_annotations, |
| 107 |
"__defaults__": cpyfunction_get_defaults, |
| 108 |
"__kwdefaults__": cpyfunction_get_kwdefaults, |
| 109 |
} |
| 110 |
|
| 111 |
writable_props = { |
| 112 |
"__name__": cpyfunction_set_name, |
| 113 |
"__annotations__": cpyfunction_set_annotations, |
| 114 |
} |
| 115 |
|
| 116 |
line = builder.fn_info.fitem.line |
| 117 |
|
| 118 |
def get_func_wrapper() -> Value: |
| 119 |
return builder.add(GetAttr(builder.self(), CPYFUNCTION_NAME, line)) |
| 120 |
|
| 121 |
for name, primitive in properties.items(): |
| 122 |
with builder.enter_method(callable_class_ir, name, object_rprimitive, internal=True): |
| 123 |
func = get_func_wrapper() |
| 124 |
val = builder.primitive_op(primitive, [func, Integer(0, c_pointer_rprimitive)], line) |
| 125 |
builder.add(Return(val)) |
| 126 |
|
| 127 |
for name, primitive in writable_props.items(): |
| 128 |
with builder.enter_method( |
| 129 |
callable_class_ir, f"{PROPSET_PREFIX}{name}", int_rprimitive, internal=True |
| 130 |
): |
| 131 |
value = builder.add_argument("value", object_rprimitive) |
| 132 |
func = get_func_wrapper() |
| 133 |
rv = builder.primitive_op( |
| 134 |
primitive, [func, value, Integer(0, c_pointer_rprimitive)], line |
| 135 |
) |
| 136 |
builder.add(Return(rv)) |
| 137 |
|
| 138 |
for name in properties: |
| 139 |
getter = callable_class_ir.get_method(name) |
| 140 |
assert getter |
| 141 |
setter = callable_class_ir.get_method(f"{PROPSET_PREFIX}{name}") |
| 142 |
callable_class_ir.properties[name] = (getter, setter) |
| 143 |
|
| 144 |
|
| 145 |
def add_call_to_callable_class( |
| 146 |
builder: IRBuilder, |
| 147 |
args: list[Register], |
| 148 |
blocks: list[BasicBlock], |
| 149 |
sig: FuncSignature, |
| 150 |
fn_info: FuncInfo, |
| 151 |
) -> FuncIR: |
| 152 |
"""Generate a '__call__' method for a callable class representing a nested function. |
| 153 |
|
| 154 |
This takes the blocks and signature associated with a function |
| 155 |
definition and uses those to build the '__call__' method of a |
| 156 |
given callable class, used to represent that function. |
| 157 |
""" |
| 158 |
# Since we create a method, we also add a 'self' parameter. |
| 159 |
nargs = len(sig.args) - sig.num_bitmap_args |
| 160 |
sig = FuncSignature( |
| 161 |
(RuntimeArg(SELF_NAME, object_rprimitive),) + sig.args[:nargs], sig.ret_type |
| 162 |
) |
| 163 |
call_fn_decl = FuncDecl("__call__", fn_info.callable_class.ir.name, builder.module_name, sig) |
| 164 |
call_fn_ir = FuncIR( |
| 165 |
call_fn_decl, args, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name |
| 166 |
) |
| 167 |
fn_info.callable_class.ir.methods["__call__"] = call_fn_ir |
| 168 |
fn_info.callable_class.ir.method_decls["__call__"] = call_fn_decl |
| 169 |
return call_fn_ir |
| 170 |
|
| 171 |
|
| 172 |
def add_get_to_callable_class(builder: IRBuilder, fn_info: FuncInfo) -> None: |
| 173 |
"""Generate the '__get__' method for a callable class.""" |
| 174 |
line = fn_info.fitem.line |
| 175 |
with builder.enter_method( |
| 176 |
fn_info.callable_class.ir, |
| 177 |
"__get__", |
| 178 |
object_rprimitive, |
| 179 |
fn_info, |
| 180 |
self_type=object_rprimitive, |
| 181 |
): |
| 182 |
instance = builder.add_argument("instance", object_rprimitive) |
| 183 |
builder.add_argument("owner", object_rprimitive) |
| 184 |
|
| 185 |
# If accessed through the class, just return the callable |
| 186 |
# object. If accessed through an object, create a new bound |
| 187 |
# instance method object. |
| 188 |
instance_block, class_block = BasicBlock(), BasicBlock() |
| 189 |
comparison = builder.translate_is_op( |
| 190 |
builder.read(instance), builder.none_object(line), "is", line |
| 191 |
) |
| 192 |
builder.add_bool_branch(comparison, class_block, instance_block) |
| 193 |
|
| 194 |
builder.activate_block(class_block) |
| 195 |
builder.add(Return(builder.self())) |
| 196 |
|
| 197 |
builder.activate_block(instance_block) |
| 198 |
builder.add( |
| 199 |
Return(builder.call_c(method_new_op, [builder.self(), builder.read(instance)], line)) |
| 200 |
) |
| 201 |
|
| 202 |
|
| 203 |
def instantiate_callable_class(builder: IRBuilder, fn_info: FuncInfo) -> Value: |
| 204 |
"""Create an instance of a callable class for a function. |
| 205 |
|
| 206 |
Calls to the function will actually call this instance. |
| 207 |
|
| 208 |
Note that fn_info refers to the function being assigned, whereas |
| 209 |
builder.fn_info refers to the function encapsulating the function |
| 210 |
being turned into a callable class. |
| 211 |
""" |
| 212 |
fitem = fn_info.fitem |
| 213 |
func_reg = builder.add(Call(fn_info.callable_class.ir.ctor, [], fitem.line)) |
| 214 |
|
| 215 |
# Set the environment attribute of the callable class to point at |
| 216 |
# the environment class defined in the callable class' immediate |
| 217 |
# outer scope. Note that there are three possible environment |
| 218 |
# class registers we may use. This depends on what the encapsulating |
| 219 |
# (parent) function is: |
| 220 |
# |
| 221 |
# - A nested function: the callable class is instantiated |
| 222 |
# from the current callable class' '__call__' function, and hence |
| 223 |
# the callable class' environment register is used. |
| 224 |
# - A generator function: the callable class is instantiated |
| 225 |
# from the '__next__' method of the generator class, and hence the |
| 226 |
# environment of the generator class is used. |
| 227 |
# - Regular function or comprehension scope: we use the environment |
| 228 |
# of the original function. Comprehension scopes are inlined (no |
| 229 |
# callable class), so they fall into this case despite is_nested. |
| 230 |
curr_env_reg = None |
| 231 |
if builder.fn_info.is_generator: |
| 232 |
curr_env_reg = builder.fn_info.generator_class.curr_env_reg |
| 233 |
elif builder.fn_info.is_nested and not builder.fn_info.is_comprehension_scope: |
| 234 |
curr_env_reg = builder.fn_info.callable_class.curr_env_reg |
| 235 |
elif builder.fn_info.contains_nested: |
| 236 |
curr_env_reg = builder.fn_info.curr_env_reg |
| 237 |
if curr_env_reg: |
| 238 |
builder.add(SetAttr(func_reg, ENV_ATTR_NAME, curr_env_reg, fitem.line)) |
| 239 |
# Initialize function wrapper for callable classes. As opposed to regular functions, |
| 240 |
# each instance of a callable class needs its own wrapper because they might be instantiated |
| 241 |
# inside other functions. |
| 242 |
if not fn_info.in_non_ext and fn_info.is_coroutine: |
| 243 |
builder.add_coroutine_setup_call(fn_info.callable_class.ir.name, func_reg) |
| 244 |
return func_reg |