Question

Does anyone know a tool I can use to generate Python code from AST?

I have successfully written a tokenizer and a parser, but I'm looking for a more Pythonic way to generate Python code from that. I've used LLVMPY before, and I was wondering if there is something like that I can use to generate Python code instead of LLVM IR.

Your suggestions will be highly appreciated :-)

EDIT

This is not Python AST. It's from my own language, so I know there isn't a tool that can magically understand it. I'm just looking for something that can meet me half-way in terms of generating Source Code.

For example:

Instead of concatenating strings to produce a = 1 + 2, have something like a = builder.add(1,2). Basically anything that would save me the pain of generating strings and handling indents manually. Is there such?

I already have a class that consumes the AST but I find myself having to do something like this everywhere:

...
elif node.type == "Assign":
    _buffer = self.descend(node.args[0])
    _buffer += self.descend(node.args[1])
    _buffer += self.descend(node.args[2])
    return _buffer

elif node.type == "BinOp":
    _buffer = self.descend(node.args[1])
    _buffer += node.args[0]
    _buffer += self.descend(node.args[2])
    return _buffer
...

This gets even more tideous when I have to implement bigger objects like Functions and Classes. I am just wondering if there isn't a better way to do this.

Était-ce utile?

La solution

There is python module ast that enables this. If you are doing own tokaniser, you might just need evaluator of ast and compile() that evaluate ast. There is also unparser that generates python code from ast and can be found in python source repo. unparse.py

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top