nom icon indicating copy to clipboard operation
nom copied to clipboard

Implement new parser `left_assoc`.

Open rodrigorc opened this issue 1 year ago • 0 comments

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 avatar Aug 12 '24 20:08 rodrigorc