【问题标题】:pycparser visit else only of an if-else statementpycparser 仅访问 if-else 语句的 else
【发布时间】:2018-09-16 13:24:54
【问题描述】:

我正在使用 pycparser 来解析一些 C 代码。具体来说,我需要代码的某些部分,pycparser 中包含一些访问者,例如 visit_If 来访问代码的 "If" 部分。但是,我在访问 if-else 语句的 'else' 部分时遇到问题。

示例 1:

if (x == 0)
{
    // some statements
}
else
{
    // some statements -> I only need all codes under else
}

示例 2:

if (x == 0)
    // a statement
else
    // a statement -> I only need all codes under else

这在 pycparser 中怎么可能?

【问题讨论】:

    标签: python python-3.x pycparser


    【解决方案1】:

    If 节点有一个 iffalse 子节点,它是原始代码中的 else 子句。例如,see the C code generatorpycparser 的一部分):

    def visit_If(self, n):
        s = 'if ('
        if n.cond: s += self.visit(n.cond)
        s += ')\n'
        s += self._generate_stmt(n.iftrue, add_indent=True)
        if n.iffalse:
            s += self._make_indent() + 'else\n'
            s += self._generate_stmt(n.iffalse, add_indent=True)
        return s
    

    这是访问If 节点并访问其所有子节点的一个很好的示例。

    【讨论】:

    • 我还想问知道如何获取“else”行的行号。我知道它在 coord.line 但示例 1 的 iffalse coord.line 指向“{”。有办法吗?
    • @Thor,它应该指向正确的位置。这可能是一个错误,所以请用最小的复制器打开一个 Github 问题
    • 接受的答案。我添加了一个github问题
    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2017-02-05
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多