pycparser嵌套节点访问者

时间:2015-11-12 09:32:44

标签: python c pycparser

我想用pycparser为每个IF语句解析带有访问者的C代码。根据我的观察,它只访问没有嵌套IF的顶级节点。这是故意的,还是我的代码中有问题?

2 个答案:

答案 0 :(得分:3)

查看课程评论:https://github.com/eliben/pycparser/blob/master/pycparser/c_ast.py#L107

  

定义了visit_XXX的节点的子节点不会   访问 - 如果需要,请在节点上调用generic_visit()。

     

您可以使用:

     

NodeVisitor.generic_visit(self,node)

我尝试了这个,它对我有用:

<强> if_conditions.py

from __future__ import print_function
import sys

# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
sys.path.extend(['.', '..'])

from pycparser import c_parser, c_ast, parse_file

class IfVisitor(c_ast.NodeVisitor):
    def __init__(self):
        pass

    def visit_If(self, node):
        node.show()
        self.generic_visit(node);



def start(filename):
    ast = parse_file(filename, use_cpp=True)
    v = IfVisitor()
    v.visit(ast)


if __name__ == "__main__":
    if len(sys.argv) > 2:
        filename = sys.argv[1]
    else:
        filename = 'examples/c_files/test.c'

    start(filename)

<强> test.c的

main ( int arc, char **argv ) {

    int i = 1;

    if (i > 1) {
        if (i > 2) {
            printf("Yay!");
        }
    }

    // code
    return 0; // Indicates that everything vent well.     
}

答案 1 :(得分:0)

generic_visit()将起作用。或者,只需重新访问子节点。

https://github.com/eliben/pycparser/blob/master/examples/func_calls.py#L29

# A visitor with some state information (the funcname it's looking for)
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)

在这种情况下(IF语句)

if node.iftrue:
    self.visit(node.iftrue)

if node.iffalse:
    self.visit(node.iffalse)