-
Notifications
You must be signed in to change notification settings - Fork 20
/
ipyflow_tracer.py
1703 lines (1601 loc) · 67 KB
/
ipyflow_tracer.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import ast
import functools
import logging
import re
import symtable
import sys
from collections import defaultdict
from contextlib import contextmanager
from types import FrameType, ModuleType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Union,
cast,
)
import pyccolo as pyc
from IPython import get_ipython
from ipyflow.analysis.live_refs import compute_live_dead_symbol_refs
from ipyflow.analysis.symbol_ref import resolve_slice_to_constant
from ipyflow.annotations.compiler import compile_and_register_handlers_for_module
from ipyflow.api.lift import code as api_code
from ipyflow.api.lift import deps as api_deps
from ipyflow.api.lift import has_tag as api_has_tag
from ipyflow.api.lift import lift as api_lift
from ipyflow.api.lift import rdeps as api_rdeps
from ipyflow.api.lift import rusers as api_rusers
from ipyflow.api.lift import set_tag as api_set_tag
from ipyflow.api.lift import timestamp as api_timestamp
from ipyflow.api.lift import unset_tag as api_unset_tag
from ipyflow.api.lift import users as api_users
from ipyflow.api.lift import watchpoints as api_watchpoints
from ipyflow.data_model.cell import cells
from ipyflow.data_model.namespace import Namespace
from ipyflow.data_model.scope import Scope
from ipyflow.data_model.statement import Statement
from ipyflow.data_model.symbol import Symbol
from ipyflow.data_model.timestamp import Timestamp
from ipyflow.models import symbols as api_symbols
from ipyflow.singletons import SingletonBaseTracer, flow, shell
from ipyflow.tracing.external_calls import resolve_external_call
from ipyflow.tracing.external_calls.base_handlers import ExternalCallHandler
from ipyflow.tracing.flow_ast_rewriter import DataflowAstRewriter
from ipyflow.tracing.symbol_resolver import resolve_rval_symbols
from ipyflow.tracing.utils import match_container_obj_or_namespace_with_literal_nodes
from ipyflow.types import SubscriptIndices, SupportedIndexType
from ipyflow.utils.misc_utils import is_project_file
if TYPE_CHECKING:
import astunparse
elif hasattr(ast, "unparse"):
astunparse = ast
else:
import astunparse
AttrSubVal = SupportedIndexType
NodeId = int
ObjId = int
SavedStoreData = Tuple[Namespace, Any, AttrSubVal, bool]
SavedDelData = Tuple[Namespace, Any, AttrSubVal, bool]
SavedComplexSymbolLoadData = Tuple[Namespace, Any, AttrSubVal, bool, Optional[str]]
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
reactive_spec = pyc.AugmentationSpec(
aug_type=pyc.AugmentationType.prefix, token="$", replacement=""
)
cascading_reactive_spec = pyc.AugmentationSpec(
aug_type=pyc.AugmentationType.prefix, token="$$", replacement=""
)
blocking_spec = pyc.AugmentationSpec(
aug_type=pyc.AugmentationType.prefix, token="$:", replacement=""
)
class ModuleIniter(pyc.BaseTracer):
@pyc.register_raw_handler(pyc.init_module)
def init_cell(self, _obj, _node_id, frame: FrameType, *_, **__):
flow().set_name_to_cell_num_mapping(frame)
for tracer in pyc._TRACER_STACK:
tracer._tracing_enabled_files.add(frame.f_code.co_filename)
@property
def should_patch_meta_path(self) -> bool:
return False
class StackFrameManager(SingletonBaseTracer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.call_depth = 0
self.external_call_depth = 0
def multiple_threads_allowed(self) -> bool:
# TODO: we should also provide a way to prevent threads from running on instrumented ASTs
return False
@pyc.register_raw_handler((pyc.call, pyc.return_))
def handle_first_ipython_frame(
self,
_ret: Any,
_node_id: None,
frame: FrameType,
event: pyc.TraceEvent,
*_,
**__,
):
if frame.f_code.co_name == "<traced_lambda>":
return pyc.SkipAll
flow_ = flow()
# IPython quirk -- every line in outer scope apparently wrapped in lambda
# We want to skip the outer 'call' and 'return' for these
frame_filename = frame.f_code.co_filename
if event == pyc.call:
self.call_depth += 1
self.external_call_depth += not flow_.is_cell_file(
frame_filename
) and not is_project_file(frame_filename)
if self.call_depth == 1:
return pyc.SkipAll
elif event == pyc.return_:
self.call_depth -= 1
self.external_call_depth -= not flow_.is_cell_file(
frame_filename
) and not is_project_file(frame_filename)
self.call_depth = max(self.call_depth, 0)
self.external_call_depth = max(self.external_call_depth, 0)
if self.call_depth == 0:
return pyc.SkipAll
@property
def should_patch_meta_path(self) -> bool:
return False
_FILTERED_PATH_REGEX = re.compile(
rf"[/\\]({'|'.join(['IPython', 'ipykernel', '_?pytest.*', 'pluggy', 'test'])})[/\\]"
)
@classmethod
def get_user_call_stack_depth(cls, frame: FrameType) -> int:
flow_ = flow()
user_call_depth = 0
while frame is not None:
filename = frame.f_code.co_filename
if flow_.is_cell_file(filename) or (
not is_project_file(filename)
and not cls._FILTERED_PATH_REGEX.search(filename)
and "scripts/test_runner.py" not in filename
):
user_call_depth += 1
frame = frame.f_back
return user_call_depth
class DataflowTracer(StackFrameManager):
ast_rewriter_cls = DataflowAstRewriter
def should_propagate_handler_exception(
self, evt: pyc.TraceEvent, exc: Exception
) -> bool:
return flow().is_dev_mode
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._tracing_enabled_files.discard(self.defined_file)
with self.persistent_fields():
self.reactive_node_ids: Set[int] = self.augmented_node_ids_by_spec[
reactive_spec
]
self.cascading_reactive_node_ids: Set[
int
] = self.augmented_node_ids_by_spec[cascading_reactive_spec]
self.blocking_node_ids: Set[int] = self.augmented_node_ids_by_spec[
blocking_spec
]
self.tracing_disabled_since_last_stmt = False
self.tracing_disabled_since_last_module_stmt = False
self.guards_pending_deactivation: Set[str] = set()
self._module_stmt_counter = 0
self._saved_stmt_ret_expr: Optional[Any] = None
self._seen_loop_ids: Set[NodeId] = set()
self._seen_functions_ids: Set[NodeId] = set()
self.prev_event: Optional[pyc.TraceEvent] = None
self.prev_trace_stmt: Optional[Statement] = None
self.traced_statements: Dict[NodeId, Statement] = {}
self.node_id_to_loaded_symbols: Dict[NodeId, List[Symbol]] = {}
self.node_id_to_saved_store_data: Dict[NodeId, SavedStoreData] = {}
self.node_id_to_saved_live_subscript_refs: Dict[NodeId, Set[Symbol]] = {}
self.node_id_to_saved_del_data: Dict[NodeId, SavedDelData] = {}
self.node_id_to_loaded_literal_scope: Dict[NodeId, Namespace] = {}
self.node_id_to_saved_dict_key: Dict[NodeId, Any] = {}
self.this_stmt_updated_symbols: Set[Symbol] = set()
self.pending_usage_updates_by_sym: Dict[Symbol, bool] = {}
self.cur_cell_symtab: Optional[symtable.SymbolTable] = None
self.tracing_disabled_user_call_depth = -1
self.calling_symbol: Optional[Symbol] = None
self.call_stack: pyc.TraceStack = self.make_stack()
with self.call_stack.register_stack_state():
# everything here should be copyable
self.prev_trace_stmt_in_cur_frame: Optional[Statement] = None
self.prev_node_id_in_cur_frame: Optional[NodeId] = None
self.external_calls: List[ExternalCallHandler] = []
self.is_external_call_pending_return: bool = False
self.saved_assign_rhs_obj: Optional[Any] = None
# this one gets set regardless of whether tracing enabled
self.next_stmt_node_id: Optional[NodeId] = None
self.pending_class_namespaces: List[Namespace] = []
# the next entries are only used when tracing gets re-enabled
self.saved_call_depth = 0
self.saved_external_call_depth = 0
self.user_call_depth = 1
with self.call_stack.needing_manual_initialization():
self.cur_frame_original_scope: Scope = flow().global_scope
self.active_scope: Scope = flow().global_scope
self.inside_anonymous_call = False
self.lexical_call_stack: pyc.TraceStack = self.make_stack()
with self.lexical_call_stack.register_stack_state():
self.cur_function: Optional[Any] = None
self.num_args_seen = 0
self.first_obj_id_in_chain: Optional[ObjId] = None
self.top_level_node_id_for_chain: Optional[NodeId] = None
self.saved_complex_symbol_load_data: Optional[
SavedComplexSymbolLoadData
] = None
self.prev_node_id_in_cur_frame_lexical: Optional[NodeId] = None
self.external_call_candidate: Optional[ExternalCallHandler] = None
self.lexical_literal_stack: pyc.TraceStack = self.make_stack()
with self.lexical_literal_stack.register_stack_state():
# `None` means use 'cur_frame_original_scope'
self.active_literal_scope: Optional[Namespace] = None
def init_symtab(self) -> None:
try:
self.cur_cell_symtab = symtable.symtable(
cells().current_cell().sanitized_content(),
f"<cell-{cells().exec_counter()}>",
"exec",
)
except Exception:
pass
@contextmanager
def dataflow_tracing_disabled(self) -> Generator[None, None, None]:
is_tracing_enabled = self.is_tracing_enabled
try:
if is_tracing_enabled:
self._disable_tracing()
yield
finally:
if is_tracing_enabled and not self.is_tracing_enabled:
self._enable_tracing()
def make_tracing_disabled_func(
self,
orig_func: Callable[[Any], Any],
kwarg_transforms: Optional[Dict[str, Tuple[Any, Callable[[Any], Any]]]] = None,
) -> Callable[[Any], Any]:
kwarg_transforms = kwarg_transforms or {}
@functools.wraps(orig_func)
def new_func(*args: Any, **kwargs: Any) -> Any:
for name, (default, transform) in kwarg_transforms.items():
kwargs[name] = transform(kwargs.get(name, default))
with self.dataflow_tracing_disabled():
return orig_func(*args, **kwargs)
return new_func
@contextmanager
def dataflow_tracing_disabled_patch(
self,
obj: Any,
attr: str,
kwarg_transforms: Optional[Dict[str, Tuple[Any, Callable[[Any], Any]]]] = None,
) -> Generator[None, None, None]:
orig_func = getattr(obj, attr)
new_func = self.make_tracing_disabled_func(
orig_func, kwarg_transforms=kwarg_transforms
)
try:
setattr(obj, attr, new_func)
yield
finally:
setattr(obj, attr, orig_func)
@property
def syntax_augmentation_specs(self) -> List[pyc.AugmentationSpec]:
return [blocking_spec, cascading_reactive_spec, reactive_spec]
@property
def should_patch_meta_path(self) -> bool:
return True
def module_stmt_counter(self) -> int:
return self._module_stmt_counter
# TODO: use stack mechanism to automate this?
def after_stmt_reset_hook(self) -> None:
self.is_external_call_pending_return = False
self.external_calls.clear()
self.external_call_candidate = None
self.active_scope = self.cur_frame_original_scope
self.first_obj_id_in_chain = None
self.top_level_node_id_for_chain = None
self.saved_complex_symbol_load_data = None
self.active_literal_scope = None
self.node_id_to_loaded_literal_scope.clear()
self.node_id_to_saved_dict_key.clear()
self.prev_node_id_in_cur_frame = None
self.saved_assign_rhs_obj = None
flow().updated_symbols |= self.this_stmt_updated_symbols
self.this_stmt_updated_symbols.clear()
self._seen_functions_ids.clear()
self.calling_symbol = None
for sym, exclude_ns in self.pending_usage_updates_by_sym.items():
sym.update_usage_info(exclude_ns=exclude_ns)
self.pending_usage_updates_by_sym.clear()
# don't clear the lexical stacks because line magics can
# mess with when an 'after_stmt' gets emitted, and anyway
# these should be pushed / popped appropriately by ast events
def _deactivate_guards(self) -> None:
for guard in self.guards_pending_deactivation:
self.deactivate_guard(guard)
self.guards_pending_deactivation.clear()
def finish_cell_hook(self) -> None:
for stmt in self.traced_statements.values():
stmt.mark_finished()
self._deactivate_guards()
def _handle_call_transition(self, trace_stmt: Statement, frame: FrameType):
if (
self.external_call_depth
>= flow().mut_settings.max_external_call_depth_for_tracing
):
self._tracked_disable_tracing(frame)
return
# ensures we only handle del's and not delitem's
self.node_id_to_saved_del_data.clear()
new_scope = trace_stmt.get_post_call_scope(trace_stmt.frame)
with self.call_stack.push():
# TODO: figure out a better way to determine if we're inside a lambda
# could this one lead to a false negative if a lambda is in the default of a function def kwarg?
self.inside_anonymous_call = not isinstance(
trace_stmt.stmt_node,
(ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef),
)
self.cur_frame_original_scope = new_scope
self.active_scope = new_scope
self.user_call_depth = max(self.get_user_call_stack_depth(frame), 1)
self.saved_call_depth = self.call_depth
self.saved_external_call_depth = self.external_call_depth
self.prev_trace_stmt_in_cur_frame = self.prev_trace_stmt = trace_stmt
def _check_prev_stmt_done_executing_hook(
self, event: pyc.TraceEvent, trace_stmt: Statement
):
if event == pyc.after_stmt and trace_stmt.is_initial_frame_stmt():
while len(self.call_stack) > 0:
# potentially necessary if tracing was disabled
self.call_stack.pop()
num_finished_stmts = 0
if (
event == pyc.return_
and self.prev_event
not in (
pyc.call,
pyc.exception,
)
and self.prev_trace_stmt is not None
):
# ensuring prev != call ensures we're not inside of a stmt with multiple calls (such as map w/ lambda)
self.prev_trace_stmt.finished_execution_hook()
num_finished_stmts += 1
if event == pyc.after_stmt or (
event == pyc.return_ and isinstance(trace_stmt.stmt_node, ast.Return)
):
trace_stmt.finished_execution_hook()
num_finished_stmts += 1
if num_finished_stmts > 0:
self.after_stmt_reset_hook()
def _tracked_enable_tracing(self, check_disabled: bool = True) -> None:
self.tracing_disabled_user_call_depth = -1
self._enable_tracing(check_disabled=check_disabled)
def _tracked_disable_tracing(
self, frame: FrameType, check_enabled: bool = True
) -> None:
self.tracing_disabled_since_last_module_stmt = True
self.tracing_disabled_since_last_stmt = True
if self.is_tracing_enabled:
self.tracing_disabled_user_call_depth = self.get_user_call_stack_depth(
frame
)
self._disable_tracing(check_enabled=check_enabled)
def _handle_return_transition(
self, trace_stmt: Statement, frame: FrameType, ret: Any
):
try:
inside_anonymous_call = self.inside_anonymous_call
try:
return_to_stmt: Statement = self.call_stack.get_field(
"prev_trace_stmt_in_cur_frame"
)
except IndexError:
# then the first call was triggered from inside library code;
# skip the transition and disable tracing in case this call
# happens in a loop; we won't catch it in our normal tracing
# disabler since it's the first call
self._tracked_disable_tracing(frame)
return
assert return_to_stmt is not None
if self.prev_event == pyc.exception:
# exception events are followed by return events until we hit an except clause
# no need to track dependencies in this case
return
if isinstance(return_to_stmt.stmt_node, ast.ClassDef):
return_to_stmt.class_scope = cast(
Namespace, self.cur_frame_original_scope
)
elif (
isinstance(trace_stmt.stmt_node, ast.Return) or inside_anonymous_call
) and not trace_stmt.lambda_call_point_deps_done_once:
trace_stmt.lambda_call_point_deps_done_once = True
maybe_lambda_sym = flow().statement_to_func_sym.get(
id(trace_stmt.stmt_node), None
)
maybe_lambda_node = None
if maybe_lambda_sym is not None:
maybe_lambda_node = maybe_lambda_sym.func_def_stmt
if (
inside_anonymous_call
and maybe_lambda_node is not None
and isinstance(maybe_lambda_node, ast.Lambda)
):
rvals = resolve_rval_symbols(maybe_lambda_node.body)
else:
rvals = resolve_rval_symbols(trace_stmt.stmt_node)
sym_to_attach = None
if len(rvals) == 1:
sym_to_attach = next(iter(rvals))
if sym_to_attach.obj_id != id(ret):
sym_to_attach = None
if sym_to_attach is None and len(rvals) > 0:
sym_to_attach = (
self.cur_frame_original_scope.upsert_symbol_for_name(
"<return_sym_%d>" % id(ret),
ret,
rvals,
trace_stmt.stmt_node,
is_anonymous=True,
)
)
if sym_to_attach is None:
return
return_to_node_id = self.call_stack.get_field(
"prev_node_id_in_cur_frame"
)
# logger.error("prev seen: %s", ast.dump(self.ast_node_by_id[return_to_node_id]))
try:
call_node_id = self.call_stack.get_field(
"lexical_call_stack"
).get_field("prev_node_id_in_cur_frame_lexical")
call_node = cast(ast.Call, self.ast_node_by_id[call_node_id])
# logger.error("prev seen outer: %s", ast.dump(self.ast_node_by_id[call_node_id]))
total_args = len(call_node.args) + len(call_node.keywords)
num_args_seen = self.call_stack.get_field("num_args_seen")
logger.warning("num args seen: %d", num_args_seen)
if total_args == num_args_seen:
return_to_node_id = call_node_id
else:
assert num_args_seen < total_args
if num_args_seen < len(call_node.args):
return_to_node_id = id(call_node.args[num_args_seen])
else:
return_to_node_id = id(
call_node.keywords[
num_args_seen - len(call_node.args)
].value
)
except IndexError:
pass
# logger.error("use node %s", ast.dump(self.ast_node_by_id[return_to_node_id]))
self.node_id_to_loaded_symbols.setdefault(return_to_node_id, []).append(
sym_to_attach
)
finally:
if self.is_tracing_enabled:
self.call_stack.pop()
if (
flow().is_dev_mode
and not self.tracing_disabled_since_last_stmt
and len(self.call_stack) == 0
):
assert self.call_depth == 1, "got %s" % self.call_depth
def state_transition_hook(
self,
event: pyc.TraceEvent,
trace_stmt: Statement,
frame: FrameType,
ret: Any,
):
self._check_prev_stmt_done_executing_hook(event, trace_stmt)
if event == pyc.call:
self._handle_call_transition(trace_stmt, frame)
if event == pyc.return_:
self._handle_return_transition(trace_stmt, frame, ret)
self.prev_trace_stmt = trace_stmt
self.prev_event = event
@staticmethod
def _partial_resolve_ref(ref: Union[str, int, ast.AST]) -> Union[str, int]:
if isinstance(ref, ast.Starred):
ref = ref.value
if isinstance(ref, ast.Name):
ref = ref.id
if isinstance(ref, ast.AST):
ref = id(ref)
return ref
def _resolve_store_data_for_simple_target(self, target: str, frame: FrameType):
scope = self.cur_frame_original_scope
lut = frame.f_locals
if scope.symtab is not None:
try:
target_sym = scope.symtab.lookup(target)
# this nonsense is necessary because the "is_nonlocal" method
# is not available on Python <= 3.7;
# the below check seems to work consistently across all Python versions
is_nonlocal = getattr(
target_sym,
"is_nonlocal",
lambda: not target_sym.is_global()
and target_sym.is_assigned()
and target_sym.is_free(),
)()
if is_nonlocal:
scope = scope.parent_scope
elif target_sym.is_global():
lut = frame.f_globals
scope = flow().global_scope
except KeyError:
pass
try:
obj = lut[target]
except KeyError:
obj = frame.f_globals[target]
scope = flow().global_scope
return scope, target, obj, False, set()
def resolve_store_data_for_target(
self, target: Union[str, int, ast.AST], frame: FrameType
) -> Tuple[Scope, AttrSubVal, Any, bool, Set[Symbol]]:
resolved_target = self._partial_resolve_ref(target)
if isinstance(resolved_target, str):
return self._resolve_store_data_for_simple_target(resolved_target, frame)
try:
(
scope,
obj,
attr_or_sub,
is_subscript,
) = self.node_id_to_saved_store_data.pop(resolved_target)
except KeyError:
if not self.tracing_disabled_since_last_stmt:
raise
if not isinstance(target, ast.Subscript) or not isinstance(
target.value, ast.Name
):
raise
# special handling for simple subscripts
is_subscript = True
obj = frame.f_locals.get(target.value.id)
if obj is None:
raise
scope = flow().namespaces.get(id(obj))
if scope is None:
raise
sliceval = resolve_slice_to_constant(target)
if isinstance(sliceval, ast.Name):
attr_or_sub = frame.f_locals.get(sliceval.id)
else:
attr_or_sub = sliceval
if attr_or_sub is None:
raise
if isinstance(obj, (dict, list)) and (
not self.tracing_disabled_since_last_stmt
or self.saved_assign_rhs_obj is not None
):
# we can be reasonably sure that the object on the rhs is the same thing
# that gets stashed in `obj` for these cases, so use it instead of doing
# the lookup (which may have side effects) to reduce intrusiveness
attr_or_sub_obj = self.saved_assign_rhs_obj
else:
attr_or_sub_obj = flow().retrieve_namespace_attr_or_sub(
obj, attr_or_sub, is_subscript
)
if attr_or_sub_obj is None:
scope_to_use = scope
else:
scope_to_use = scope.get_earliest_ancestor_containing(
id(attr_or_sub_obj), is_subscript
)
if scope_to_use is None:
# Nobody before `scope` has it, so we'll insert it at this level
scope_to_use = scope
return (
scope_to_use,
attr_or_sub,
attr_or_sub_obj,
is_subscript,
self.node_id_to_saved_live_subscript_refs.pop(resolved_target, set()),
)
def resolve_del_data_for_target(
self, target: Union[str, int, ast.AST]
) -> Tuple[Scope, Optional[Any], AttrSubVal, bool]:
target = self._partial_resolve_ref(target)
if isinstance(target, str):
return self.cur_frame_original_scope, None, target, False
(scope, obj, attr_or_sub, is_subscript) = self.node_id_to_saved_del_data[target]
return scope, obj, attr_or_sub, is_subscript
def resolve_loaded_symbols(
self, symbol_ref: Union[str, int, ast.AST, Symbol]
) -> List[Symbol]:
if isinstance(symbol_ref, Symbol):
return [symbol_ref]
symbol_ref = self._partial_resolve_ref(symbol_ref)
if isinstance(symbol_ref, int):
return self.node_id_to_loaded_symbols.get(symbol_ref, [])
elif isinstance(symbol_ref, str):
ret = self.cur_frame_original_scope.lookup_symbol_by_name(symbol_ref)
if ret is None:
return []
else:
return [ret]
else:
return []
def resolve_symbols(self, symbol_refs: Set[Union[str, int, Symbol]]) -> Set[Symbol]:
symbols = set()
for ref in symbol_refs:
symbols.update(self.resolve_loaded_symbols(ref))
return symbols
def _get_namespace_for_obj(
self, obj: Any, obj_name: Optional[str] = None
) -> Namespace:
obj_id = id(obj)
ns = flow().namespaces.get(obj_id)
if ns is not None:
return ns
class_scope = flow().namespaces.get(id(obj.__class__), None)
if class_scope is not None:
# logger.warning(
# 'found class scope %s containing %s',
# class_scope, list(class_scope.all_symbols_this_indentation())
# )
ns = class_scope.clone(obj)
if obj_name is not None:
ns.scope_name = obj_name
else:
# print('no scope for class', obj.__class__)
try:
scope_name = (
flow().get_first_full_symbol(obj_id).name
if obj_name is None
else obj_name
)
except AttributeError:
scope_name = "<unknown namespace>"
ns = Namespace(obj, scope_name, parent_scope=None)
# FIXME: brittle strategy for determining parent scope of obj
frame = self.prev_trace_stmt_in_cur_frame.frame
if ns.parent_scope is None and frame is not None:
if obj_name is not None and obj_name not in frame.f_locals:
parent_scope = flow().global_scope
else:
parent_scope = self.active_scope
ns.parent_scope = parent_scope
return ns
def create_if_not_exists_module_symbol(
self,
module_or_function: Any,
node: ast.AST,
is_load: bool = True,
is_named: bool = False,
) -> Optional[Symbol]:
# TODO: upsert modules / namespaces hierarchically
if isinstance(module_or_function, ModuleType):
module = module_or_function
else:
module = getattr(module_or_function, "__module__", None)
if module is None:
# to handle numpy attributes
module = getattr(
getattr(
getattr(module_or_function, "__self__", None), "__class__", None
),
"__module__",
None,
)
module = sys.modules.get(cast(str, module))
if module is None:
return None
module_name = module.__name__
if module_name in (None, "builtins", "__main__"):
return None
is_first = True
cur_scope = self.cur_frame_original_scope
up_to_component = ""
symbol = None
components = module_name.split(".")
for idx, component in enumerate(components):
if is_first:
up_to_component = component
else:
up_to_component = f"{up_to_component}.{component}"
module = sys.modules.get(up_to_component)
if module is None:
return None
sym_name = component
if is_first and not is_named and not sym_name.startswith("<"):
sym_name = f"<{sym_name}>"
symbol = next(iter(flow().aliases.get(id(module), {None})))
if symbol is None:
symbol = cur_scope.upsert_symbol_for_name(
sym_name,
module,
set(),
self.prev_trace_stmt_in_cur_frame.stmt_node,
is_subscript=False,
is_module=True,
propagate=False,
implicit=not isinstance(node, (ast.Import, ast.ImportFrom)),
symbol_node=node,
)
is_first = False
if idx == len(components) - 1:
break
symbol_namespace = symbol.namespace
if symbol_namespace is None:
cur_scope = Namespace(module, component, parent_scope=cur_scope)
else:
cur_scope = symbol_namespace
if is_load and not symbol.is_implicit:
self.node_id_to_loaded_symbols.setdefault(id(node), []).append(symbol)
return symbol
def _clear_info_and_maybe_lookup_or_create_complex_symbol(
self, obj_attr_or_sub: Any, node: ast.AST
) -> Optional[Symbol]:
if self.saved_complex_symbol_load_data is None:
return None
(
scope,
obj,
attr_or_subscript,
is_subscript,
*_,
) = self.saved_complex_symbol_load_data
self.saved_complex_symbol_load_data = None
sym = scope.lookup_symbol_by_name_this_indentation(
attr_or_subscript,
is_subscript=is_subscript,
skip_cloned_lookup=True,
)
logger.warning("found sym %s in scope %s", sym, scope)
if sym is None:
parent = scope.lookup_symbol_by_name_this_indentation(
attr_or_subscript,
is_subscript=is_subscript,
skip_cloned_lookup=False,
)
parents = set() if parent is None else {parent}
is_default_dict = isinstance(obj, defaultdict)
sym = scope.upsert_symbol_for_name(
attr_or_subscript,
obj_attr_or_sub,
parents,
self.prev_trace_stmt_in_cur_frame.stmt_node,
is_subscript=is_subscript,
propagate=is_default_dict,
implicit=not is_default_dict,
symbol_node=node,
)
elif sym.obj_id != id(obj_attr_or_sub):
sym.update_obj_ref(obj_attr_or_sub)
self.create_if_not_exists_module_symbol(obj_attr_or_sub, node, is_load=False)
return sym
@pyc.register_raw_handler(pyc.after_import)
def after_import(self, *_, module: ModuleType, **__):
compile_and_register_handlers_for_module(module)
if getattr(module, "__name__", "") == "numpy":
if TYPE_CHECKING:
import numpy
else:
numpy = module
# TODO: convert these to Python ints when used on Python objects
SubscriptIndices.types += (numpy.int32, numpy.int64)
@pyc.register_raw_handler(
(
pyc.before_call,
pyc.before_attribute_load,
pyc.before_attribute_store,
pyc.before_attribute_del,
pyc.before_subscript_load,
pyc.before_subscript_store,
pyc.before_subscript_del,
)
)
def _save_node_id(self, _obj, node_id: NodeId, frame, *_, **__):
self.prev_node_id_in_cur_frame = node_id
self.prev_node_id_in_cur_frame_lexical = node_id
# @pyc.register_raw_handler((pyc.before_for_loop_body, pyc.before_while_loop_body))
# def before_loop_body(self, _obj: Any, loop_id: NodeId, *_, **__):
# ret = self.is_tracing_enabled and loop_id not in self._seen_loop_ids
# if ret:
# self._seen_loop_ids.add(loop_id)
# return ret
@pyc.register_raw_handler(
(
pyc.after_for_loop_iter,
pyc.after_while_loop_iter,
pyc.after_comprehension_if,
pyc.after_comprehension_elt,
pyc.after_dict_comprehension_key,
pyc.after_dict_comprehension_value,
)
)
def after_loop_iter(self, _obj, _node, frame: FrameType, *_, guard: str, **__):
self.activate_guard(guard)
self.guards_pending_deactivation.add(guard)
self._tracked_disable_tracing(frame, check_enabled=False)
# @pyc.register_raw_handler(pyc.after_function_execution)
# def after_function_exec(self, _obj: Any, _loop_id: NodeId, *_, guard: str, **__):
# self.activate_guard(guard)
@pyc.register_raw_handler(pyc.after_assign_rhs)
@pyc.skip_when_tracing_disabled
def after_assign_rhs(self, obj: Any, *_, **__):
self.saved_assign_rhs_obj = obj
@pyc.register_raw_handler(pyc.after_subscript_slice)
@pyc.skip_when_tracing_disabled
def after_subscript_slice(self, _obj: Any, node_id: NodeId, *__, **___):
node = self.ast_node_by_id.get(node_id, None)
if node is None:
return
slice_node = cast(ast.Subscript, node).slice
live, *_ = compute_live_dead_symbol_refs(
slice_node, scope=self.cur_frame_original_scope
)
subscript_live_refs = []
for ref in live:
if len(ref.ref.chain) == 1:
subscript_live_refs.append(cast(str, ref.ref.chain[0].value))
self.node_id_to_saved_live_subscript_refs[node_id] = self.resolve_symbols(
set(subscript_live_refs)
)
Timestamp.update_usage_info(
self.cur_frame_original_scope.lookup_symbol_by_name(ref)
for ref in subscript_live_refs
)
@pyc.register_handler(
(
pyc.before_attribute_load,
pyc.before_attribute_store,
pyc.before_attribute_del,
pyc.before_subscript_load,
pyc.before_subscript_store,
pyc.before_subscript_del,
)
)
@pyc.skip_when_tracing_disabled
def attrsub_tracer(
self,
obj: Any,
node: Union[ast.Attribute, ast.Subscript],
_frame_: FrameType,
event: pyc.TraceEvent,
*_,
attr_or_subscript: AttrSubVal,
call_context: bool,
top_level_node_id: NodeId,
obj_name: Optional[str] = None,
**__,
):
value_node_id = id(node.value)
if isinstance(self.ast_node_by_id[value_node_id], ast.Call):
# clear the callpoint dependency
self.node_id_to_loaded_symbols.pop(value_node_id, None)
if obj is None or obj is get_ipython():
return
logger.warning("%s %s of obj %s", event, attr_or_subscript, obj)
sym_for_obj = self._clear_info_and_maybe_lookup_or_create_complex_symbol(
obj, node
)
# Resolve symbol if necessary
if sym_for_obj is None and obj_name is not None:
sym_for_obj = self.active_scope.get(obj_name)
scope = self._get_namespace_for_obj(obj, obj_name=obj_name)
is_subscript = "subscript" in event.value
if sym_for_obj is not None and sym_for_obj.obj is obj:
try:
sym = scope.lookup_symbol_by_name_this_indentation(
attr_or_subscript,
is_subscript=is_subscript,
skip_cloned_lookup=True,
)
except TypeError:
sym = None
if call_context or event not in (
pyc.before_attribute_load,
pyc.before_subscript_load,
):
self.pending_usage_updates_by_sym[sym_for_obj] = (
self.pending_usage_updates_by_sym.get(sym_for_obj, True)
and (sym is not None)
and not call_context
)
if sym is not None and event in (
pyc.before_attribute_load,
pyc.before_subscript_load,
):
self.pending_usage_updates_by_sym.setdefault(sym, True)
obj_id = id(obj)
if self.top_level_node_id_for_chain is None:
self.top_level_node_id_for_chain = top_level_node_id
if self.first_obj_id_in_chain is None:
self.first_obj_id_in_chain = obj_id
try:
if isinstance(attr_or_subscript, list):
attr_or_subscript = tuple(attr_or_subscript)
if isinstance(attr_or_subscript, tuple):
if not all(
isinstance(v, SubscriptIndices.types) for v in attr_or_subscript
):
return
elif not isinstance(attr_or_subscript, SubscriptIndices.types):
return
if "store" in event.value:
logger.warning(
"save store data for node id %d: %s, %s, %s, %s",
top_level_node_id,
scope,
obj,
attr_or_subscript,
is_subscript,
)
self.node_id_to_saved_store_data[top_level_node_id] = (
scope,
obj,
attr_or_subscript,
is_subscript,
)
return
elif "del" in event.value:
# logger.error("save del data for node %s", ast.dump(self.ast_node_by_id[top_level_node_id]))
logger.warning("save del data for node id %d", top_level_node_id)
self.node_id_to_saved_del_data[top_level_node_id] = (
scope,
obj,