Assume this code works:
left '*'
left '+'
expr: expr '+' expr
| expr '*' expr
;
I want to define an other precedence marker like:
left MULTIPLY
left PLUS
expr: expr '+' expr %prec PLUS
| expr '*' expr %prec MULTIPLY
;
Yet this is not actually effective.
I suppose these two forms should be equivalent, however, they’re not.
It’s not on practical problem. I just want to know the reason and the principle for this phenomenon.
Thanks.
You say you are not trying to solve a specific, practical problem. And from your question, I’m a little confused about how you are trying to use the precedence marker.
I think you will find that you don’t need to use the precedence marker often. It is usually simpler, and clearer to the reader, to rewrite your grammar so that precedence is explicitly accounted for. To give multiply and divide higher precedence than add and subtract, you can do something like this (example adapted from John Levine, lex & yacc 2/e, 1992):
In your example,
PLUSandMULTIPLYare not real tokens; you can’t use them interchangeably with'+'and'*'. Levine calls them pseudo-tokens. They are there to link your productions back to your list of precedences that you have defined with%leftand%nonassocdeclarations. He gives this example of how you might use%precto give unary minus high precedence even though the ‘-‘ token has low precedence:To sum up, I would recommend following the pattern of my first code example rather than the second; make the grammar explicit.