File size: 999 Bytes
096c926 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import ast
import gast
def _generate_translators(to):
class Translator(ast.NodeTransformer):
def _visit(self, node):
if isinstance(node, list):
return [self._visit(n) for n in node]
elif isinstance(node, ast.AST):
return self.visit(node)
else:
return node
def generic_visit(self, node):
cls = type(node).__name__
# handle nodes that are not part of the AST
if not hasattr(to, cls):
return
new_node = getattr(to, cls)()
for field in node._fields:
setattr(new_node, field, self._visit(getattr(node, field)))
for attr in getattr(node, '_attributes'):
if hasattr(node, attr):
setattr(new_node, attr, getattr(node, attr))
return new_node
return Translator
AstToGAst = _generate_translators(gast)
GAstToAst = _generate_translators(ast)
|