首页 > 解决方案 > 如何从 pycparser 生成的 ast 中找到 switch 语句?

问题描述

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

标签: pythoncregexabstract-syntax-treepycparser

解决方案


您不能在 pycparser AST 上运行正则表达式匹配!

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节点。


推荐阅读