Associativity and Precedence of Expressions when Generating C / C++ Code?

試著忘記壹切 提交于 2019-12-10 19:59:55

问题


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.


回答1:


Historically, they call this "pretty printing". If you Google that plus "precedence", you may find some examples to help you.

Informally, I think the basic idea is that when you recurse into a subexpression, you compare its precedence to the current expression. If it's lower, you need parentheses. Otherwise you don't. Associativity can be handled by doing a similar check: if the subexpression has the same precedence as the parent you need parentheses if it's on the wrong side according to associativity.




回答2:


If an operation with a higher precedence is lower in the tree you don't need to put it into parentheses.

It is not enough to know the precedence of the operations though. You also need to know the associativity of the operations. It allows to group operations of equal precedence properly. Say, subtraction is left associative, so A-B-C is equal to (A-B)-C, but not to A-(B-C).

Just write down the whole table of precedence and associativities for all your operations and consult it as you generate your expression.



来源:https://stackoverflow.com/questions/4306680/associativity-and-precedence-of-expressions-when-generating-c-c-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!