Browse Source

Method iter_subtrees_topdown added

tags/gm/2021-09-23T00Z/github.com--lark-parser-lark/0.66
Alexey Shrub 6 years ago
parent
commit
2ad06a24bd
2 changed files with 20 additions and 1 deletions
  1. +5
    -1
      docs/classes.md
  2. +15
    -0
      lark/tree.py

+ 5
- 1
docs/classes.md View File

@@ -76,7 +76,11 @@ Returns all nodes of the tree whose data equals the given data.

#### iter_subtrees(self)

Iterates over all the subtrees, never returning to the same node twice (Lark's parse-tree is actually a DAG)
Iterates over all the subtrees, never returning to the same node twice (Lark's parse-tree is actually a DAG).

#### iter_subtrees_topdown(self)

Iterates over all the subtrees, return nodes in order like pretty() does.

#### \_\_eq\_\_, \_\_hash\_\_



+ 15
- 0
lark/tree.py View File

@@ -5,6 +5,7 @@ except ImportError:

from copy import deepcopy


###{standalone
class Meta:
pass
@@ -42,6 +43,7 @@ class Tree(object):

def pretty(self, indent_str=' '):
return ''.join(self._pretty(0, indent_str))

def __eq__(self, other):
try:
return self.data == other.data and self.children == other.children
@@ -99,12 +101,25 @@ class Tree(object):
yield x
seen.add(id(x))

def iter_subtrees_topdown(self):
if not self.children:
return self

stack = [self]
while stack:
node = stack.pop()
if not isinstance(node, Tree):
continue
yield node
for n in reversed(node.children):
stack.append(n)

def __deepcopy__(self, memo):
return type(self)(self.data, deepcopy(self.children, memo))

def copy(self):
return type(self)(self.data, self.children)

def set(self, data, children):
self.data = data
self.children = children


Loading…
Cancel
Save