生成C / C ++代码时的表达式的关联性和优先级? [英] Associativity and Precedence of Expressions when Generating C / C++ Code?

本文介绍了生成C / C ++代码时的表达式的关联性和优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个基本的编译器,它生成一个AST,正确地考虑了表达式中的运算符优先级。但是,当执行代码生成以生成C ++代码时,我不确定如何处理使用括号。

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.

对于此表达式:

A - (B - c)

以下AST:

   -
  / \
 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.

推荐答案

在历史上,他们称之为漂亮的印刷。如果你的Google加上优先,你可能会找到一些例子来帮助你。

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.

这篇关于生成C / C ++代码时的表达式的关联性和优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