Browse Source

Improved: efficiency of iter_subtrees(), customizability of pretty()

tags/gm/2021-09-23T00Z/github.com--lark-parser-lark/0.5.1
Erez Shinan 7 years ago
parent
commit
9570918005
1 changed files with 8 additions and 1 deletions
  1. +8
    -1
      lark/tree.py

+ 8
- 1
lark/tree.py View File

@@ -10,11 +10,14 @@ class Tree(object):
def __repr__(self): def __repr__(self):
return 'Tree(%s, %s)' % (self.data, self.children) return 'Tree(%s, %s)' % (self.data, self.children)


def _pretty_label(self):
return self.data

def _pretty(self, level, indent_str): def _pretty(self, level, indent_str):
if len(self.children) == 1 and not isinstance(self.children[0], Tree): if len(self.children) == 1 and not isinstance(self.children[0], Tree):
return [ indent_str*level, self.data, '\t', '%s' % self.children[0], '\n'] return [ indent_str*level, self.data, '\t', '%s' % self.children[0], '\n']


l = [ indent_str*level, self.data, '\n' ]
l = [ indent_str*level, self._pretty_label(), '\n' ]
for n in self.children: for n in self.children:
if isinstance(n, Tree): if isinstance(n, Tree):
l += n._pretty(level+1, indent_str) l += n._pretty(level+1, indent_str)
@@ -62,10 +65,14 @@ class Tree(object):
yield c yield c


def iter_subtrees(self): def iter_subtrees(self):
visited = set()
q = [self] q = [self]


while q: while q:
subtree = q.pop() subtree = q.pop()
if id(subtree) in visited:
continue # already been here from another branch
visited.add(id(subtree))
yield subtree yield subtree
q += [c for c in subtree.children if isinstance(c, Tree)] q += [c for c in subtree.children if isinstance(c, Tree)]




Loading…
Cancel
Save