0

我使用 PycParser 为 C 函数生成抽象语法树,但我仍在尝试弄清楚如何将解析树转换为字符串:

from pycparser import c_parser

src =  '''
int hello(a, b){
    return a + b;
}
'''
ast = c_parser.CParser().parse(src)
aString = ast.show()
print(aString) #This prints "None" instead of printing the parse tree

是否可以从已生成的解析树中生成一个字符串(或字符串数​​组)?

这是打印的抽象语法树,但我不知道如何将其转换为字符串:

FileAST: 
  FuncDef: 
    Decl: hello, [], [], []
      FuncDecl: 
        ParamList: 
          ID: a
          ID: b
        TypeDecl: hello, []
          IdentifierType: ['int']
    Compound: 
      Return: 
        BinaryOp: +
          ID: a
          ID: b
4

2 回答 2

1

show方法接受一个buf关键字参数——你可以在那里传递一个StringIOsys.stdout是默认值。见https://github.com/eliben/pycparser/blob/master/pycparser/c_ast.py#L30

于 2014-10-17T23:28:03.030 回答
0

请试试这个

from pycparser import c_parser
src =  '''
     int hello(a, b){
        return a + b;
     }
'''
ast = c_parser.CParser().parse(src)
ast_buffer_write=open("buffer.txt","w") # here will be your AST source
ast.show(ast_buffer_write)
ast_buffer_write.close()
ast_buffer_read=open("buffer.txt","r")
astString=ast_buffer_read.read()
print(astString)
于 2015-11-17T15:03:06.033 回答