Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement new parser left_assoc. #1775

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

rodrigorc
Copy link

This PR adds a new combinator left_assoc to parse left-associative operators.

Parsing operator with different precedence in nom has usually been a bit of a challenge. There is this other PR#1362, but it seems a bit stalled.

The classical alternative in LALR grammars is to use a recursive rule such as:

A := A op B | B

Alas, that can't be parsed easily with nom because it will recurse infinitely.

The solution is to parse it with this other equivalent rule:

A := B (op B)*

while calling a callback to give the user the chance to build the AST, or whatever.

This could be implemented as a call to B and then fold_many0 with the pair(op, B). Instead, I chose copying the separated_list1 code (that OM thing is tricky).

As an alternative public API, the type of the left expression and that of the right expression could be different. Then we would need two separated parsers, left and right returning types L and R; and the builder would be of type FnMut(L, OP, R) -> L. Maybe another combinator, left_assoc_2() could be added for that?

@rodrigorc rodrigorc requested a review from Geal as a code owner August 12, 2024 20:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant