如何给表达式加上括号? [英] How do I parenthesize an expression?

查看:117
本文介绍了如何给表达式加上括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的程序可以帮助我在C之类的语言中使用运算符优先级.这个过程中最困难的部分是在表达式中加上括号.例如,我想要这样:

I have an idea for a simple program to make that will help me with operator precedence in languages like C. The most difficult part of this is parenthesizing the expression. For example, I want this:

*a.x++ = *b.x++

已转换为此:

((*(((a).(x))++)) = (*(((b).(x))++)))

我在以下步骤中手动进行过:

Which I did manually in these steps:

           *a.x++ = *b.x++
       *(a).(x)++ = *(b).(x)++
     *((a).(x))++ = *((b).(x))++
   *(((a).(x))++) = *(((b).(x))++)
 (*(((a).(x))++)) = (*(((b).(x))++))
((*(((a).(x))++)) = (*(((b).(x))++)))

完成此任务的最佳方法是什么?我已经可以使用一种解决方案了吗?我更愿意在PHP,C,C ++,Python或Ruby中进行此操作.

What is the best way to accomplish this? Is there already a solution out there that I could use? I'd prefer to do this in either PHP, C, C++, Python, or Ruby.

(这不是我程序的整体思想,只是第一步.)

(This isn't the whole idea of my program, it is only the first step.)

推荐答案

只需为您选择的语言选择一个解析器,例如 C解析器,解析表达式/源代码,并以您想要的方式打印回AST.

Just pick up a parser for your selected language, for instance C parser, parse the expression/source code and print the AST back in the way you want.

test.c:

void main(void){
    int c = 2;
}

终端:

$ python
>>> import pycparser
>>> test = pycparser.parse_file('test.c')
>>> test.show()
FileAST: 
  FuncDef: 
    Decl: main, [], []
      FuncDecl: 
        ParamList: 
          Typename: []
            TypeDecl: None, []
              IdentifierType: ['void']
        TypeDecl: main, []
          IdentifierType: ['void']
    Compound: 
      Decl: c, [], []
        TypeDecl: c, []
          IdentifierType: ['int']
        Constant: int, 2
>>> for node in test.ext:
...     print node
...
<pycparser.c_ast.FuncDef object at 0x7fe1436db750>
>>>

这篇关于如何给表达式加上括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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