I was trying to implement a LL(1) top-down parser for a calculator language. It only allows us to sum, subtract, divide and multiply numbers. No parentheses.
S -> A
A -> B + A
| B - A
| B
B -> int * B
| int / B
| int
As this grammar is not suited to a LL(1) parser, I had to change it quite a bit:
S -> A
A -> B A'
A'-> + A
| - A
| λ
B -> int B'
B'-> * B
| / B
| λ
The problem is that now the grammar is not left associative for the 4 shown operators, and I need it to be so. How to solve this problem? Is it even possible to accomplish so?
You can get left-associativity by replacing recursion with iteration. The following sort-of-pseudocode directly computes values just for simplicity, but you could generate a parse tree using the same method.
function A() {
val = B();
t = peek();
while (t=='+' || t=='-') {
match(t);
val1 = B();
if (t=='+')
val = val + val1;
else
val = val - val1;
t = peek();
}
return(val)
}
where peek()
returns the next token without eating it, and match()
eats the next token. You'd do the same thing for B().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With