How to use the js2py.internals.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 / internals / base.py View on Github external
return self.pat.match(string, int(pos))


class PyJsError(PyJs):
    Class = 'Error'
    extensible = True

    def __init__(self, message=None, prototype=None):
        self.prototype = prototype
        self.own = {}
        if message is not None:
            self.put('message', to_string(message))
            self.own['message']['enumerable'] = False


class PyJsDate(PyJs):
    Class = 'Date'
    UTCToLocal = None  # todo UTC to local should be imported!

    def __init__(self, value, prototype=None):
        self.value = value
        self.own = {}
        self.prototype = prototype

    # todo fix this problematic datetime part
    def to_local_dt(self):
        return datetime.datetime.utcfromtimestamp(
            self.UTCToLocal(self.value) // 1000)

    def to_utc_dt(self):
        return datetime.datetime.utcfromtimestamp(self.value // 1000)
github PiotrDabkowski / Js2Py / js2py / internals / base.py View on Github external
repr(kind))
            i += 1

    def _set_props(self, prop_descs):
        for prop, desc in six.iteritems(prop_descs):
            self.define_own_property(prop, desc)


# Array


# todo Optimise Array - extremely slow due to index conversions from str to int and back etc.
# solution - make get and put methods callable with any type of prop and handle conversions from inside
# if not array then use to_string(prop). In array if prop is integer then just use it
# also consider removal of these stupid writable, enumerable etc for ints.
class PyJsArray(PyJs):
    Class = 'Array'

    def __init__(self, length, prototype=None):
        self.prototype = prototype
        self.own = {
            'length': {
                'value': float(length),
                'writable': True,
                'enumerable': False,
                'configurable': False
            }
        }

    def _init(self, elements):
        for i, ele in enumerate(elements):
            if ele is None: continue
github PiotrDabkowski / Js2Py / js2py / internals / base.py View on Github external
elif typ == float:
        # use standard number prototype
        return space.NumberPrototype.get(prop)
    elif typ == bool:
        return space.BooleanPrototype.get(prop)
    elif typ in (UNDEFINED_TYPE, NULL_TYPE):
        raise MakeError('TypeError',
                        "Cannot read property '%s' of undefined" % prop)
    else:
        raise RuntimeError('Unknown type! - ' + repr(typ))


# Object


class PyJsObject(PyJs):
    TYPE = 'Object'
    Class = 'Object'

    def __init__(self, prototype=None):
        self.prototype = prototype
        self.own = {}

    def _init(self, props, vals):
        i = 0
        for prop, kind in props:
            if prop in self.own:  # just check... probably will not happen very often.
                if is_data_descriptor(self.own[prop]):
                    if kind != 'i':
                        raise MakeError(
                            'SyntaxError',
                            'Invalid object initializer! Duplicate property name "%s"'
github PiotrDabkowski / Js2Py / js2py / internals / base.py View on Github external
old_len_desc['value'] = index + 1.
            return True
        else:
            return PyJs.define_own_property(self, prop, desc, False)

    def to_list(self):
        return [
            self.get(str(e)) for e in xrange(self.get('length').to_uint32())
        ]


# database with compiled patterns. Js pattern -> Py pattern.
REGEXP_DB = {}


class PyJsRegExp(PyJs):
    Class = 'RegExp'

    def __init__(self, body, flags, prototype=None):
        self.prototype = prototype
        self.glob = True if 'g' in flags else False
        self.ignore_case = re.IGNORECASE if 'i' in flags else 0
        self.multiline = re.MULTILINE if 'm' in flags else 0
        self.value = body

        if (body, flags) in REGEXP_DB:
            self.pat = REGEXP_DB[body, flags]
        else:
            comp = None
            try:
                # converting JS regexp pattern to Py pattern.
                possible_fixes = [(u'[]', u'[\0]'), (u'[^]', u'[^\0]'),
github PiotrDabkowski / Js2Py / js2py / internals / base.py View on Github external
dt = self.to_utc_dt()
        except:
            raise MakeError(
                'TypeError',
                'unsupported date range. Will fix in future versions')
        try:
            return dt.strftime(pattern)
        except:
            raise MakeError(
                'TypeError',
                'Could not generate date string from this date (limitations of python.datetime)'
            )


# Scope class it will hold all the variables accessible to user
class Scope(PyJs):
    Class = 'Global'
    extensible = True
    IS_CHILD_SCOPE = True
    THIS_BINDING = None
    space = None
    exe = None

    # 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, space, parent=None):
        """Doc"""
        self.space = space
        self.prototype = parent
github PiotrDabkowski / Js2Py / js2py / internals / base.py View on Github external
'configurable': False
            },
            'lastIndex': {
                'value': 0.,
                'enumerable': False,
                'writable': True,
                'configurable': False
            }
        }

    def match(self, string, pos):
        '''string is of course a py string'''
        return self.pat.match(string, int(pos))


class PyJsError(PyJs):
    Class = 'Error'
    extensible = True

    def __init__(self, message=None, prototype=None):
        self.prototype = prototype
        self.own = {}
        if message is not None:
            self.put('message', to_string(message))
            self.own['message']['enumerable'] = False


class PyJsDate(PyJs):
    Class = 'Date'
    UTCToLocal = None  # todo UTC to local should be imported!

    def __init__(self, value, prototype=None):
github PiotrDabkowski / Js2Py / js2py / internals / base.py View on Github external
obj = space.NewObject()
    obj.Class = 'Arguments'
    obj.define_own_property(
        'length', {
            'value': float(len(args)),
            'writable': True,
            'enumerable': False,
            'configurable': True
        }, False)
    for i, e in enumerate(args):
        obj.put(unicode(i), e)
    return obj


#Function
class PyJsFunction(PyJs):
    Class = 'Function'
    source = '{ [native code] }'
    IS_CONSTRUCTOR = True

    def __init__(self,
                 code,
                 ctx,
                 params,
                 name,
                 space,
                 is_declaration,
                 definitions,
                 prototype=None):
        self.prototype = prototype
        self.own = {}