How to use the js2py.base.PyJs function in Js2Py

To help you get started, we’ve selected a few Js2Py examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
'-': '__sub__',
    '<<': '__lshift__',
    '>>': '__rshift__',
    '&': '__and__',
    '^': '__xor__',
    '|': '__or__',
    '>>>': 'pyjs_bshift'
}


def Empty():
    return Js(None)


#Number
class PyJsNumber(PyJs):  #Note i dont implement +0 and -0. Just 0.
    TYPE = 'Number'
    Class = 'Number'


NumberPrototype = PyJsObject({}, ObjectPrototype)
NumberPrototype.Class = 'Number'
NumberPrototype.value = 0

Infinity = PyJsNumber(float('inf'), NumberPrototype)
NaN = PyJsNumber(float('nan'), NumberPrototype)
PyJs.NaN = NaN
PyJs.Infinity = Infinity

# This dict aims to increase speed of string creation by storing character instances
CHAR_BANK = {}
NUM_BANK = {}
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
PyJs.MakeError = staticmethod(MakeError)


def JsToPyException(js):
    temp = PyJsException()
    temp.mes = js
    return temp


def PyExceptionToJs(py):
    return py.mes


#Scope class it will hold all the variables accessible to user
class Scope(PyJs):
    Class = 'global'
    extensible = True
    IS_CHILD_SCOPE = True

    # todo speed up
    # in order to speed up this very important class the top scope should behave differently than
    # child scopes, child scope should not have this property descriptor thing because they cant be changed anyway
    # they are all confugurable= False

    def __init__(self, scope, closure=None):
        """Doc"""
        self.prototype = closure
        if closure is None:
            # global, top level scope
            self.own = {}
            for k, v in six.iteritems(scope):
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
self.define_own_property(
            'prototype', {
                'value': proto,
                'writable': True,
                'enumerable': False,
                'configurable': False
            })

    def call(self, this, args=()):
        return self.target.call(self.bound_this, self.bound_args + args)

    def has_instance(self, other):
        return self.target.has_instance(other)


PyJs.PyJsBoundFunction = PyJsBoundFunction

OP_METHODS = {
    '*': '__mul__',
    '/': '__div__',
    '%': '__mod__',
    '+': '__add__',
    '-': '__sub__',
    '<<': '__lshift__',
    '>>': '__rshift__',
    '&': '__and__',
    '^': '__xor__',
    '|': '__or__',
    '>>>': 'pyjs_bshift'
}
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
Uint8ClampedArrayPrototype = PyJsUint8ClampedArray([], ObjectPrototype)

Int16ArrayPrototype = PyJsInt16Array([], ObjectPrototype)

Uint16ArrayPrototype = PyJsUint16Array([], ObjectPrototype)

Int32ArrayPrototype = PyJsInt32Array([], ObjectPrototype)

Uint32ArrayPrototype = PyJsUint32Array([], ObjectPrototype)

Float32ArrayPrototype = PyJsFloat32Array([], ObjectPrototype)

Float64ArrayPrototype = PyJsFloat64Array([], ObjectPrototype)


