Search code examples
algorithmparsingoperator-precedenceparentheses

How do I parenthesize an expression?


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

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.)


Solution

  • 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;
    }
    

    terminal:

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