Original Post
I'm writing a small language parser. Addition and subtraction are left-associative. In other words, 3+3+3 means (3+3)+3. In my grammar, it's basically this:
Expression ::= Expression + Term | Term I'm having trouble getting my mind around this problem. If it was right-associative, my parsing function for this rule would be something like this:
Expression ParseExpression() {
Term tLeft = ParseTerm();
if(NextToken().Type == Plus)
return new Addition(tLeft, ParseExpression());
else
return tLeft;
}
In fact, I originally wrote the function that way, and it worked great--except that my additions were all right-associative instead of left-associative. The problem, of course, is that my function would get into an infinite loop if I tried to do this instead:
Expression ParseExpression() {
Expression eLeft = ParseExpression();
if(NextToken().Type == Plus)
return new Addition(eLeft, ParseTerm());
else
return eLeft;
}
So, what do I have to change to implement left-associativity? [edit: Fixed grammar] Thanks, [Edited by - BeanDog on September 27, 2006 6:28:13 PM]