Longest match lexer option to mimic the Unix tool Lex #1490
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi. I added a lexer for the lalr parser as a complement, which mimics the behavior of the Unix tool Lex and libraries such as flex. The behavior in question is to: match with the longest match found; if there are multiple longest matches the precedence of the terminals is in the order that they are defined.
This also means that the terminals are not sorted according to the priority rules defined in grammar.md:
By not relying on the above rules for precedence, it is possible to use grammars defined for Lex and its derivations in Lark.
Below follows an example using
longest_match
:This is a grammar that neither the basic nor contextual lexer can deal with. Both will use AB, and the contextual will not try AC as AB is a possible token to parse from start. It's not possible for the programmer to set the precedence in this scenario to tokenize "ab" or "ac" correctly. Using basic yields:
Using contextual yields:
Regarding the implementation it consists of a new lexer and a new scanner: LongestMatchLexer, which inherits from BasicLexer; LongestMatchScanner, which attempts to match against every terminal, yielding the longest match. (Not optimal - but it's an option.)
It seems some other users have attempted to use longest matches (as I tried when I used lark first):
#370
#1463
Edit:
An issue with using earley instead, is that it may not yield the desired result for ambiguous grammars such as in the example below (which is a simplification of a grammar that worked for a lex derivation):
Which yields: