-
Notifications
You must be signed in to change notification settings - Fork 21
/
symbol.py
1458 lines (1328 loc) · 55 KB
/
symbol.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 logging
import sys
from enum import Enum
from types import FrameType, FunctionType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Set,
Tuple,
Type,
cast,
)
from ipyflow.config import ExecutionSchedule, FlowDirection
from ipyflow.data_model.cell import Cell, cells
from ipyflow.data_model.timestamp import Timestamp
from ipyflow.data_model.utils.annotation_utils import (
get_type_annotation,
make_annotation_string,
)
from ipyflow.data_model.utils.update_protocol import UpdateProtocol
from ipyflow.models import _SymbolContainer, namespaces, statements, symbols
from ipyflow.singletons import flow, shell, tracer
from ipyflow.slicing.context import dynamic_slicing_context, slicing_context
from ipyflow.slicing.mixin import FormatType, Slice
from ipyflow.tracing.watchpoint import Watchpoints
from ipyflow.types import IMMUTABLE_PRIMITIVE_TYPES, IdType, SupportedIndexType
from ipyflow.utils.misc_utils import cleanup_discard, debounce
try:
from importlib.util import _LazyModule # type: ignore
except: # noqa
_LazyModule = None
if TYPE_CHECKING:
import astunparse
elif hasattr(ast, "unparse"):
astunparse = ast
else:
import astunparse
if TYPE_CHECKING:
# avoid circular imports
from ipyflow.data_model.namespace import Namespace
from ipyflow.data_model.scope import Scope
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
# just want to get rid of unused warning
_override_unused_warning_symbols = symbols
@debounce(0.1)
def _debounced_exec_schedule(executed_cell_id: IdType, reactive: bool) -> None:
flow_ = flow()
settings = flow_.mut_settings
exec_schedule = settings.exec_schedule
try:
if exec_schedule == ExecutionSchedule.DAG_BASED:
settings.exec_schedule = ExecutionSchedule.HYBRID_DAG_LIVENESS_BASED
flow_.get_and_set_exception_raised_during_execution(None)
flow_.handle(
{
"type": "compute_exec_schedule",
"executed_cell_id": executed_cell_id,
"is_reactively_executing": reactive,
"allow_new_ready": reactive,
}
)
finally:
settings.exec_schedule = exec_schedule
flow_.debounced_exec_schedule_pending = False
class SymbolType(Enum):
DEFAULT = "default"
SUBSCRIPT = "subscript"
FUNCTION = "function"
CLASS = "class"
IMPORT = "import"
MODULE = "module"
ANONYMOUS = "anonymous"
class Symbol:
NULL = object()
# object for virtual display symbol
DISPLAY = object()
IMMUTABLE_TYPES = set(IMMUTABLE_PRIMITIVE_TYPES)
IPYFLOW_MUTATION_VIRTUAL_SYMBOL_NAME = "__ipyflow_mutation"
def __init__(
self,
name: SupportedIndexType,
symbol_type: SymbolType,
obj: Any,
containing_scope: "Scope",
stmt_node: Optional[ast.stmt] = None,
symbol_node: Optional[ast.AST] = None,
refresh_cached_obj: bool = False,
implicit: bool = False,
) -> None:
if refresh_cached_obj:
# TODO: clean up redundancies
assert implicit
assert stmt_node is None
self.name = name
self.symbol_type = symbol_type
self.obj = obj
# additional user-specific metadata
self._tags: Set[str] = set()
self.extra_metadata: Dict[str, Any] = {}
self._tombstone = False
self._cached_out_of_sync = True
self.cached_obj_id: Optional[int] = None
self.cached_obj_type: Optional[Type[object]] = None
self.cached_obj_len: Optional[int] = None
if refresh_cached_obj:
self._refresh_cached_obj()
self.containing_scope = containing_scope or flow().global_scope
self.call_scope: Optional[Scope] = None
self.func_def_stmt: Optional[ast.stmt] = None
self.stmt_node = self.update_stmt_node(stmt_node)
self.symbol_node = symbol_node
self._funcall_live_symbols = None
self.parents: Dict["Symbol", List[Timestamp]] = {}
self.children: Dict["Symbol", List[Timestamp]] = {}
# initialize at -1 for implicit since the corresponding piece of data could already be around,
# and we don't want liveness checker to think this was newly created unless we
# explicitly trace an update somewhere
self._timestamp: Timestamp = (
Timestamp.uninitialized() if implicit else Timestamp.current()
)
self._snapshot_timestamps: List[Timestamp] = []
self._snapshot_timestamp_ubounds: List[Timestamp] = []
self._defined_cell_num = cells().exec_counter()
self._is_dangling_on_edges = False
self._cascading_reactive_cell_num = -1
self._override_ready_liveness_cell_num = -1
self._override_timestamp: Optional[Timestamp] = None
self.watchpoints = Watchpoints()
# The necessary last-updated timestamp / cell counter for this symbol to not be waiting
self.required_timestamp: Timestamp = self.timestamp
# for each usage of this sym, the version that was used, if different from the timestamp of usage
self.timestamp_by_used_time: Dict[Timestamp, Timestamp] = {}
self.used_node_by_used_time: Dict[Timestamp, ast.AST] = {}
# History of definitions at time of liveness
self.timestamp_by_liveness_time: Dict[Timestamp, Timestamp] = {}
# All timestamps associated with updates to this symbol
self.updated_timestamps: Set[Timestamp] = set()
# The most recent timestamp associated with a particular object id
self.last_updated_timestamp_by_obj_id: Dict[int, Timestamp] = {}
self.fresher_ancestors: Set["Symbol"] = set()
self.fresher_ancestor_timestamps: Set[Timestamp] = set()
# cells where this symbol was live
self.cells_where_deep_live: Set[Cell] = set()
self.cells_where_shallow_live: Set[Cell] = set()
self._last_computed_ready_or_waiting_cache_ts: int = -1
self._is_ready_or_waiting_at_position_cache: Dict[Tuple[int, bool], bool] = {}
# if implicitly created when tracing non-store-context ast nodes
self._implicit = implicit
# Will never be stale if no_warning is True
self.disable_warnings = False
self._temp_disable_warnings = False
self._num_ipywidget_observers = 0
self._num_mercury_widget_observers = 0
flow().aliases.setdefault(id(obj), set()).add(self)
if (
isinstance(self.name, str)
and not self.is_anonymous
and not self.containing_scope.is_namespace_scope
):
ns = self.namespace
if ns is not None and ns.scope_name == "self":
# hack to get a better name than `self.whatever` for fields of this object
# not ideal because it relies on the `self` convention but is probably
# acceptable for the use case of improving readable names
ns.scope_name = self.name
@property
def aliases(self) -> List["Symbol"]:
return list(flow().aliases.get(self.obj_id, []))
@property
def cells_where_live(self) -> Set[Cell]:
return self.cells_where_deep_live | self.cells_where_shallow_live
def __repr__(self) -> str:
return f"<{self.readable_name}>"
def __str__(self) -> str:
return self.readable_name
def __hash__(self) -> int:
return hash(id(self))
def __lt__(self, other) -> bool:
return id(self) < id(other)
def add_tag(self, tag_value: str) -> None:
self._tags.add(tag_value)
def remove_tag(self, tag_value: str) -> None:
self._tags.discard(tag_value)
def has_tag(self, tag_value: str) -> bool:
return tag_value in self._tags
def temporary_disable_warnings(self) -> None:
self._temp_disable_warnings = True
@property
def last_used_timestamp(self) -> Timestamp:
if len(self.timestamp_by_used_time) == 0:
return Timestamp.uninitialized()
else:
return max(self.timestamp_by_used_time.keys())
@property
def namespace_waiting_symbols(self) -> Set["Symbol"]:
ns = self.namespace
return set() if ns is None else ns.namespace_waiting_symbols
@property
def shallow_timestamp(self) -> Timestamp:
if self._override_timestamp is None:
return self._timestamp
else:
return max(self._timestamp, self._override_timestamp)
@property
def visible_timestamp(self) -> Optional[Timestamp]:
for ts in sorted(self.updated_timestamps, reverse=True):
if cells().at_timestamp(ts).is_visible:
return ts
return None
@property
def memoize_timestamp(self) -> Optional[Timestamp]:
return self.last_updated_timestamp_by_obj_id.get(self.obj_id)
@property
def timestamp(self) -> Timestamp:
ts = self.shallow_timestamp
if self.is_import or self.is_module:
return ts
ns = self.namespace
return ts if ns is None else max(ts, ns.max_descendent_timestamp)
def _compute_namespace_timestamps(
self,
seen: Optional[Set["Symbol"]] = None,
version_ubound: Optional[Timestamp] = None,
) -> Set[Timestamp]:
if version_ubound is None:
timestamps = {self.shallow_timestamp, self.timestamp}
else:
max_leq_ubound = Timestamp.uninitialized()
for ts in reversed(self._snapshot_timestamps):
if ts <= version_ubound:
max_leq_ubound = ts
break
if max_leq_ubound.is_initialized:
timestamps = {max_leq_ubound}
else:
timestamps = set()
ns = self.namespace
if ns is None:
return timestamps
if seen is None:
seen = set()
if self in seen:
return timestamps
seen.add(self)
for sym in ns.all_symbols_this_indentation():
timestamps |= sym._compute_namespace_timestamps(
seen=seen, version_ubound=version_ubound
)
return timestamps
def _get_timestamps_for_version(self, version: int) -> Set[Timestamp]:
if len(self._snapshot_timestamps) == 0:
return {self.timestamp}
ts = self._snapshot_timestamps[version]
if ts.cell_num == -1:
return {Timestamp(self.defined_cell_num, ts.stmt_num)}
else:
return self._compute_namespace_timestamps(
version_ubound=None if version == -1 else ts
)
def code(
self, format_type: Optional[Type[FormatType]] = None, version: int = -1
) -> Slice:
return statements().format_multi_slice(
self._get_timestamps_for_version(version=version),
blacken=True,
format_type=format_type,
)
def cascading_reactive_cell_num(
self,
seen: Optional[Set["Symbol"]] = None,
consider_containing_symbols: bool = True,
) -> int:
if seen is None:
seen = set()
if self in seen:
return -1
seen.add(self)
cell_num = self._cascading_reactive_cell_num
ns = self.namespace
ret = (
cell_num
if ns is None
else max(
cell_num,
ns.max_cascading_reactive_cell_num(seen),
)
)
if not consider_containing_symbols:
return ret
for sym in self.iter_containing_symbols():
ret = max(ret, sym.cascading_reactive_cell_num(seen=seen))
return ret
def bump_cascading_reactive_cell_num(self, ctr: Optional[int] = None) -> None:
self._cascading_reactive_cell_num = max(
self._cascading_reactive_cell_num,
flow().cell_counter() if ctr is None else ctr,
)
def iter_containing_symbols(self) -> Generator["Symbol", None, None]:
yield self
ns = self.containing_namespace
if ns is None or not ns.is_namespace_scope:
return
for containing_ns in ns.iter_containing_namespaces():
yield from flow().aliases.get(containing_ns.obj_id, [])
@property
def waiting_timestamp(self) -> int:
return max(self._timestamp.cell_num, flow().min_timestamp)
@property
def defined_cell_num(self) -> int:
return self._defined_cell_num
@property
def readable_name(self) -> str:
return self.containing_scope.make_namespace_qualified_name(self)
@property
def is_subscript(self) -> bool:
return self.symbol_type == SymbolType.SUBSCRIPT
@property
def is_class(self) -> bool:
return self.symbol_type == SymbolType.CLASS
@property
def is_function(self) -> bool:
return self.symbol_type == SymbolType.FUNCTION
@property
def is_import(self) -> bool:
return self.symbol_type == SymbolType.IMPORT
@property
def is_module(self) -> bool:
return self.symbol_type == SymbolType.MODULE
@property
def imported_module(self) -> str:
if not self.is_import:
raise ValueError("only IMPORT symbols have `imported_module` property")
if isinstance(self.stmt_node, ast.Import):
for alias in self.stmt_node.names:
name = alias.asname or alias.name
if name == self.name:
return alias.name
raise ValueError(
"Unable to find module for symbol %s is stmt %s"
% (self, ast.dump(self.stmt_node))
)
elif isinstance(self.stmt_node, ast.ImportFrom):
return self.stmt_node.module
else:
raise TypeError(
"Invalid stmt type for import symbol: %s" % ast.dump(self.stmt_node)
)
@property
def imported_symbol_original_name(self) -> str:
if not self.is_import:
raise ValueError(
"only IMPORT symbols have `imported_symbol_original_name` property"
)
if isinstance(self.stmt_node, ast.Import):
return self.imported_module
elif isinstance(self.stmt_node, ast.ImportFrom):
for alias in self.stmt_node.names:
name = alias.asname or alias.name
if name == self.name:
return alias.name
raise ValueError(
"Unable to find module for symbol %s is stmt %s"
% (self, ast.dump(self.stmt_node))
)
else:
raise TypeError(
"Invalid stmt type for import symbol: %s" % ast.dump(self.stmt_node)
)
def is_cascading_reactive_at_counter(self, ctr: int) -> bool:
return self.cascading_reactive_cell_num() > max(
ctr, flow().min_cascading_reactive_cell_num
)
def get_top_level(self) -> Optional["Symbol"]:
if not self.containing_scope.is_namespace_scope:
return self
else:
containing_scope = cast("Namespace", self.containing_scope)
for alias in flow().aliases.get(containing_scope.obj_id, []):
if alias.is_globally_accessible:
return alias.get_top_level()
return None
def get_import_string(self) -> str:
if not self.is_import:
raise ValueError("only IMPORT symbols support recreating the import string")
module = self.imported_module
if isinstance(self.stmt_node, ast.Import):
if module == self.name:
return f"import {module}"
else:
return f"import {module} as {self.name}"
elif isinstance(self.stmt_node, ast.ImportFrom):
original_symbol_name = self.imported_symbol_original_name
if original_symbol_name == self.name:
return f"from {module} import {original_symbol_name}"
else:
return f"from {module} import {original_symbol_name} as {self.name}"
else:
raise TypeError(
"Invalid stmt type for import symbol: %s" % ast.dump(self.stmt_node)
)
@property
def is_anonymous(self) -> bool:
if self.symbol_type == SymbolType.ANONYMOUS:
return True
ns = self.containing_namespace
if ns is not None and ns.is_anonymous:
return True
return False
@property
def is_implicit(self) -> bool:
return self._implicit
def shallow_clone(
self, new_obj: Any, new_containing_scope: "Scope", symbol_type: SymbolType
) -> "Symbol":
return self.__class__(self.name, symbol_type, new_obj, new_containing_scope)
@property
def obj_id(self) -> int:
return id(self.obj)
@property
def obj_len(self) -> Optional[int]:
try:
if not self.is_obj_lazy_module and hasattr(self.obj, "__len__"):
return len(self.obj)
except: # noqa: E722
pass
return None
@property
def obj_type(self) -> Type[Any]:
return type(self.obj)
@property
def is_immutable(self) -> bool:
return self.obj_type in self.IMMUTABLE_TYPES
@property
def is_mutation_virtual_symbol(self) -> bool:
return self.name == self.IPYFLOW_MUTATION_VIRTUAL_SYMBOL_NAME
@property
def is_underscore(self) -> bool:
return self.name == "_" and self.containing_scope.is_global
@property
def is_obj_lazy_module(self) -> bool:
return self.obj_type is _LazyModule
def get_type_annotation(self):
return get_type_annotation(self.obj)
def get_type_annotation_string(self) -> str:
return make_annotation_string(self.get_type_annotation())
@property
def namespace(self) -> Optional["Namespace"]:
return flow().namespaces.get(self.obj_id)
@property
def containing_namespace(self) -> Optional["Namespace"]:
if self.containing_scope.is_namespace_scope:
return cast("Namespace", self.containing_scope)
else:
return None
@property
def full_path(self) -> Tuple[str, ...]:
return self.containing_scope.full_path + (str(self.name),)
@property
def full_namespace_path(self) -> str:
return self.containing_scope.make_namespace_qualified_name(self)
@property
def is_garbage(self) -> bool:
return self._tombstone
def is_new_garbage(self) -> bool:
if self._tombstone:
return False
containing_ns = self.containing_namespace
numpy = sys.modules.get("numpy", None)
if (
numpy is not None
and containing_ns is not None
and isinstance(containing_ns.obj, numpy.ndarray)
):
# numpy atoms are not interned (so assigning array elts to a variable does not bump refcount);
# also seems that refcount is always 0, so just check if the containing namespace is garbage
return self.containing_namespace.is_garbage
return self.get_ref_count() == 0
@property
def is_globally_accessible(self) -> bool:
return self.containing_scope.is_globally_accessible
@property
def is_user_accessible(self) -> bool:
return (
self.is_globally_accessible
and not self.is_anonymous
and not self.is_garbage
and not (
self.containing_namespace is not None
and (
self.containing_namespace.is_anonymous
or self.containing_namespace.is_garbage
)
)
)
def _remove_self_from_aliases(self) -> None:
cleanup_discard(flow().aliases, self.obj_id, self)
self.obj = None
def mark_garbage(self) -> None:
if self.is_garbage:
return
self._tombstone = True
ns = self.namespace
if ns is not None and all(alias.is_garbage for alias in self.aliases):
ns.mark_garbage()
def collect_self_garbage(self) -> None:
assert self.is_garbage
flow().blocked_reactive_timestamps_by_symbol.pop(self, None)
self._remove_self_from_aliases()
for parent in self.parents:
parent.children.pop(self, None)
for child in self.children:
child.parents.pop(self, None)
containing_ns = self.containing_namespace
if self.is_subscript and containing_ns is not None:
containing_ns._subscript_symbol_by_name.pop(self.name, None)
elif not self.is_subscript:
self.containing_scope._symbol_by_name.pop(self.name, None)
else:
logger.warning(
"could not find symbol %s in its scope %s", self, self.containing_scope
)
# TODO: remove from static / dynamic parent / children edges
# need to keep this around for readable_name to work
# self.containing_scope = None
# def update_type(self, new_type):
# self.symbol_type = new_type
# if self.is_function:
# self.call_scope = self.containing_scope.make_child_scope(self.name)
# else:
# self.call_scope = None
def update_obj_ref(self, obj: Any, refresh_cached: bool = True) -> None:
if self._num_ipywidget_observers > 0:
try:
self.obj.unobserve_all()
except: # noqa
pass
self._num_ipywidget_observers = 0
if self._num_mercury_widget_observers > 0:
try:
self._mercury_widgets_manager.get_widget(
self.obj.code_uid
).unobserve_all()
except: # noqa
pass
self._num_mercury_widget_observers = 0
self._tombstone = False
self._cached_out_of_sync = True
if (
flow().settings.mark_typecheck_failures_unsafe
and self.cached_obj_type != type(obj)
):
for cell in self.cells_where_live:
cell.invalidate_typecheck_result()
self.cells_where_shallow_live.clear()
self.cells_where_deep_live.clear()
self.obj = obj
if self.cached_obj_id is not None and self.cached_obj_id != self.obj_id:
new_ns = flow().namespaces.get(self.obj_id, None)
# don't overwrite existing namespace for this obj
old_ns = flow().namespaces.get(self.cached_obj_id, None)
if (
old_ns is not None
and old_ns.full_namespace_path == self.full_namespace_path
):
if new_ns is None:
logger.info("create fresh copy of namespace %s", old_ns)
new_ns = old_ns.fresh_copy(obj)
old_ns.transfer_symbols_to(new_ns)
else:
new_ns.scope_name = old_ns.scope_name
new_ns.parent_scope = old_ns.parent_scope
self._handle_aliases()
if (
old_ns is not None
and len(flow().aliases.get(self.cached_obj_id, [])) == 0
):
old_ns.mark_garbage()
if refresh_cached:
self._refresh_cached_obj()
def invalidate_cached(self) -> None:
self._cached_out_of_sync = True
self.cached_obj_id = None
self.cached_obj_type = None
def get_ref_count(self) -> int:
if self.obj is None or self.obj is Symbol.NULL:
return -1
total = sys.getrefcount(self.obj) - 1
total -= len(flow().aliases.get(self.obj_id, []))
ns = flow().namespaces.get(self.obj_id, None)
if ns is not None and ns.obj is not None and ns.obj is not Symbol.NULL:
total -= 1
return total
def _should_cancel_propagation(self, prev_obj: Optional[Any]) -> bool:
if prev_obj is None:
return False
if (
flow().blocked_reactive_timestamps_by_symbol.get(self, -1)
== self.timestamp.cell_num
):
return False
if not self._cached_out_of_sync or self.obj_id == self.cached_obj_id:
return True
if self.obj is None or prev_obj is Symbol.NULL:
return self.obj is None and prev_obj is Symbol.NULL
return False
def _handle_aliases(self):
cleanup_discard(flow().aliases, self.cached_obj_id, self)
flow().aliases.setdefault(self.obj_id, set()).add(self)
def update_stmt_node(self, stmt_node: Optional[ast.stmt]) -> Optional[ast.stmt]:
self.stmt_node = stmt_node
self._funcall_live_symbols = None
if self.is_function or (
stmt_node is not None and isinstance(stmt_node, ast.Lambda)
):
# TODO: in the case of lambdas, there will not necessarily be one
# symbol for a given statement. We need a more precise way to determine
# the symbol being called than by looking at the stmt in question.
flow().statement_to_func_sym[id(stmt_node)] = self
self.call_scope = self.containing_scope.make_child_scope(self.name)
self.func_def_stmt = stmt_node
return stmt_node
def _refresh_cached_obj(self) -> None:
self._cached_out_of_sync = False
# don't keep an actual ref to avoid bumping refcount
self.cached_obj_id = self.obj_id
self.cached_obj_type = self.obj_type
self.cached_obj_len = self.obj_len
def get_definition_args(self) -> List[ast.arg]:
assert self.func_def_stmt is not None and isinstance(
self.func_def_stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
)
args = []
for arg in self.func_def_stmt.args.args + self.func_def_stmt.args.kwonlyargs:
args.append(arg)
if self.func_def_stmt.args.vararg is not None:
args.append(self.func_def_stmt.args.vararg)
if self.func_def_stmt.args.kwarg is not None:
args.append(self.func_def_stmt.args.kwarg)
return args
def _match_call_args_with_definition_args(
self,
) -> Generator[Tuple[ast.arg, List["Symbol"]], None, None]:
# TODO: handle posonlyargs, kwonlyargs
assert self.func_def_stmt is not None and isinstance(
self.func_def_stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
)
caller_node = self._get_calling_ast_node()
if caller_node is None or not isinstance(caller_node, ast.Call):
return
kwarg_by_name = {
arg_key.arg: arg_key
for arg_key in self.func_def_stmt.args.args[
-len(self.func_def_stmt.args.defaults) :
]
}
if not all(keyword.arg in kwarg_by_name for keyword in caller_node.keywords):
logger.warning("detected mismatched kwargs from caller node to definition")
return
def_args = self.func_def_stmt.args.args
if len(self.func_def_stmt.args.defaults) > 0:
def_args = def_args[: -len(self.func_def_stmt.args.defaults)]
if len(def_args) > 0 and def_args[0].arg == "self":
# FIXME: this is bad and I should feel bad
def_args = def_args[1:]
for def_arg, call_arg in zip(def_args, caller_node.args):
if isinstance(call_arg, ast.Starred):
# give up
# TODO: handle this case
break
yield def_arg, tracer().resolve_loaded_symbols(call_arg)
seen_keys = set()
for keyword in caller_node.keywords:
keyword_key, keyword_value = keyword.arg, keyword.value
if keyword_value is None:
continue
seen_keys.add(keyword_key)
yield kwarg_by_name[keyword_key], tracer().resolve_loaded_symbols(
keyword_value
)
for arg_key, arg_value in zip(
self.func_def_stmt.args.args[-len(self.func_def_stmt.args.defaults) :],
self.func_def_stmt.args.defaults,
):
if arg_key.arg in seen_keys:
continue
yield arg_key, tracer().resolve_loaded_symbols(arg_value)
def _get_calling_ast_node(self) -> Optional[ast.Call]:
if tracer().tracing_disabled_since_last_module_stmt or (
not hasattr(self.obj, "__module__")
and getattr(type(self.obj), "__module__", None) == "builtins"
):
return None
if self.func_def_stmt is not None and isinstance(
self.func_def_stmt, (ast.FunctionDef, ast.AsyncFunctionDef)
):
if self.name in ("__getitem__", "__setitem__", "__delitem__"):
# TODO: handle case where we're looking for a subscript for the calling node
return None
for decorator in self.func_def_stmt.decorator_list:
if isinstance(decorator, ast.Name) and decorator.id == "property":
# TODO: handle case where we're looking for an attribute for the calling node
return None
lexical_call_stack = tracer().lexical_call_stack
if len(lexical_call_stack) == 0:
return None
prev_node_id_in_cur_frame_lexical = lexical_call_stack.get_field(
"prev_node_id_in_cur_frame_lexical"
)
caller_ast_node = tracer().ast_node_by_id.get(
prev_node_id_in_cur_frame_lexical, None
)
if caller_ast_node is None or not isinstance(caller_ast_node, ast.Call):
return None
return caller_ast_node
def create_symbols_for_call_args(self, call_frame: FrameType) -> None:
assert self.func_def_stmt is not None
seen_def_args = set()
logger.info("create symbols for call to %s", self)
for def_arg, deps in self._match_call_args_with_definition_args():
seen_def_args.add(def_arg.arg)
self.call_scope.upsert_symbol_for_name(
def_arg.arg,
call_frame.f_locals.get(def_arg.arg),
deps,
self.func_def_stmt,
propagate=False,
symbol_node=def_arg,
)
logger.info("def arg %s matched with deps %s", def_arg, deps)
for def_arg in self.get_definition_args():
if def_arg.arg in seen_def_args:
continue
self.call_scope.upsert_symbol_for_name(
def_arg.arg,
None,
set(),
self.func_def_stmt,
propagate=False,
symbol_node=def_arg,
)
@property
def is_waiting(self) -> bool:
if self.disable_warnings or self._temp_disable_warnings:
return False
if self.waiting_timestamp < self.required_timestamp.cell_num:
return True
elif flow().min_timestamp == -1:
return len(self.namespace_waiting_symbols) > 0
else:
# TODO: guard against infinite recurision
return any(sym.is_waiting for sym in self.namespace_waiting_symbols)
@property
def is_shallow_stale(self) -> bool:
if self.disable_warnings or self._temp_disable_warnings:
return False
return self.waiting_timestamp < self.required_timestamp.cell_num
def _is_ready_or_waiting_at_position_impl(self, pos: int, deep: bool) -> bool:
for par, timestamps in self.parents.items():
for ts in timestamps:
dep_introduced_pos = cells().at_timestamp(ts).position
if dep_introduced_pos > pos:
continue
for updated_ts in par.updated_timestamps:
if cells().at_timestamp(updated_ts).position > dep_introduced_pos:
continue
if updated_ts.cell_num > ts.cell_num or par.is_waiting_at_position(
dep_introduced_pos
):
# logger.error("sym: %s", self)
# logger.error("pos: %s", pos)
# logger.error("parent: %s", par)
# logger.error("dep introdced ts: %s", ts)
# logger.error("dep introdced pos: %s", dep_introduced_pos)
# logger.error("par updated ts: %s", updated_ts)
# logger.error("par updated position: %s", cells().from_timestamp(updated_ts).position)
return True
if deep:
for sym in self.namespace_waiting_symbols:
if sym.is_waiting_at_position(pos):
return True
return False
def is_waiting_at_position(self, pos: int, deep: bool = True) -> bool:
if deep:
if not self.is_waiting:
return False
else:
if not self.is_shallow_stale:
return False
if flow().mut_settings.flow_order == FlowDirection.ANY_ORDER:
return True
if cells().exec_counter() > self._last_computed_ready_or_waiting_cache_ts:
self._is_ready_or_waiting_at_position_cache.clear()
self._last_computed_ready_or_waiting_cache_ts = cells().exec_counter()
if (pos, deep) in self._is_ready_or_waiting_at_position_cache:
return self._is_ready_or_waiting_at_position_cache[pos, deep]
# preemptively set this entry to 'False' in the cache to avoid infinite loops
self._is_ready_or_waiting_at_position_cache[pos, deep] = False
is_waiting = self._is_ready_or_waiting_at_position_impl(pos, deep)
self._is_ready_or_waiting_at_position_cache[pos, deep] = is_waiting
return is_waiting
def should_mark_waiting(self, updated_dep):
if self.disable_warnings:
return False
if updated_dep is self:
return False
return True
def _is_underscore_or_simple_assign(self, new_deps: Set["Symbol"]) -> bool:
if self.is_underscore:
# FIXME: distinguish between explicit assignment to _ from user and implicit assignment from kernel
return True
if not isinstance(self.stmt_node, (ast.Assign, ast.AnnAssign)):
return False
if len(new_deps) != 1:
return False
only_dep: Symbol = next(iter(new_deps))
# obj ids can get reused for anon symbols like literals
return not only_dep.is_anonymous and self.obj_id == only_dep.obj_id
def update_deps(
self,
new_deps: Set["Symbol"],
prev_obj: Any = None,
overwrite: bool = True,
mutated: bool = False,
deleted: bool = False,
propagate_to_namespace_descendents: bool = False,
propagate: bool = True,
refresh: bool = True,
is_cascading_reactive: Optional[bool] = None,
) -> None:
if self.is_import and self.obj_id == self.cached_obj_id:
# skip updates for imported symbols; just bump the version
self.refresh()
return
if overwrite and not self.is_globally_accessible:
self.watchpoints.clear()
if mutated and self.is_immutable:
return
# if we get here, no longer implicit
self._implicit = False
# quick last fix to avoid overwriting if we appear inside the set of deps to add (or a 1st order ancestor)
# TODO: check higher-order ancestors too?
overwrite = overwrite and self not in new_deps
overwrite = overwrite and not any(
self in new_dep.parents for new_dep in new_deps
)
logger.warning("symbol %s new deps %s", self, new_deps)
new_deps.discard(self)
if overwrite:
for parent in self.parents.keys() - new_deps:
parent.children.pop(self, None)
self.parents.pop(parent, None)
for new_parent in new_deps - self.parents.keys():
if new_parent is None:
continue
new_parent.children.setdefault(self, []).append(Timestamp.current())
self.parents.setdefault(new_parent, []).append(Timestamp.current())
self.required_timestamp = Timestamp.uninitialized()
self.fresher_ancestors.clear()
self.fresher_ancestor_timestamps.clear()
if mutated or isinstance(self.stmt_node, ast.AugAssign):
self.update_usage_info()
if (
(mutated or overwrite)
and Timestamp.current().is_initialized
and not self.is_immutable
and not self.is_mutation_virtual_symbol
and not self.is_anonymous
and self.containing_scope.is_global
and not self.is_underscore
and not self.is_implicit
and self.obj_type is not type
and not self.is_class
and self.namespace is not None
):
self.namespace.upsert_symbol_for_name(
self.IPYFLOW_MUTATION_VIRTUAL_SYMBOL_NAME, object(), propagate=False
)
propagate = propagate and (
mutated or deleted or not self._should_cancel_propagation(prev_obj)
)
try:
prev_cell = cells().current_cell().prev_cell
except KeyError:
prev_cell = None