python - 如何从 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 完全陌生,对此一无所知
解决方案
您不能在 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
节点。
推荐阅读
- vue.js - Nuxt - 在动态路由中访问异步数据
- flutter - 如何使用 PageView 显示多个页面?
- aws-amplify - 如何在邮递员中进行 AWS Amplify 的登录和注册
- cmd - 7z 只列出文件名
- mysql - 将日期作为整数从 MySQL 转换为 Excel 中的日期
- r - 是否有可以将十进制格式(41183.50417)的日期时间字段转换为 dd/mm/yyyy hh:mm:ss 的 R 函数
- mysql - SQL 按一组获取用户但排除其他用户
- android - Activity 如何创建窗口来设置布局
- dart - 将整数位模式解析为 IEEE 754 在飞镖中浮动
- docusignapi - 如何设置自定义选项卡字段的值?