Skip to content

Commit e0889a3

Browse files
committed
Sort Options inside a TerminalTree
1 parent 4b70d1d commit e0889a3

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

lark/load_grammar.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -614,6 +614,10 @@ def expansions(self, exps):
614614
if len(exps) == 1:
615615
return exps[0]
616616

617+
# Do a bit of sorting to make sure that the longest option is returned
618+
# (Python's re module otherwise prefers just 'l' when given (l|ll) and both could match)
619+
exps.sort(key=lambda x: (-x.max_width, -x.min_width, -len(x.value)))
620+
617621
pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
618622
return _make_joined_pattern(pattern, {i.flags for i in exps})
619623

tests/test_grammar.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -247,10 +247,8 @@ def test_ranged_repeat_large(self):
247247
self.assertRaises(UnexpectedInput, l.parse, u'A' * 8192)
248248

249249
def test_large_terminal(self):
250-
# TODO: The `reversed` below is required because otherwise the regex engine is happy
251-
# with just parsing 9 from the string 999 instead of consuming the longest
252250
g = "start: NUMBERS\n"
253-
g += "NUMBERS: " + '|'.join('"%s"' % i for i in reversed(range(0, 1000)))
251+
g += "NUMBERS: " + '|'.join('"%s"' % i for i in range(0, 1000))
254252

255253
l = Lark(g, parser='lalr')
256254
for i in (0, 9, 99, 999):

0 commit comments

Comments
 (0)