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!

2
  • 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?) Commented Nov 21, 2015 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... Commented Nov 21, 2015 at 23:01

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.