I have written a basic compiler which generates an AST, correctly taking account of the operator precedence in expressions. However, when performing code generation to produce C++ code, I'm unsure of how to handle the use of brackets.
For this expression:
A - (B - c)
The AST below:
-
/ \
A -
/ \
B C
Should correctly generate the previous expression including the parentheses, however if the second operator was an addition operator (for example), the parentheses would be unecessary. I would prefer to only use them where necessary to improve readability.
Are there any rules dictating this kind of behaviour and how to know when to use parentheses. Plus and minus have the same level of precedence in most languages and I'd like to make this work for all operators.