Python分析具有未知类型的缩进C文件

时间:2019-03-04 22:06:04

标签: python c parsing

如何解析语法上正确的 C文件,其中包含单个函数但具有未定义的类型?使用this service在每个block关键字下方的括号中自动缩进文件(4个空格),例如

if ( condition1 )
{
    func1( int hi );
    unktype foo;
    do
    {
        if ( condition2 )
            goto LABEL_1;
    }
    while ( condition3 );
}
else
{
    float a = bar(baz, 0);
LABEL_1:
    int foobar = (int)a;
}

第一行是原型,第二行是“ {”。所有行都以\ n结尾。最后一行只是“} \ n” 有很多多对一的陷阱,而且标签经常不在其范围内(糟糕,我知道:D) 我只关心结构信息,即块和语句类型。这里是我想要得到的(打印时为清楚起见添加了缩进):

[If(condition = [condition1], 
    bodytrue = ["func1( int hi );", 
                "unktype foo;" 
                DoWhile(condition = [condition3], 
                        body = [
                                SingleLineIf(condition = [condition2],
                                             bodytrue =["goto LABEL_1;"], 
                                             bodyelse = []
                                )
                                ]
                )
    ]
    bodyelse = ["float a = bar(baz, 0);",
               "int foobar = (int)a;"
    ]
)]

带条件1,条件2和条件3字符串。其他构造将工作相同。 标签可以丢弃。我还需要包括与任何特殊语句无关的块,例如Block([...]). 由于类型未知,标准C语言Python解析器无法正常工作(例如pycparser给出语法错误)

1 个答案:

答案 0 :(得分:1)

Pyparsing包含a simple C parser as part of its examples,这是一个解析器,它将处理您的示例代码,以及更多一些(包括对for语句的支持)。

这不是很好的C解析器。它仅在嵌套括号中的字符串的情况下大致遍历if,while和do条件。但这可能会让您开始提取您感兴趣的位。

import pyparsing as pp

IF, WHILE, DO, ELSE, FOR = map(pp.Keyword, "if while do else for".split())
SEMI, COLON, LBRACE, RBRACE = map(pp.Suppress, ';:{}')

stmt_body = pp.Forward()
single_stmt = pp.Forward()
stmt_block = stmt_body | single_stmt

if_condition = pp.ungroup(pp.nestedExpr('(', ')'))
while_condition = if_condition()
for_condition = if_condition()

if_stmt = pp.Group(IF 
           + if_condition("condition") 
           + stmt_block("bodyTrue")
           + pp.Optional(ELSE + stmt_block("bodyElse"))
           )
do_stmt = pp.Group(DO 
           + stmt_block("body") 
           + WHILE 
           + while_condition("condition")
           + SEMI
           )
while_stmt = pp.Group(WHILE + while_condition("condition")
              + stmt_block("body"))
for_stmt = pp.Group(FOR + for_condition("condition")
            + stmt_block("body"))
other_stmt = (~(LBRACE | RBRACE) + pp.SkipTo(SEMI) + SEMI)
single_stmt <<= if_stmt | do_stmt | while_stmt | for_stmt | other_stmt
stmt_body <<= pp.nestedExpr('{', '}', content=single_stmt)

label = pp.pyparsing_common.identifier + COLON

parser = pp.OneOrMore(stmt_block)
parser.ignore(label)

sample = """
if ( condition1 )
{
    func1( int hi );
    unktype foo;
    do
    {
        if ( condition2 )
            goto LABEL_1;
    }
    while ( condition3 );
}
else
{
    float a = bar(baz, 0);
LABEL_1:
    int foobar = (int)a;
}
"""

print(parser.parseString(sample).dump())

打印:

[['if', 'condition1', ['func1( int hi )', 'unktype foo', ['do', [['if', 'condition2', 'goto LABEL_1']], 'while', 'condition3']], 'else', ['float a = bar(baz, 0)', 'int foobar = (int)a']]]
[0]:
  ['if', 'condition1', ['func1( int hi )', 'unktype foo', ['do', [['if', 'condition2', 'goto LABEL_1']], 'while', 'condition3']], 'else', ['float a = bar(baz, 0)', 'int foobar = (int)a']]
  - bodyElse: ['float a = bar(baz, 0)', 'int foobar = (int)a']
  - bodyTrue: ['func1( int hi )', 'unktype foo', ['do', [['if', 'condition2', 'goto LABEL_1']], 'while', 'condition3']]
    [0]:
      func1( int hi )
    [1]:
      unktype foo
    [2]:
      ['do', [['if', 'condition2', 'goto LABEL_1']], 'while', 'condition3']
      - body: [['if', 'condition2', 'goto LABEL_1']]
        [0]:
          ['if', 'condition2', 'goto LABEL_1']
          - bodyTrue: 'goto LABEL_1'
          - condition: 'condition2'
      - condition: 'condition3'
  - condition: 'condition1'