Skip to content

Commit b560d4b

Browse files
committed
made __hash__ and set_all_read_only in tree.py iterative
1 parent 2291d29 commit b560d4b

1 file changed

Lines changed: 23 additions & 15 deletions

File tree

src/fandango/language/tree.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -258,15 +258,12 @@ def get_path(self) -> list["DerivationTree"]:
258258
return path
259259

260260
def set_all_read_only(self, read_only: bool) -> None:
261-
"""
262-
Sets self as well as all children and sources to read-only.
263-
This signals other classes, that this subtree should not be modified.
264-
"""
265-
self.read_only = read_only
266-
for child in self._children:
267-
child.set_all_read_only(read_only)
268-
for child in self._sources:
269-
child.set_all_read_only(read_only)
261+
stack = [self]
262+
while stack:
263+
node = stack.pop()
264+
node.read_only = read_only
265+
stack.extend(node._children)
266+
stack.extend(node._sources)
270267

271268
def protocol_msgs(self) -> list[ProtocolMessage]:
272269
"""
@@ -423,13 +420,24 @@ def __hash__(self) -> int:
423420
"""
424421
Computes a hash of the derivation tree based on its structure and symbols.
425422
"""
426-
if self.hash_cache is None:
427-
self.hash_cache = hash(
423+
if self.hash_cache is not None:
424+
return self.hash_cache
425+
426+
order: list[DerivationTree] = []
427+
stack: list[DerivationTree] = [self]
428+
while stack:
429+
node = stack.pop()
430+
if node.hash_cache is None:
431+
order.append(node)
432+
stack.extend(node._children)
433+
434+
for node in reversed(order):
435+
node.hash_cache = hash(
428436
(
429-
self.symbol,
430-
self.sender,
431-
self.recipient,
432-
tuple(hash(child) for child in self._children),
437+
node.symbol,
438+
node.sender,
439+
node.recipient,
440+
tuple(hash(child) for child in node._children),
433441
)
434442
)
435443
return self.hash_cache

0 commit comments

Comments
 (0)