0

I want to express this grammar in scala StdTokenParsers:

expr -> expr ("+"|"-") ~ muldivexpr | muldivexpr

"+" and "-" is left associative.

The grammar is left recursive so it caused infinite recursions. I can rewrite to remove left recursion, but it will change to right associativity.

Now I am planning to use scala rep() to rewrite it as:

expr -> rep(muldivexpr ("+"|"-")) ~ muldivexpr

but will rep() that change the associativity? How does rep() work in this case?

I am asking this question because I have to output the AST in the future.

minhnhat93
  • 141
  • 1
  • 2
  • 13

1 Answers1

1

You are most likely looking for:

chainl1[T](p: => Parser[T], q: => Parser[(T, T) => T]): Parser[T]

The general idea is p is an operand, and q is a separator yielding a function which can combine two operands, e.g.

chainl1(muldivexpr,
  "+" ^^^ { (l: Expr, r: Expr) => Addition(l, r)    }
| "-" ^^^ { (l: Expr, r: Expr) => Subtraction(l, r) }
)
J Cracknell
  • 3,498
  • 1
  • 19
  • 13