pythoncregexabstract-syntax-treepycparser

how to find switch statement from an ast generated from pycparser?


I am trying to parse c files using pycparser and find the switch statement I have generated the ast using https://github.com/eliben/pycparser/blob/master/examples/explore_ast.py this link. then using n = len(ast.ext) i have found the length of the exts generated from the ast. Now i have to find the switch statement from the ast i tried doing if re.findall(r'(switch(\s*'),ast.ext) and match regex to find switch case but it isnt happening. How to proceed with this as i am entirely new to pycparser and have no idea about it


Solution

  • You can't run regexp matching on pycparser ASTs!

    There are multiple examples in the pycparser repository that should help you: explore_ast.py, which you've already seen lets you play with the AST and explore its nodes.

    dump_ast.py shows how to dump the whole AST and see what nodes your code has.

    Finally, func_calls.py demonstrates how to walk the AST looking for specific kinds of nodes:

    class FuncCallVisitor(c_ast.NodeVisitor):
        def __init__(self, funcname):
            self.funcname = funcname
    
        def visit_FuncCall(self, node):
            if node.name.name == self.funcname:
                print('%s called at %s' % (self.funcname, node.name.coord))
            # Visit args in case they contain more func calls.
            if node.args:
                self.visit(node.args)
    

    In this case FuncCall nodes, but you need switch nodes, so you'll create a method named visit_Switch, and the visitor will find all Switch nodes.