python - pycparser 嵌套节点访问者

标签 python c pycparser

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

最佳答案

查看类(class)评论:https://github.com/eliben/pycparser/blob/master/pycparser/c_ast.py#L107

The children of nodes for which a visit_XXX was defined will not be visited - if you need this, call generic_visit() on the node.

You can use:

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)

测试.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.     
}

关于python - pycparser 嵌套节点访问者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33668210/

相关文章:

python - 创建一个包含 n 个整数后跟一个整数的列表

c - 如何将十六进制字符串转换为无符号字符数组?

c++ - 在 Windows 上编译 MariaDB C/C++ 连接器

python - 如何使用 pycparser 删除 AST 节点?

python - 任意 C 项目的预处理

python - 有没有办法使用 pyqt 将(动画)GIF 图像作为系统托盘图标?

python - 如何在 python 中将时间对象转换为自午夜以来的秒数?

python - 列表与数据框的交叉连接(笛卡尔积)

C: 我怎样才能将文件名列表作为字符串发送到套接字上?

python - 使用 PycParser 解析 c 文件时提取输入参数及其标识符类型