我怎么括起的前pression编程?我怎么、pression

2023-09-11 04:17:55 作者:不怕死只怕你离开

我有一个想法,一个简单的程序来进行,这将帮助我运营商precedence的语言,如C。这方面最困难的部分是圆括号前pression。例如,我想这样的:

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++

转换为这样的:

Converted to this:

((*(((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))++)))

什么是编程方式实现这一目标的最佳途径?是否已有一个解决方案,在那里,我可以用?我想preFER做到这一点在任何PHP,C,C ++,Python和或Ruby。

What is the best way to accomplish this programmatically? 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.)

推荐答案

只要拿起一个解析器为您选择的语言,例如Ç解析器,解析EX pression /源$ C ​​$ 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>
>>>