如何从pycparser生成的ast中查找switch语句?

2024-09-30 01:20:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pycparser解析c文件并找到switch语句 我使用https://github.com/eliben/pycparser/blob/master/examples/explore_ast.py这个链接生成了ast。 然后使用n=len(ast.ext)我找到了从ast生成的ext的长度。 现在我必须从ast中找到switch语句 我试过了 if re.findall(r'(开关(\s*),ast.ext) 并匹配正则表达式以查找开关大小写,但它没有发生。 由于我对pycparser完全陌生,对此一无所知,因此如何进行此操作


Tags: 文件pyhttpsgithubmastercom语句ast
1条回答
网友
1楼 · 发布于 2024-09-30 01:20:42

无法在pycparser AST上运行regexp匹配

pycparser存储库中有多个示例可以帮助您:explore_ast.py,您已经看到了它可以让您使用AST并探索其节点

dump_ast.py演示如何转储整个AST并查看代码中有哪些节点

最后,func_calls.py演示了如何遍历AST以查找特定类型的节点:

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)

在本例中FuncCall节点,但您需要切换节点,因此您将创建一个名为visit_Switch的方法,访问者将找到所有Switch节点

相关问题 更多 >

    热门问题