Skip to content

Commit

Permalink
Merge pull request #1013 from adbancroft/nonrecursive_discard
Browse files Browse the repository at this point in the history
  • Loading branch information
erezsh authored Oct 4, 2021
2 parents 1f56497 + f4f19a5 commit ee664b5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
10 changes: 8 additions & 2 deletions lark/visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,9 +277,15 @@ def transform(self, tree):
del stack[-size:]
else:
args = []
stack.append(self._call_userfunc(x, args))
try:
stack.append(self._call_userfunc(x, args))
except Discard:
pass
elif self.__visit_tokens__ and isinstance(x, Token):
stack.append(self._call_userfunc_token(x))
try:
stack.append(self._call_userfunc_token(x))
except Discard:
pass
else:
stack.append(x)

Expand Down
12 changes: 11 additions & 1 deletion tests/test_trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,11 @@ def b(cls, args):
self.assertEqual(x, t2)

def test_transformer_variants(self):
tree = Tree('start', [Tree('add', [Token('N', '1'), Token('N', '2')]), Tree('add', [Token('N', '3'), Token('N', '4')])])
tree = Tree('start', [
Tree('add', [Token('N', '1'), Token('N', '2'), Token('IGNORE_TOKEN', '4')]),
Tree('add', [Token('N', '3'), Token('N', '4')]),
Tree('ignore_tree', [Token('DO', 'NOT PANIC')]),
])
for base in (Transformer, Transformer_InPlace, Transformer_NonRecursive, Transformer_InPlaceRecursive):
class T(base):
def add(self, children):
Expand All @@ -384,6 +388,12 @@ def add(self, children):
def N(self, token):
return int(token)

def ignore_tree(self, children):
raise Discard

def IGNORE_TOKEN(self, token):
raise Discard

copied = copy.deepcopy(tree)
result = T().transform(copied)
self.assertEqual(result, Tree('start', [3, 7]))
Expand Down

0 comments on commit ee664b5

Please sign in to comment.