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を受け入れます -そこに a を渡すことができます。がデフォルトです。https://github.com/eliben/pycparser/blob/master/pycparser/c_ast.py#L30を参照してください。bufStringIOsys.stdout

于 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 に答える