1

A typical BNF defining arithmetic operations:

E :- E + T
  |  T
T :- T * F
  |  F
F :- ( E )
  | number

Is there any way to re-write this grammar so it could be implemented with an LR(0) parser, while still retaining the precedence and left-associativity of the operators? I'm thinking it should be possible by introducing some sort of disambiguation non-terminals, but I can't figure out how to do it.

Thanks!

Fredrik
  • 97
  • 7
  • It's been a while since I did parser theory, but isn't that already an lalr(1) grammar? (and if so, isn't creating an lr(0) parser just grunt work?) – thebjorn Nov 21 '15 at 20:15
  • It could be that it is, or it may be just SLR. I am curios as to whether there are any workarounds to shift/reduce problems like these. Seems like alot of trouble to have to implement LALR for simple arithmetics... – Fredrik Nov 21 '15 at 23:01

1 Answers1

1

A language can only have an LR(0) grammar if it's prefix-free, meaning that no string in the language is a prefix of another. In this case, the language you're describing isn't prefix-free. For example, the string number + number is a prefix of number + number + number.

A common workaround to address this would be to "endmark" your language by requiring all strings generated to end in a special "done" character. For example, you could require that all strings generated end in a semicolon. If you do that, you can build an LR(0) parser for the language with this grammar:

S → E;

E → E + T | T

T → T * F | F

F → number | (E)

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065