class PyJsArguments(PyJs):
    Class = 'Arguments'

    def __init__(self, args, callee):
        self.own = {}
        self.extensible = True
        self.prototype = ObjectPrototype
        self.define_own_property(
            'length', {
                'value': Js(len(args)),
                'writable': True,
                'enumerable': False,
                'configurable': True
            })
        self.define_own_property(
            'callee', {
                'value': callee,
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
temp = PyJsFunction(e.__func__, FunctionPrototype)
                attrs = dict((k, v) for k, v in attrs.iteritems())
                attrs['value'] = temp
                prototype.define_own_property(i, attrs)
        else:
            if hasattr(e, '__call__') and not i.startswith('__'):
                temp = PyJsFunction(e, FunctionPrototype)
                attrs = dict((k, v) for k, v in attrs.items())
                attrs['value'] = temp
                prototype.define_own_property(i, attrs)
        if constructor:
            attrs['value'] = constructor
            prototype.define_own_property('constructor', attrs)


PyJs.undefined = undefined
PyJs.Js = staticmethod(Js)

from .prototypes import jsfunction, jsobject, jsnumber, jsstring, jsboolean, jsarray, jsregexp, jserror, jsarraybuffer, jstypedarray

#Object proto
fill_prototype(ObjectPrototype, jsobject.ObjectPrototype, default_attrs)


#Define __proto__ accessor (this cant be done by fill_prototype since)
@Js
def __proto__():
    return this.prototype if this.prototype is not None else null


getter = __proto__
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
def PyJsComma(a, b):
    return b


from .internals.simplex import JsException as PyJsException, js_dtoa
import pyjsparser
pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError('SyntaxError', msg)


class PyJsSwitchException(Exception):
    pass


PyJs.MakeError = staticmethod(MakeError)


def JsToPyException(js):
    temp = PyJsException()
    temp.mes = js
    return temp


def PyExceptionToJs(py):
    return py.mes


#Scope class it will hold all the variables accessible to user
class Scope(PyJs):
    Class = 'global'
    extensible = True
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
def put(self, lval, val, op=None):
        if self.prototype is None:
            # global scope put, simple
            return PyJs.put(self, lval, val, op)
        else:
            # trying to put in local scope
            # we dont know yet in which scope we should place this var
            if lval in self.own:
                if op:  # increment operation
                    val = getattr(self.own[lval], OP_METHODS[op])(val)
                self.own[lval] = val
                return val
            else:
                #try to put in the lower scope since we cant put in this one (var wasn't registered)
                return self.prototype.put(lval, val, op)
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
#Null
class PyJsNull(PyJs):
    TYPE = 'Null'
    Class = 'Null'

    def __init__(self):
        pass


null = PyJsNull()
PyJs.null = null


class PyJsArray(PyJs):
    Class = 'Array'

    def __init__(self, arr=[], prototype=None):
        self.extensible = True
        self.prototype = prototype
        self.own = {
            'length': {
                'value': Js(0),
                'writable': True,
                'enumerable': False,
                'configurable': False
            }
        }
        for i, e in enumerate(arr):
            self.define_own_property(
                str(i), {
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
def to_python(val):
    if not isinstance(val, PyJs):
        return val
    if isinstance(val, PyJsUndefined) or isinstance(val, PyJsNull):
        return None
    elif isinstance(val, PyJsNumber):
        # this can be either float or long/int better to assume its int/long when a whole number...
        v = val.value
        try:
            i = int(v) if v == v else v  # nan...
            return v if i != v else i
        except:
            return v
    elif isinstance(val, (PyJsString, PyJsBoolean)):
        return val.value
    elif isinstance(val, PyObjectWrapper):
        return val.__dict__['obj']
    elif isinstance(val, PyJsArray) and val.CONVERT_TO_PY_PRIMITIVES:
github PiotrDabkowski / Js2Py / js2py / base.py View on Github external
flags = flags.to_string().value if not flags.is_undefined() else ''
    for flag in flags:
        if flag not in REG_EXP_FLAGS:
            raise MakeError(
                'SyntaxError',
                'Invalid flags supplied to RegExp constructor "%s"' % flag)
    if len(set(flags)) != len(flags):
        raise MakeError(
            'SyntaxError',
            'Invalid flags supplied to RegExp constructor "%s"' % flags)
    pattern = '/%s/' % (pattern if pattern else '(?:)') + flags
    return JsRegExp(pattern)


RegExp.create = RegExp
PyJs.RegExp = RegExp

# Number


@Js
def Number():
    if len(arguments):
        return arguments[0].to_number()
    else:
        return Js(0)


@Js
def number_constructor():
    temp = PyJsObject(prototype=NumberPrototype)
    temp.Class = 'Number'