I'm doing a homework assignment where I am give some BNF grammar:
<assign> -> <id> = <expr>
<id> -> A | B | C
<expr> -> <expr> + <term>
| <term>
<term> -> <term> * <factor>
| <factor>
<factor> -> ( <expr> )
| <id>
and the question is:
"Rewrite this grammar so that the +
operator is right associative and takes precedence over the *
operator."
A classmate suggested we simply switch the +
and *
operators and then +
will have precedence and gain right association, however I don't think this is correct since the question is recursive.
My question is, does the +
operator gain precedence and right association by simply switching it with the *
operator? My two thoughts are to remove the recursion and do what my classmate suggests, or put the +
operator in a condition where is must be surrounded by (
and )
to work.
Maybe I'm over thinking this?
+
and*
in the grammar will clearly swap the precedence, but making them right-associative is a seperate step – Mooing DuckA = B * (C + (C + (C + C)))
– Ryan Tibbetts