If:
- You don't care about how either
+
operator (addition or concatenation) associates; and - You don't need to be able to use parentheses around string expressions,
then there is a solution. I regard it more as an intellectual exercise than a practical solution, partly because the above requirements are highly restrictive, and partly because I don't think you should use the same operator with two different precedences. (In fact, I'm not a big supporter of using +
for concatenation. It's different enough that it deserves its own symbol.)
The following solution works pretty hard to make sure that string expressions are distinguishable from arithmetic expressions, which requires that string expressions cannot start with a (
. In order to avoid premature reduction of concatenation, it makes the concatenation version of +
associate to the right, while the addition version associates to the left as normal.
S : E '+' A
| E
| A
;
A : QUOT '+' S
| QUOT
;
E : E '+' T
| E '-' T
| T
;
T : T '*' F
| T '/' F
| F
;
F : NUM
| '(' E ')'
;