|
| 1 | +"""Generate classes representing function environments (+ related operations).""" |
| 2 | + |
| 3 | +from typing import Optional, Union |
| 4 | + |
| 5 | +from mypy.nodes import FuncDef, SymbolNode |
| 6 | + |
| 7 | +from mypyc.common import SELF_NAME, ENV_ATTR_NAME |
| 8 | +from mypyc.ir.ops import Call, GetAttr, SetAttr, Value, Environment, AssignmentTargetAttr |
| 9 | +from mypyc.ir.rtypes import RInstance, object_rprimitive |
| 10 | +from mypyc.ir.class_ir import ClassIR |
| 11 | +from mypyc.irbuild.builder import IRBuilder |
| 12 | +from mypyc.irbuild.context import FuncInfo, ImplicitClass, GeneratorClass |
| 13 | + |
| 14 | + |
| 15 | +def setup_env_class(builder: IRBuilder) -> ClassIR: |
| 16 | + """Generates a class representing a function environment. |
| 17 | +
|
| 18 | + Note that the variables in the function environment are not actually populated here. This |
| 19 | + is because when the environment class is generated, the function environment has not yet |
| 20 | + been visited. This behavior is allowed so that when the compiler visits nested functions, |
| 21 | + it can use the returned ClassIR instance to figure out free variables it needs to access. |
| 22 | + The remaining attributes of the environment class are populated when the environment |
| 23 | + registers are loaded. |
| 24 | +
|
| 25 | + Returns a ClassIR representing an environment for a function containing a nested function. |
| 26 | + """ |
| 27 | + env_class = ClassIR('{}_env'.format(builder.fn_info.namespaced_name()), |
| 28 | + builder.module_name, is_generated=True) |
| 29 | + env_class.attributes[SELF_NAME] = RInstance(env_class) |
| 30 | + if builder.fn_info.is_nested: |
| 31 | + # If the function is nested, its environment class must contain an environment |
| 32 | + # attribute pointing to its encapsulating functions' environment class. |
| 33 | + env_class.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_infos[-2].env_class) |
| 34 | + env_class.mro = [env_class] |
| 35 | + builder.fn_info.env_class = env_class |
| 36 | + builder.classes.append(env_class) |
| 37 | + return env_class |
| 38 | + |
| 39 | + |
| 40 | +def finalize_env_class(builder: IRBuilder) -> None: |
| 41 | + """Generates, instantiates, and sets up the environment of an environment class.""" |
| 42 | + |
| 43 | + instantiate_env_class(builder) |
| 44 | + |
| 45 | + # Iterate through the function arguments and replace local definitions (using registers) |
| 46 | + # that were previously added to the environment with references to the function's |
| 47 | + # environment class. |
| 48 | + if builder.fn_info.is_nested: |
| 49 | + add_args_to_env(builder, local=False, base=builder.fn_info.callable_class) |
| 50 | + else: |
| 51 | + add_args_to_env(builder, local=False, base=builder.fn_info) |
| 52 | + |
| 53 | + |
| 54 | +def instantiate_env_class(builder: IRBuilder) -> Value: |
| 55 | + """Assigns an environment class to a register named after the given function definition.""" |
| 56 | + curr_env_reg = builder.add( |
| 57 | + Call(builder.fn_info.env_class.ctor, [], builder.fn_info.fitem.line) |
| 58 | + ) |
| 59 | + |
| 60 | + if builder.fn_info.is_nested: |
| 61 | + builder.fn_info.callable_class._curr_env_reg = curr_env_reg |
| 62 | + builder.add(SetAttr(curr_env_reg, |
| 63 | + ENV_ATTR_NAME, |
| 64 | + builder.fn_info.callable_class.prev_env_reg, |
| 65 | + builder.fn_info.fitem.line)) |
| 66 | + else: |
| 67 | + builder.fn_info._curr_env_reg = curr_env_reg |
| 68 | + |
| 69 | + return curr_env_reg |
| 70 | + |
| 71 | + |
| 72 | +def load_env_registers(builder: IRBuilder) -> None: |
| 73 | + """Loads the registers for the current FuncItem being visited. |
| 74 | +
|
| 75 | + Adds the arguments of the FuncItem to the environment. If the FuncItem is nested inside of |
| 76 | + another function, then this also loads all of the outer environments of the FuncItem into |
| 77 | + registers so that they can be used when accessing free variables. |
| 78 | + """ |
| 79 | + add_args_to_env(builder, local=True) |
| 80 | + |
| 81 | + fn_info = builder.fn_info |
| 82 | + fitem = fn_info.fitem |
| 83 | + if fn_info.is_nested: |
| 84 | + load_outer_envs(builder, fn_info.callable_class) |
| 85 | + # If this is a FuncDef, then make sure to load the FuncDef into its own environment |
| 86 | + # class so that the function can be called recursively. |
| 87 | + if isinstance(fitem, FuncDef): |
| 88 | + setup_func_for_recursive_call(builder, fitem, fn_info.callable_class) |
| 89 | + |
| 90 | + |
| 91 | +def load_outer_env(builder: IRBuilder, base: Value, outer_env: Environment) -> Value: |
| 92 | + """Loads the environment class for a given base into a register. |
| 93 | +
|
| 94 | + Additionally, iterates through all of the SymbolNode and AssignmentTarget instances of the |
| 95 | + environment at the given index's symtable, and adds those instances to the environment of |
| 96 | + the current environment. This is done so that the current environment can access outer |
| 97 | + environment variables without having to reload all of the environment registers. |
| 98 | +
|
| 99 | + Returns the register where the environment class was loaded. |
| 100 | + """ |
| 101 | + env = builder.add(GetAttr(base, ENV_ATTR_NAME, builder.fn_info.fitem.line)) |
| 102 | + assert isinstance(env.type, RInstance), '{} must be of type RInstance'.format(env) |
| 103 | + |
| 104 | + for symbol, target in outer_env.symtable.items(): |
| 105 | + env.type.class_ir.attributes[symbol.name] = target.type |
| 106 | + symbol_target = AssignmentTargetAttr(env, symbol.name) |
| 107 | + builder.environment.add_target(symbol, symbol_target) |
| 108 | + |
| 109 | + return env |
| 110 | + |
| 111 | + |
| 112 | +def load_outer_envs(builder: IRBuilder, base: ImplicitClass) -> None: |
| 113 | + index = len(builder.builders) - 2 |
| 114 | + |
| 115 | + # Load the first outer environment. This one is special because it gets saved in the |
| 116 | + # FuncInfo instance's prev_env_reg field. |
| 117 | + if index > 1: |
| 118 | + # outer_env = builder.fn_infos[index].environment |
| 119 | + outer_env = builder.builders[index].environment |
| 120 | + if isinstance(base, GeneratorClass): |
| 121 | + base.prev_env_reg = load_outer_env(builder, base.curr_env_reg, outer_env) |
| 122 | + else: |
| 123 | + base.prev_env_reg = load_outer_env(builder, base.self_reg, outer_env) |
| 124 | + env_reg = base.prev_env_reg |
| 125 | + index -= 1 |
| 126 | + |
| 127 | + # Load the remaining outer environments into registers. |
| 128 | + while index > 1: |
| 129 | + # outer_env = builder.fn_infos[index].environment |
| 130 | + outer_env = builder.builders[index].environment |
| 131 | + env_reg = load_outer_env(builder, env_reg, outer_env) |
| 132 | + index -= 1 |
| 133 | + |
| 134 | + |
| 135 | +def add_args_to_env(builder: IRBuilder, |
| 136 | + local: bool = True, |
| 137 | + base: Optional[Union[FuncInfo, ImplicitClass]] = None, |
| 138 | + reassign: bool = True) -> None: |
| 139 | + fn_info = builder.fn_info |
| 140 | + if local: |
| 141 | + for arg in fn_info.fitem.arguments: |
| 142 | + rtype = builder.type_to_rtype(arg.variable.type) |
| 143 | + builder.environment.add_local_reg(arg.variable, rtype, is_arg=True) |
| 144 | + else: |
| 145 | + for arg in fn_info.fitem.arguments: |
| 146 | + if is_free_variable(builder, arg.variable) or fn_info.is_generator: |
| 147 | + rtype = builder.type_to_rtype(arg.variable.type) |
| 148 | + assert base is not None, 'base cannot be None for adding nonlocal args' |
| 149 | + builder.add_var_to_env_class(arg.variable, rtype, base, reassign=reassign) |
| 150 | + |
| 151 | + |
| 152 | +def setup_func_for_recursive_call(builder: IRBuilder, fdef: FuncDef, base: ImplicitClass) -> None: |
| 153 | + """ |
| 154 | + Adds the instance of the callable class representing the given FuncDef to a register in the |
| 155 | + environment so that the function can be called recursively. Note that this needs to be done |
| 156 | + only for nested functions. |
| 157 | + """ |
| 158 | + # First, set the attribute of the environment class so that GetAttr can be called on it. |
| 159 | + prev_env = builder.fn_infos[-2].env_class |
| 160 | + prev_env.attributes[fdef.name] = builder.type_to_rtype(fdef.type) |
| 161 | + |
| 162 | + if isinstance(base, GeneratorClass): |
| 163 | + # If we are dealing with a generator class, then we need to first get the register |
| 164 | + # holding the current environment class, and load the previous environment class from |
| 165 | + # there. |
| 166 | + prev_env_reg = builder.add(GetAttr(base.curr_env_reg, ENV_ATTR_NAME, -1)) |
| 167 | + else: |
| 168 | + prev_env_reg = base.prev_env_reg |
| 169 | + |
| 170 | + # Obtain the instance of the callable class representing the FuncDef, and add it to the |
| 171 | + # current environment. |
| 172 | + val = builder.add(GetAttr(prev_env_reg, fdef.name, -1)) |
| 173 | + target = builder.environment.add_local_reg(fdef, object_rprimitive) |
| 174 | + builder.assign(target, val, -1) |
| 175 | + |
| 176 | + |
| 177 | +def is_free_variable(builder: IRBuilder, symbol: SymbolNode) -> bool: |
| 178 | + fitem = builder.fn_info.fitem |
| 179 | + return ( |
| 180 | + fitem in builder.free_variables |
| 181 | + and symbol in builder.free_variables[fitem] |
| 182 | + ) |
0 commit comments