Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions lark/load_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,17 +243,29 @@ def _add_rule(self, key, name, expansions):
self.rules_cache[key] = t
return t

def _token_filtering(self, expr: Union[Tree, Symbol]) -> Tuple[bool, ...]:
"""Returns, for each terminal in expr, whether the current rule filters it out.

Terminals compare by name only, so two equal expressions may still differ in
which tokens they keep. Helper rules may only be shared when this is the same.
"""
keep_all_tokens = bool(self.rule_options and self.rule_options.keep_all_tokens)
symbols = expr.scan_values(lambda v: True) if isinstance(expr, Tree) else [expr]
return tuple(sym.filter_out and not keep_all_tokens
for sym in symbols if isinstance(sym, Terminal))

def _add_recurse_rule(self, type_: str, expr: Tree):
key = (expr, self._token_filtering(expr))
try:
return self.rules_cache[expr]
return self.rules_cache[key]
except KeyError:
new_name = self._name_rule(type_)
t = NonTerminal(new_name)
tree = ST('expansions', [
ST('expansion', [expr]),
ST('expansion', [t, expr])
])
return self._add_rule(expr, new_name, tree)
return self._add_rule(key, new_name, tree)

def _add_repeat_rule(self, a, b, target, atom):
"""Generate a rule that repeats target ``a`` times, and repeats atom ``b`` times.
Expand All @@ -267,7 +279,7 @@ def _add_repeat_rule(self, a, b, target, atom):
new_rule: target target target atom atom atom atom

"""
key = (a, b, target, atom)
key = (a, b, target, atom, self._token_filtering(atom))
try:
return self.rules_cache[key]
except KeyError:
Expand Down Expand Up @@ -300,7 +312,7 @@ def _add_repeat_opt_rule(self, a, b, target, target_opt, atom):
| target target target atom atom atom

"""
key = (a, b, target, atom, "opt")
key = (a, b, target, atom, "opt", self._token_filtering(atom))
try:
return self.rules_cache[key]
except KeyError:
Expand Down
44 changes: 44 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1732,6 +1732,50 @@ def test_keep_all_tokens(self):
tree = l.parse('aaa')
self.assertEqual(tree.children, ['a', 'a', 'a'])

def test_repetition_keep_all_tokens(self):
for repeat, count in [('+', 2), ('*', 2), ('~60', 60), ('~0..60', 2)]:
if PARSER == 'cyk' and repeat in ('*', '~0..60'):
continue # CYK doesn't support empty rules
rules = ['dropped: _A' + repeat, '!kept: _A' + repeat]
for rule_order in (rules, rules[::-1]):
with self.subTest(repeat=repeat, rules=rule_order):
l = _Lark('\n'.join(['start: dropped "," kept'] + rule_order + ['_A: "a"']))
dropped, kept = l.parse('a' * count + ',' + 'a' * count).children
self.assertEqual(dropped, Tree('dropped', []))
self.assertEqual(kept, Tree('kept', [Token('_A', 'a')] * count))

def test_repetition_named_and_anonymous_terminal(self):
# "a" resolves to the terminal A, but only the anonymous use is filtered out
for repeat, count in [('+', 2), ('*', 2), ('~60', 60), ('~0..60', 2)]:
if PARSER == 'cyk' and repeat in ('*', '~0..60'):
continue # CYK doesn't support empty rules
rules = ['named: A' + repeat, 'anon: "a"' + repeat]
for rule_order in (rules, rules[::-1]):
with self.subTest(repeat=repeat, rules=rule_order):
l = _Lark('\n'.join(['start: named "," anon'] + rule_order + ['A: "a"']))
named, anon = l.parse('a' * count + ',' + 'a' * count).children
self.assertEqual(named, Tree('named', [Token('A', 'a')] * count))
self.assertEqual(anon, Tree('anon', []))

def test_repetition_shared_by_keep_all_tokens_rule(self):
# Both rules filter x and NAME the same way, so they must share the repetition.
# Otherwise, LALR can't decide between the two copies (Reduce/Reduce collision)
for repeat, count in [('+', 2), ('~60', 60), ('~2..60', 2)]:
if PARSER == 'cyk' and repeat == '~2..60':
continue # CYK doesn't support empty rules
for item, expected in [('x', Tree('x', [])), ('NAME', Token('NAME', 'x'))]:
with self.subTest(repeat=repeat, item=item):
l = _Lark("""start: a | b
a: %s "a"
!b: %s "b"
x: "x"
NAME: "x"
""" % (item + repeat, item + repeat))
a, = l.parse('x' * count + 'a').children
self.assertEqual(a, Tree('a', [expected] * count))
b, = l.parse('x' * count + 'b').children
self.assertEqual(b, Tree('b', [expected] * count + [Token('B', 'b')]))


def test_token_flags(self):
l = _Lark("""!start: "a"i+
Expand Down