-
Notifications
You must be signed in to change notification settings - Fork 21
/
base_handlers.py
332 lines (278 loc) · 10.6 KB
/
base_handlers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# -*- coding: utf-8 -*-
import ast
import logging
from types import ModuleType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Set,
Tuple,
Type,
Union,
cast,
)
from ipyflow.data_model.timestamp import Timestamp
from ipyflow.singletons import flow, tracer
from ipyflow.types import IMMUTABLE_PRIMITIVE_TYPES
if TYPE_CHECKING:
from ipyflow.data_model.symbol import Symbol
ExternalCallArgument = Tuple[Any, Set[Symbol]]
logger = logging.getLogger(__name__)
class HasGetitem(type):
"""
Mixin for indicating that a class has a __getitem__ method
"""
def __getitem__(cls, item):
return NotImplemented
class ExternalCallHandler(metaclass=HasGetitem):
not_yet_defined = object()
module: Optional[ModuleType] = None
caller_self: Any = None
function_or_method: Any = None
args: List["ExternalCallArgument"] = None
kwargs: Dict[str, "ExternalCallArgument"] = None
_arg_syms: Optional[Set["Symbol"]] = None
return_value: Any = not_yet_defined
stmt_node: ast.stmt = None
def __new__(cls, *args, **kwargs):
if cls is ExternalCallHandler:
raise TypeError(f"only children of '{cls.__name__}' may be instantiated")
return object.__new__(cls)
@classmethod
def create(cls, **kwargs) -> "ExternalCallHandler":
module = kwargs.pop("module", None)
caller_self = kwargs.pop("caller_self", None)
function_or_method = kwargs.pop("function_or_method", None)
call_node = kwargs.pop("call_node", None)
calling_symbol = kwargs.pop("calling_symbol", None)
return cls(
module=module,
caller_self=caller_self,
function_or_method=function_or_method,
call_node=call_node,
calling_symbol=calling_symbol,
)._initialize_impl(**kwargs)
def _initialize_impl(self, **kwargs) -> "ExternalCallHandler":
ret = self
for cls in self.__class__.mro():
if not hasattr(cls, "initialize"):
break
ret = cls.initialize(ret, **kwargs) or ret # type: ignore
return ret
def initialize(self, **_) -> Optional["ExternalCallHandler"]:
return self
def __init__(
self,
*,
module: Optional[ModuleType] = None,
caller_self: Any = None,
function_or_method: Any = None,
call_node: Optional[ast.Call] = None,
calling_symbol: Optional["Symbol"] = None,
) -> None:
self.module = module
self.caller_self = caller_self
self.function_or_method = function_or_method
self.args: List["ExternalCallArgument"] = []
self.kwargs: Dict[str, "ExternalCallArgument"] = {}
self._arg_syms: Optional[Set["Symbol"]] = None
self.return_value: Any = self.not_yet_defined
self.call_node = call_node
self.calling_symbol = calling_symbol
self.stmt_node = tracer().prev_trace_stmt_in_cur_frame.stmt_node
def __init_subclass__(cls):
external_call_handler_by_name[cls.__name__] = cls
@property
def caller_self_obj_id(self) -> Optional[int]:
return None if self.caller_self is None else id(self.caller_self)
@property
def arg_syms(self) -> Set["Symbol"]:
if self._arg_syms is None:
self._arg_syms = set().union(
*(arg[1] for arg in self.args + list(self.kwargs.values()))
)
return self._arg_syms
def process_arg(self, arg: Any) -> None:
pass
def _process_arg_impl(self, arg: "ExternalCallArgument") -> None:
self.args.append(arg)
self.process_arg(arg[0])
def process_args(self, args: List["ExternalCallArgument"]) -> None:
for arg in args:
self._process_arg_impl(arg)
def process_kwarg(self, kw: str, arg: Any) -> None:
pass
def _process_kwarg_impl(self, kw: str, arg: "ExternalCallArgument") -> None:
self.kwargs[kw] = arg
self.process_kwarg(kw, arg[0])
def process_kwargs(self, kwargs: Dict[str, "ExternalCallArgument"]) -> None:
for kw, arg in kwargs.items():
self._process_kwarg_impl(kw, arg)
def process_return(self, return_value: Any) -> None:
self.return_value = return_value
def _handle_impl(self) -> None:
Timestamp.update_usage_info(self.arg_syms)
result = self.handle()
if result is None or self.call_node is None:
return
symbols = (
cast(Iterable["Symbol"], result)
if hasattr(result, "__iter__")
else [cast("Symbol", result)]
)
tracer().node_id_to_loaded_symbols.setdefault(id(self.call_node), []).extend(
symbols
)
def mutate_caller(self, should_propagate: bool) -> None:
if self.caller_self is None:
return
if self.calling_symbol is None:
syms_to_mutate = []
if isinstance(self.call_node.func, ast.Attribute) and isinstance(
self.call_node.func.value, ast.Name
):
syms_to_mutate = [
sym
for sym in flow().aliases.get(self.caller_self_obj_id, [])
if sym.name == self.call_node.func.value.id
]
for sym in syms_to_mutate:
self._mutate_calling_symbol(sym, should_propagate=should_propagate)
if len(syms_to_mutate) == 0:
self.mutate_aliases(
self.caller_self_obj_id, should_propagate=should_propagate
)
else:
self._mutate_calling_symbol(
self.calling_symbol, should_propagate=should_propagate
)
def mutate_module(self, should_propagate: bool) -> None:
if self.module is None:
return
self.mutate_aliases(id(self.module), should_propagate=should_propagate)
def mutate_aliases(self, obj_id: Optional[int], should_propagate: bool) -> None:
mutated_syms = flow().aliases.get(obj_id, set())
for sym in mutated_syms:
self._mutate_calling_symbol(sym, should_propagate=should_propagate)
def _mutate_calling_symbol(self, sym: "Symbol", should_propagate: bool) -> None:
sym.update_deps(
self.arg_syms,
overwrite=False,
mutated=True,
propagate_to_namespace_descendents=should_propagate,
refresh=should_propagate,
)
def handle(self) -> Optional[Union["Symbol", Iterable["Symbol"]]]:
pass
external_call_handler_by_name: Dict[str, Type[ExternalCallHandler]] = {}
REGISTERED_HANDLER_BY_FUNCTION: Dict[Callable, Type[ExternalCallHandler]] = {}
REGISTERED_HANDLER_BY_METHOD: Dict[Tuple[type, str], Type[ExternalCallHandler]] = {}
class NoopCallHandler(ExternalCallHandler):
pass
# TODO: use dsl for these instead
ARG_MUTATION_EXCEPTED_MODULES = {
"alt",
"altair",
"display",
"logging",
"matplotlib",
"pyplot",
"plot",
"plt",
"seaborn",
"sns",
"widget",
}
class StandardMutation(ExternalCallHandler):
def _maybe_mutate_caller(self) -> None:
if self.return_value is not None and self.caller_self is not self.return_value:
return
self.mutate_caller(should_propagate=True)
def handle(self) -> None:
if self.caller_self is not None:
self._maybe_mutate_caller()
elif self.module is not None and self.return_value is None:
self.mutate_module(should_propagate=True)
if len(self.args) == 0:
return
# FIXME: extremely hacky
if (self.module.__name__ or "").split(".")[
0
] in ARG_MUTATION_EXCEPTED_MODULES:
return
# FIXME: extremely hacky here too
first_arg_obj, first_arg_syms = self.args[0]
if isinstance(first_arg_obj, (list, set, dict) + IMMUTABLE_PRIMITIVE_TYPES):
return
depending_on_first_arg = []
for obj, syms in self.args[1:]:
filtered_syms = {
sym
for sym in syms
if any(first_sym in sym.parents for first_sym in first_arg_syms)
}
if len(filtered_syms) > 0:
depending_on_first_arg.append((obj, filtered_syms))
self.args = [self.args[0]] + depending_on_first_arg
self._arg_syms = None
ArgMutate.handle(self) # type: ignore
class CallerMutation(ExternalCallHandler):
def handle(self) -> None:
self.mutate_caller(should_propagate=True)
class CallerUpsert(ExternalCallHandler):
def handle(self) -> None:
for module_sym in flow().aliases.get(id(self.caller_self), []):
module_sym.update_deps(
self.arg_syms,
overwrite=True,
propagate_to_namespace_descendents=True,
refresh=True,
)
tracer().pending_usage_updates_by_sym.pop(module_sym, None)
class ModuleMutation(ExternalCallHandler):
def handle(self) -> None:
self.mutate_module(should_propagate=True)
class ModuleUpsert(ExternalCallHandler):
def handle(self) -> None:
for module_sym in flow().aliases.get(id(self.module), []):
module_sym.update_deps(
self.arg_syms,
overwrite=True,
propagate_to_namespace_descendents=True,
refresh=True,
)
tracer().pending_usage_updates_by_sym.pop(module_sym, None)
class NamespaceClear(StandardMutation):
def handle(self) -> None:
super().handle()
mutated_sym = flow().get_first_full_symbol(self.caller_self_obj_id)
if mutated_sym is None:
return
namespace = mutated_sym.namespace
if namespace is None:
return
for name in sorted(
(
sym.name
for sym in namespace.all_symbols_this_indentation(
exclude_class=True, is_subscript=True
)
),
reverse=True,
):
namespace.delete_symbol_for_name(name, is_subscript=True)
class MutatingMethodEventNotYetImplemented(ExternalCallHandler):
pass
class ArgMutate(ExternalCallHandler):
def handle(self) -> None:
for mutated_sym in self.arg_syms:
if mutated_sym is None or mutated_sym.is_anonymous:
continue
# TODO: happens when module mutates args
# should we add module as a dep in this case?
mutated_sym.update_deps(set(), overwrite=False, mutated=True)