Reputation: 31850
I used PycParser to generate an abstract syntax tree for a C function, but I'm still trying to figure out how to convert the parse tree into a string:
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
Would it be possible to generate a string (or an array of strings) from the parse tree that has been generated?
This is the abstract syntax tree that was printed, but I can't figure out how to convert it to a string:
FileAST:
FuncDef:
Decl: hello, [], [], []
FuncDecl:
ParamList:
ID: a
ID: b
TypeDecl: hello, []
IdentifierType: ['int']
Compound:
Return:
BinaryOp: +
ID: a
ID: b
Upvotes: 0
Views: 1179
Reputation: 1
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)
Upvotes: 0
Reputation: 273706
The show
method accepts a buf
keyword parameter - you can pass a StringIO
there. sys.stdout
is the default. See https://github.com/eliben/pycparser/blob/master/pycparser/c_ast.py#L30
Upvotes: 1