Tuesday, December 6, 2011

Assignment as an expression in Antlr grammar

Look at this example of statement:
a = b = 4;
This statement consists of two assignments: b = 4 is an assignment expression, and a = b = 4; is an assignment statement

Here is the topic on stackoverflow about how to define an assignment as an expression in ANTLR grammar. I gave one of the answers, but you should see the other that uses syntactic predicates. It turned out to be very good example if you want to understand how to effectively use syntactic predicates.
I will present you here how to define assignment expression

About an assignment expression

What is so special about assignment expression? There is one crucial difference between operators like + or *, and an assignment operator =. It is right associative. So, if you write a = b = 4;  b = 4 is evaluated first. (In contrary if you write 2 + 3 + 4, 2+3 is evaluated first). Next thing is that assignment operator has almost the lowest precedence (only comma operator has lower precedence in C). So when you add the assignment expression to you grammar, it has to be on the top of the other expressions.

Simple ANTLR grammar with an assignment expression

Here is the complete example in ANTLR parser grammar:

As you can see, expression is defined as an assignment expression or like an add expression:
The way assign expression is defined ensures it's right associativity, since expr on the right side of the Assign token is always evaluated first. Also, this way of definition ensures the lowest precedence of the assign operator. A few parse tree examples are given below:

Statement       a = 2 + 3;  gives the following parse tree:

And statements

a=b=4;
a = 2 * (b = 1);

give the following parse tree:

No comments:

Post a Comment