in experimental/piranha_playground/rule_inference/graph_parser.py [0:0]
def _traverse_tree(self, tree: Tree) -> Dict[str, List[Node]]:
"""
Performs a depth-first search (DFS) on the given tree to find nodes that are used for templates.
:param tree: The tree to be traversed.
:type tree: Tree
:return: A dictionary mapping template identifiers to corresponding nodes.
:rtype: Dict[str, List[Node]]
"""
root = tree.root_node
stack: Deque = deque([root])
replacement_pairs = []
node_start = root
while stack:
node = stack.pop()
if "comment" in node.type:
node_text = node.text.decode("utf8")
if "->" in node_text:
x, y = map(str.strip, node_text[2:].split("->"))
self.edges[x].add(y)
elif node_text.strip().endswith("end"):
replacement_pairs.append((node_start, node))
else:
node_start = node
for child in reversed(node.children):
stack.append(child)
replacement_dict = defaultdict(list)
for start, end in replacement_pairs:
begin_capture = start.end_byte
end_capture = end.start_byte
nodes = NodeUtils.get_nodes_in_range(root, begin_capture, end_capture)
comment = start.text.decode("utf8")[2:].strip()
replacement_dict[comment] = nodes
return replacement_dict