pycparser visit else only of an if-else statement

382 views Asked by At

I'm using pycparser to parse some C code. Specifically, I need certain portions of the code, included in pycparser are some visitors like visit_If to visit "If" sections of the code. However, I'm having problem visiting 'else' part of an if-else statement.

Example 1:

if (x == 0)
{
    // some statements
}
else
{
    // some statements -> I only need all codes under else
}

Example 2:

if (x == 0)
    // a statement
else
    // a statement -> I only need all codes under else

How is this possible in pycparser?

1

There are 1 answers

3
Eli Bendersky On BEST ANSWER

The If node has an iffalse child node which is the else clause from the original code. For example, see the C code generator (part of pycparser):

def visit_If(self, n):
    s = 'if ('
    if n.cond: s += self.visit(n.cond)
    s += ')\n'
    s += self._generate_stmt(n.iftrue, add_indent=True)
    if n.iffalse:
        s += self._make_indent() + 'else\n'
        s += self._generate_stmt(n.iffalse, add_indent=True)
    return s

This is a good example of visiting an If node and accessing all its child nodes.