1

Is it possible to create a grammar that has a rule with multiple operators with the same level of precedence but different associativity?

For example "+" and "-" both have same precedence and associativity (left assoc.)

But if I want to change "+" to right associative but with the same precedence how can I do that ?

I tried:

expr:  expr op=('*'|'/') expr                   # MulDiv
   |   expr op=(<assoc=right>'+'|'-') expr      # AddSub
   |   INT                                      # int
   |   ID                                       # id
   |   '(' expr ')'                             # parens
   ;

And @LucasTrzesniewski. Still does not work your suggestion

addSubOp: <assoc=right>'+'| <assoc=lefts>'-'; expr: expr op=('*'|'/') expr # MulDiv | expr addSubOp expr # AddSub | INT # int | ID # id | '(' expr ')' # parens ;

But with no success.

  • is there such a thing called "operators with the same level of precedence but different associativity"? I've been asking such a question some time ago http://stackoverflow.com/questions/11700550/why-associativity-is-a-fundamental-property-of-operators-but-not-that-of-precede . In those languages I know of e.g. C++, operators with the same precedence are having the same associativity – JavaMan Dec 01 '16 at 18:04
  • Yes it is possible it might not be popular (it might be only academic) but still it is possible. Precedence is a separate abstract from associativity. – Radoslaw A Dembkowski Dec 02 '16 at 01:09
  • but what is, say, `a+b-c` if `+` is left associative while `-` is right associative? – JavaMan Dec 02 '16 at 06:42
  • Have you tried to extract the operator to its own rule? `addSubOp: '+'|'-';`? – Lucas Trzesniewski Dec 02 '16 at 09:30
  • @LucasTrzesniewski Still nothing – Radoslaw A Dembkowski Dec 02 '16 at 16:51

0 Answers0