Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a left associative operator be expressed in a way such that top-down LL(1) parsers can understand?

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?

like image 826
devoured elysium Avatar asked May 06 '13 19:05

devoured elysium


1 Answers

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().

like image 167
ebohlman Avatar answered Sep 30 '22 12:09

ebohlman