You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
997 B

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