Skip to content

Commit faeb8c0

Browse files
committed
Add symbol dependency
All Symbol instances now have a set which points which others it requires and which ones requires the given instance. An symbol that requires another means that all the parents of the former will also requires it.
1 parent 6f929e9 commit faeb8c0

1 file changed

Lines changed: 36 additions & 2 deletions

File tree

symbols/symbol_.py

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@
1010
# ----------------------------------------------------------------------
1111

1212
import re
13+
from functools import reduce
14+
from typing import Set, Optional
15+
1316
from ast_ import Ast
1417
import api.global_
1518

1619

1720
class Symbol(Ast):
18-
""" Symbol object to store everything related to
19-
a symbol.
21+
""" Symbol object to store everything related to a symbol.
2022
"""
2123
def __init__(self, *children):
2224
super(Symbol, self).__init__()
@@ -25,6 +27,34 @@ def __init__(self, *children):
2527
assert isinstance(child, Symbol)
2628
self.appendChild(child)
2729

30+
self._required_by: Set['Symbol'] = set() # Symbols that depends on this one
31+
self._requires: Set['Symbol'] = set() # Symbols this one depends on
32+
self._cached_required_by: Optional[Set['Symbol']] = set()
33+
34+
@property
35+
def required_by(self) -> Set['Symbol']:
36+
if self._cached_required_by is not None:
37+
return self._cached_required_by
38+
39+
self._cached_required_by = reduce(lambda x: x.union, (x.required_by for x in self.children),
40+
set(self._required_by))
41+
return self._cached_required_by
42+
43+
@property
44+
def requires(self) -> Set['Symbol']:
45+
return set(self._requires)
46+
47+
def mark_as_required_by(self, other: 'Symbol'):
48+
self._required_by.add(other)
49+
self._cached_required_by.add(other)
50+
if self.parent is not None:
51+
assert isinstance(self.parent, Symbol)
52+
self.parent.mark_as_required_by(other)
53+
54+
def add_required_symbol(self, other: 'Symbol'):
55+
self._requires.add(other)
56+
other.mark_as_required_by(self)
57+
2858
@property
2959
def token(self):
3060
""" token = AST Symbol class name, removing the 'Symbol' prefix.
@@ -63,3 +93,7 @@ def copy_attr(self, other):
6393
val = getattr(other, attr)
6494
if isinstance(val, str) or str(val)[0] != '<': # Not a value
6595
setattr(self, attr, val)
96+
97+
@property
98+
def is_needed(self) -> bool:
99+
return len(self.required_by) > 0

0 commit comments

Comments
 (0)