How to implement indexes in Parsec?

I am writing a parser in Parsek. Left-recursive works, such as E โ†’ E + E, cannot be easily written in the LL parser, so Parsec provides a buildExpressionParser that supports the infix, postfix and prefix operators. But what about index operators?

How will E โ†’ E [E] be implemented? If I could use a closing bracket without consuming a second expression, then I could imitate it by writing an Infix table entry for buildExpressionParser . Thoughts?

Edit: I know there is an algorithm for eliminating left recursion, which is likely to work for my grammar. I am looking for something simple or well-distracted (like buildExpressionParser ). Otherwise, I just use Happy.

+4
source share
1 answer

In our project, we manually removed left recursion from the expressions. This works as follows:

We have created a general expression form, which is parameterized by the term parser:

 expressionGen :: MParser (Expr LocInfo) -> MParser (Expr LocInfo) expressionGen term = buildExpressionParser precedenceTable term <?> "expression" where precedenceTable = -- unary, binary expressions 

We have a normal parser, and the parser has no recursive rules. At the same time, we can analyze (several) indices:

 term :: MParser (Expr LocInfo) term = do indBase <- termNoArray indexes <- many $ (brackets expression >>= return) return -- semantics <?> "term" termNoArray :: MParser (Expr LocInfo) termNoArray = -- normal terms 

Finally, we have the topmost parser for expressions: expression = expressionGen term

+1
source

Source: https://habr.com/ru/post/1487981/


All Articles