Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def generic_visit(self, node):
"""Throwing an error by default."""
raise Py2JSSyntaxError('Unsupported {} node'.format(node.__class__.__name__))
def visit_UnaryOp(self, node):
"""Turn a Python unaryop expression into JavaScript code."""
if isinstance(node.op, ast.Not):
return '!({})'.format(self.visit(node.operand))
if isinstance(node.op, ast.USub):
return '-{}'.format(self.visit(node.operand))
if isinstance(node.op, ast.UAdd):
return '+{}'.format(self.visit(node.operand))
raise Py2JSSyntaxError('Unsupported {} operator'.format(node.op.__class__.__name__))
def _visit_binop_impl(self, left_node, op, right_node):
left = left_node if isinstance(left_node, str) else self.visit(left_node)
right = self.visit(right_node)
# Use Array.indexof or String.indexof depending on the right type
# if isinstance(op, ast.In):
# return 'indexof({}, {}) != -1'.format(right, left)
# if isinstance(op, ast.NotIn):
# return 'indexof({}, {}) == -1'.format(right, left)
if isinstance(op, ast.Pow):
return 'Math.pow({}, {})'.format(left, right)
operator = OPERATOR_MAPPING.get(op.__class__)
if operator is None:
raise Py2JSSyntaxError('Unsupported {} operator'.format(op.__class__.__name__))
return '{} {} {}'.format(left, operator, right)
def visit_Subscript(self, node):
"""Turn a Python Subscript node into JavaScript code."""
value = self.visit(node.value)
if isinstance(node.slice, ast.Index):
return '{value}[{index}]'.format(
value=value,
index=self.visit(node.slice.value)
)
raise Py2JSSyntaxError('Unsupported {} node'.format(node.slice.__class__.__name__))
def __init__(self, message):
error_msg = message + ', note that only a subset of Python is supported'
super(Py2JSSyntaxError, self).__init__(error_msg)