Example #1
0
def getappfileloader(pkgroot, appname, spec):
    """ NOT_RPYTHON """
    # hum, it's a bit more involved, because we usually
    # want the import at applevel
    modname, attrname = spec.split(".")
    impbase = pkgroot + "." + modname
    try:
        app = applevelcache[impbase]
    except KeyError:
        import imp

        pkg = __import__(pkgroot, None, None, ["__doc__"])
        file, fn, (suffix, mode, typ) = imp.find_module(modname, pkg.__path__)
        assert typ == imp.PY_SOURCE
        source = file.read()
        file.close()
        if fn.endswith(".pyc") or fn.endswith(".pyo"):
            fn = fn[:-1]
        app = gateway.applevel(source, filename=fn, modname=appname)
        applevelcache[impbase] = app

    def afileloader(space):
        return app.wget(space, attrname)

    return afileloader
Example #2
0
    def get_entry_point(self, config):
        space = make_objspace(config)

        # manually imports app_main.py
        filename = os.path.join(pypydir, 'interpreter', 'app_main.py')
        app = gateway.applevel(open(filename).read(), 'app_main.py', 'app_main')
        app.hidden_applevel = False
        w_dict = app.getwdict(space)
        entry_point, _ = create_entry_point(space, w_dict)

        return entry_point, None, PyPyAnnotatorPolicy()
Example #3
0
    def get_entry_point(self, config):
        self.space = make_objspace(config)

        # manually imports app_main.py
        filename = os.path.join(pypydir, 'interpreter', 'app_main.py')
        app = gateway.applevel(open(filename).read(), 'app_main.py', 'app_main')
        app.hidden_applevel = False
        w_dict = app.getwdict(self.space)
        entry_point, _ = create_entry_point(self.space, w_dict)

        return entry_point, None, PyPyAnnotatorPolicy()
    def get_entry_point(self, config):
        from pypy.tool.lib_pypy import import_from_lib_pypy
        rebuild = import_from_lib_pypy('ctypes_config_cache/rebuild')
        rebuild.try_rebuild()

        space = make_objspace(config)

        # manually imports app_main.py
        filename = os.path.join(pypydir, 'interpreter', 'app_main.py')
        app = gateway.applevel(open(filename).read(), 'app_main.py', 'app_main')
        app.hidden_applevel = False
        w_dict = app.getwdict(space)
        entry_point, _ = create_entry_point(space, w_dict)

        return entry_point, None, PyPyAnnotatorPolicy()
Example #5
0
    def get_entry_point(self, config):
        from pypy.tool.lib_pypy import import_from_lib_pypy
        rebuild = import_from_lib_pypy('ctypes_config_cache/rebuild')
        rebuild.try_rebuild()

        space = make_objspace(config)

        # manually imports app_main.py
        filename = os.path.join(pypydir, 'interpreter', 'app_main.py')
        app = gateway.applevel(open(filename).read(), 'app_main.py', 'app_main')
        app.hidden_applevel = False
        w_dict = app.getwdict(space)
        entry_point, _ = create_entry_point(space, w_dict)

        return entry_point, None, PyPyAnnotatorPolicy()
Example #6
0
def getappfileloader(pkgroot, appname, spec):
    # hum, it's a bit more involved, because we usually
    # want the import at applevel
    modname, attrname = spec.split('.')
    impbase = pkgroot + '.' + modname
    try:
        app = applevelcache[impbase]
    except KeyError:
        import imp
        pkg = __import__(pkgroot, None, None, ['__doc__'])
        file, fn, (suffix, mode, typ) = imp.find_module(modname, pkg.__path__)
        assert typ == imp.PY_SOURCE
        source = file.read()
        file.close()
        if fn.endswith('.pyc') or fn.endswith('.pyo'):
            fn = fn[:-1]
        app = gateway.applevel(source, filename=fn, modname=appname)
        applevelcache[impbase] = app

    def afileloader(space):
        return app.wget(space, attrname)
    return afileloader
Example #7
0
import time as t
gmtime = t.gmtime()
date = t.strftime("%b %d %Y", gmtime)
time = t.strftime("%H:%M:%S", gmtime)
del t

# ____________________________________________________________

app = gateway.applevel('''
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield
class version_info:
    __metaclass__ = structseqtype

    major        = structseqfield(0, "Major release number")
    minor        = structseqfield(1, "Minor release number")
    micro        = structseqfield(2, "Patch release number")
    releaselevel = structseqfield(3,
                       "'alpha', 'beta', 'candidate', or 'release'")
    serial       = structseqfield(4, "Serial release number")
''')

def get_api_version(space):
    return space.wrap(CPYTHON_API_VERSION)

def get_version_info(space):
    w_version_info = app.wget(space, "version_info")
    return space.call_function(w_version_info, space.wrap(CPYTHON_VERSION))

def get_version(space):
Example #8
0
from pypy.interpreter import gateway

app = gateway.applevel(r'''
    def PyUnicode_DecodeUnicodeEscape(data):
        import _codecs
        return _codecs.unicode_escape_decode(data)[0]

    def PyUnicode_DecodeRawUnicodeEscape(data):
        import _codecs
        return _codecs.raw_unicode_escape_decode(data)[0]

    def PyUnicode_DecodeUTF8(data):
        import _codecs
        return _codecs.utf_8_decode(data)[0]

    def PyUnicode_AsEncodedString(data, encoding):
        import _codecs
        return _codecs.encode(data, encoding)

    def PyUnicode_EncodeUTF8(data):
        import _codecs
        return _codecs.utf_8_encode(data)[0]

''')

PyUnicode_DecodeUnicodeEscape = app.interphook('PyUnicode_DecodeUnicodeEscape')
PyUnicode_DecodeRawUnicodeEscape = app.interphook('PyUnicode_DecodeRawUnicodeEscape')
PyUnicode_DecodeUTF8 = app.interphook('PyUnicode_DecodeUTF8')
PyUnicode_AsEncodedString = app.interphook('PyUnicode_AsEncodedString')
PyUnicode_EncodeUTF8 = app.interphook('PyUnicode_EncodeUTF8') 
Example #9
0
app = gateway.applevel('''
"NOT_RPYTHON"
import builtins

class fake_code(object):
    co_name = "?"
    co_filename = "?"
    co_firstlineno = 0

class fake_frame(object):
    f_back = None
    f_builtins = builtins.__dict__
    f_code = fake_code()
    f_exc_traceback = None
    f_exc_type = None
    f_exc_value = None
    f_globals = {}
    f_lasti = -1
    f_lineno = 0
    f_locals = {}
    f_restricted = False
    f_trace = None

    def __init__(self, f):
        if f is not None:
            for name in ["f_builtins", "f_code", "f_globals", "f_lasti",
                         "f_lineno"]:
                setattr(self, name, getattr(f, name))
''')
Example #10
0
        StrOption(
            "warn",
            "warning control (arg is action:message:category:module:lineno)",
            default=None,
            cmdline="-W"),
    ])

pypy_init = gateway.applevel('''
def pypy_init(import_site):
    if import_site:
        import os, sys
        _MACOSX = sys.platform == 'darwin'
        if _MACOSX:
            # __PYVENV_LAUNCHER__, used by CPython on macOS, should be ignored
            # since it (possibly) results in a wrong sys.prefix and
            # sys.exec_prefix (and consequently sys.path).
            old_pyvenv_launcher = os.environ.pop('__PYVENV_LAUNCHER__', None)
        try:
            import site
        except:
            import sys
            print("'import site' failed", file=sys.stderr)
        if _MACOSX and old_pyvenv_launcher:
            os.environ['__PYVENV_LAUNCHER__'] = old_pyvenv_launcher
''').interphook('pypy_init')


def set_compiler(option, opt, value, parser):
    from rpython.translator.platform import set_platform
    set_platform('host', value)

Example #11
0
        Decrease the usecount of the socketobject. If the
        usecount reaches 0 close the socket.
        Intended only to be used by socket._socketobject
        """
        self.usecount -= 1
        if self.usecount > 0:
            return
        self.close_w(space)
    _drop_w.unwrap_spec = ['self', ObjSpace]

app_makefile = gateway.applevel(r'''
def makefile(self, mode="r", buffersize=-1):
    """makefile([mode[, buffersize]]) -> file object

    Return a regular file object corresponding to the socket.
    The mode and buffersize arguments are as for the built-in open() function.
    """
    import os
    newfd = os.dup(self.fileno())
    return os.fdopen(newfd, mode, buffersize)
''', filename =__file__).interphook('makefile')

def newsocket(space, w_subtype, family=AF_INET,
              type=SOCK_STREAM, proto=0):
    # XXX If we want to support subclassing the socket type we will need
    # something along these lines. But allocate_instance is only defined
    # on the standard object space, so this is not really correct.
    #sock = space.allocate_instance(W_RSocket, w_subtype)
    #Socket.__init__(sock, space, fd, family, type, proto)
    try:
        sock = W_RSocket(family, type, proto)
Example #12
0
     LL_TYPEMAP, NARROW_INTEGER_TYPES)
from rpython.rlib.clibffi import USERDATA_P, CallbackFuncPtr, FUNCFLAG_CDECL
from rpython.rlib.clibffi import ffi_type_void, LibFFIError
from rpython.rlib import rweakref
from pypy.module._rawffi.tracker import tracker
from pypy.interpreter.error import OperationError
from pypy.interpreter import gateway
from rpython.rlib.unroll import unrolling_iterable

BIGENDIAN = sys.byteorder == 'big'

unroll_narrow_integer_types = unrolling_iterable(NARROW_INTEGER_TYPES)

app = gateway.applevel('''
    def tbprint(tb, err):
        import traceback, sys
        traceback.print_tb(tb)
        print >>sys.stderr, err
''', filename=__file__)

tbprint = app.interphook("tbprint")

def callback(ll_args, ll_res, ll_userdata):
    userdata = rffi.cast(USERDATA_P, ll_userdata)
    callback_ptr = global_counter.get(userdata.addarg)
    w_callable = callback_ptr.w_callable
    argtypes = callback_ptr.argtypes
    must_leave = False
    space = callback_ptr.space
    try:
        must_leave = space.threadlocals.try_enter_thread(space)
        args_w = [None] * len(argtypes)
Example #13
0
app = gateway.applevel('''

    # in the following functions we use dict.__setitem__ instead of
    # d[k]=...  because when a subclass of dict override __setitem__,
    # CPython does not call it when doing builtin operations.  The
    # same for other operations.

    def update1(d, o):
        if hasattr(o, 'keys'):
            for k in o.keys():
                dict.__setitem__(d, k, o[k])
        else:
            for k,v in o:
                dict.__setitem__(d, k, v)

    def update(d, *args, **kwargs):
        len_args = len(args)
        if len_args == 1:
            update1(d, args[0])
        elif len_args > 1:
            raise TypeError("update takes at most 1 (non-keyword) argument")
        if kwargs:
            update1(d, kwargs)

    def popitem(d):
        for k in dict.iterkeys(d):
            break
        else:
            raise KeyError("popitem(): dictionary is empty")
        v = dict.__getitem__(d, k)
        dict.__delitem__(d, k)
        return k, v

    def get(d, k, v=None):
        if k in d:
            return dict.__getitem__(d, k)
        else:
            return v

    def setdefault(d, k, v=None):
        if k in d:
            return dict.__getitem__(d, k)
        else:
            dict.__setitem__(d, k, v)
            return v

    def pop(d, k, defaults):     # XXX defaults is actually *defaults
        if len(defaults) > 1:
            raise TypeError, "pop expected at most 2 arguments, got %d" % (
                1 + len(defaults))
        try:
            v = dict.__getitem__(d, k)
            dict.__delitem__(d, k)
        except KeyError, e:
            if defaults:
                return defaults[0]
            else:
                raise e
        return v

    def iteritems(d):
        return iter(dict.items(d))

    def iterkeys(d):
        return iter(dict.keys(d))

    def itervalues(d):
        return iter(dict.values(d))
''', filename=__file__)
Example #14
0
app = gateway.applevel(r"""    
# Implement pep302

IMP_HOOK = 9

def find_module(fullname,  path):
    import sys
    meta_path = sys.meta_path
    for hook in meta_path:
        loader = hook.find_module(fullname,  path)
        if loader:
            return loader
    if path != None and type(path) == str:
        pass
        # XXX Check for frozen modules ?
    if path == None:
        # XXX Check frozen
        path = sys.path
    path_hooks = sys.path_hooks
    importer_cache = sys.path_importer_cache 
    importer = None
    for p in path:
        if importer_cache.get(p,None):
            importer = importer_cache.get(p)
        else:
            importer_cache[p] = None
            importer = None
            for hook in path_hooks:
                try:
                    importer = hook(p)
                except ImportError:
                    pass
                else:
                    break
            if importer:
                importer_cache[p] = importer
        if importer:
            loader = importer.find_module(fullname)
            if loader:
                return loader
     #no hooks match - do normal import
    """)
Example #15
0
File: misc.py Project: Mu-L/pypy
from pypy.interpreter import gateway
from rpython.rlib.objectmodel import dict_to_switch
from rpython.rlib.unroll import unrolling_iterable

app = gateway.applevel("""
def syntax_warning(msg, fn, lineno, offset):
    import warnings
    try:
        warnings.warn_explicit(msg, SyntaxWarning, fn, lineno)
    except SyntaxWarning:
        raise SyntaxError(msg, (fn, lineno, offset, msg))
""",
                       filename=__file__)
_emit_syntax_warning = app.interphook("syntax_warning")
del app


def syntax_warning(space, msg, fn, lineno, offset):
    """Raise an applevel SyntaxWarning.

    If the user has set this warning to raise an error, a SyntaxError will be
    raised."""
    w_msg = space.newtext(msg)
    w_filename = space.newtext(fn)
    w_lineno = space.newint(lineno)
    w_offset = space.newint(offset)
    _emit_syntax_warning(space, w_msg, w_filename, w_lineno, w_offset)


def parse_future(tree, feature_flags):
    from pypy.interpreter.astcompiler import ast
Example #16
0
            space.setitem(w_dict, w_key, w_fill)
    return w_dict


app = gateway.applevel('''
    def dictrepr(currently_in_repr, d):
        if len(d) == 0:
            return "{}"
        dict_id = id(d)
        if dict_id in currently_in_repr:
            return '{...}'
        currently_in_repr[dict_id] = 1
        try:
            items = []
            # XXX for now, we cannot use iteritems() at app-level because
            #     we want a reasonable result instead of a RuntimeError
            #     even if the dict is mutated by the repr() in the loop.
            for k, v in dict.items(d):
                items.append(repr(k) + ": " + repr(v))
            return "{" +  ', '.join(items) + "}"
        finally:
            try:
                del currently_in_repr[dict_id]
            except:
                pass
''',
                       filename=__file__)

dictrepr = app.interphook("dictrepr")

Example #17
0
from rpython.rtyper.lltypesystem import lltype, rffi

app = gateway.applevel("""
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield
class float_info(metaclass=structseqtype):

    max = structseqfield(0)
    max_exp = structseqfield(1)
    max_10_exp = structseqfield(2)
    min = structseqfield(3)
    min_exp = structseqfield(4)
    min_10_exp = structseqfield(5)
    dig = structseqfield(6)
    mant_dig = structseqfield(7)
    epsilon = structseqfield(8)
    radix = structseqfield(9)
    rounds = structseqfield(10)

class int_info(metaclass=structseqtype):
    bits_per_digit = structseqfield(0)
    sizeof_digit = structseqfield(1)

class hash_info(metaclass=structseqtype):
    width = structseqfield(0)
    modulus = structseqfield(1)
    inf = structseqfield(2)
    nan = structseqfield(3)
    imag = structseqfield(4)
""")

Example #18
0
            return exprcompile(space, w_compileAST)
        else:
            return modcompile(space, w_compileAST)
    descr_compile.unwrap_spec = ['self', ObjSpace, str]

ASTType = STType

app = applevel("""
    def mycompile(tup, filename):
        import compiler
        transformer = compiler.transformer.Transformer()
        compileAST = transformer.compile_node(tup)
        compiler.misc.set_filename(filename, compileAST)
        return compileAST

    def exprcompile(compileAST):
        import compiler
        gen = compiler.pycodegen.ExpressionCodeGenerator(compileAST)
        return gen.getCode()

    def modcompile(compileAST):
        import compiler
        gen = compiler.pycodegen.ModuleCodeGenerator(compileAST)
        return gen.getCode()
""", filename=__file__)

mycompile = app.interphook("mycompile")
exprcompile = app.interphook("exprcompile")
modcompile = app.interphook("modcompile")

STType.typedef = TypeDef("parser.st",
    compile = interp2app(STType.descr_compile),
Example #19
0
init_defaults = [None]
def init__Set(space, w_set, __args__):
    w_iterable, = __args__.parse_obj(
            None, 'set',
            init_signature,
            init_defaults)
    _initialize_set(space, w_set, w_iterable)

app = gateway.applevel("""
    def setrepr(currently_in_repr, s):
        'The app-level part of repr().'
        set_id = id(s)
        if set_id in currently_in_repr:
            return '%s(...)' % (s.__class__.__name__,)
        currently_in_repr[set_id] = 1
        try:
            return '%s(%s)' % (s.__class__.__name__, [x for x in s])
        finally:
            try:
                del currently_in_repr[set_id]
            except:
                pass
""", filename=__file__)

setrepr = app.interphook("setrepr")

def repr__Set(space, w_set):
    ec = space.getexecutioncontext()
    w_currently_in_repr = ec._py_repr
    if w_currently_in_repr is None:
        w_currently_in_repr = ec._py_repr = space.newdict()
Example #20
0

def init__Set(space, w_set, __args__):
    w_iterable, = __args__.parse_obj(None, 'set', init_signature,
                                     init_defaults)
    _initialize_set(space, w_set, w_iterable)


app = gateway.applevel("""
    def setrepr(currently_in_repr, s):
        'The app-level part of repr().'
        set_id = id(s)
        if set_id in currently_in_repr:
            return '%s(...)' % (s.__class__.__name__,)
        currently_in_repr[set_id] = 1
        try:
            return '%s(%s)' % (s.__class__.__name__, [x for x in s])
        finally:
            try:
                del currently_in_repr[set_id]
            except:
                pass
""",
                       filename=__file__)

setrepr = app.interphook("setrepr")


def repr__Set(space, w_set):
    ec = space.getexecutioncontext()
    w_currently_in_repr = ec._py_repr
    if w_currently_in_repr is None:
Example #21
0
    app_os_path = applevel("""
        def dirname(p):
            i = p.rfind('/') + 1
            head = p[:i]
            if head and head != '/'*len(head):
                head = head.rstrip('/')
            return head

        def join(path, b):
            if b.startswith('/'):
                path = b
            elif path == '' or path.endswith('/'):
                path +=  b
            else:
                path += '/' + b
            return path

        def normpath(path):
            if path == '':
                return '.'
            initial_slashes = path.startswith('/')
            # POSIX allows one or two initial slashes, but treats three or more
            # as single slash.
            if (initial_slashes and
                path.startswith('//') and not path.startswith('///')):
                initial_slashes = 2
            comps = path.split('/')
            new_comps = []
            for comp in comps:
                if comp in ('', '.'):
                    continue
                if (comp != '..' or (not initial_slashes and not new_comps) or
                     (new_comps and new_comps[-1] == '..')):
                    new_comps.append(comp)
                elif new_comps:
                    new_comps.pop()
            comps = new_comps
            path = '/'.join(comps)
            if initial_slashes:
                path = '/'*initial_slashes + path
            return path or '.'

        def abspath(path):
            if not path.startswith('/'):
                import posix
                cwd = posix.getcwd()
                path = join(cwd, path)
            return normpath(path)

        def isfile(path):
            import posix
            try:
                st = posix.stat(path)
            except posix.error:
                return False
            return (st.st_mode & 0170000) == 0100000      # S_ISREG

        def islink(path):
            import posix
            try:
                st = posix.lstat(path)
            except posix.error:
                return False
            return (st.st_mode & 0170000) == 0120000      # S_ISLNK

    """,
                           filename=__file__)
Example #22
0
                          "type object '%s' has no attribute '%s'",
                          w_type.name, name)

def eq__Type_Type(space, w_self, w_other):
    return space.is_(w_self, w_other)

# ____________________________________________________________


abstract_mro = gateway.applevel("""
    def abstract_mro(klass):
        # abstract/classic mro
        mro = []
        stack = [klass]
        while stack:
            klass = stack.pop()
            if klass not in mro:
                mro.append(klass)
                if not isinstance(klass.__bases__, tuple):
                    raise TypeError, '__bases__ must be a tuple'
                stack += klass.__bases__[::-1]
        return mro
""", filename=__file__).interphook("abstract_mro")

def get_mro(space, klass):
    if isinstance(klass, W_TypeObject):
        return list(klass.mro_w)
    else:
        return space.unpackiterable(abstract_mro(space, klass))


def compute_C3_mro(space, cls):
Example #23
0
the few needed functions are implemented in a tiny os module
that contains a tiny path module.

os.getenv got a direct implementation to overcome the caching
problem.

Please adjust the applevel code below, if you need to support
more from os and os.path.
"""

from pypy.interpreter.gateway import applevel, ObjSpace, W_Root, interp2app
import os

app_os_path = applevel(
    r"""
    from os.path import dirname, join, abspath, isfile, islink
""",
    filename=__file__,
)

app_os = applevel(
    r"""
    from os import sep, pathsep, getenv, name, fdopen
    try:
        from os import readlink
    except ImportError:
        pass
""",
    filename=__file__,
)

Example #24
0
from pypy.interpreter.typedef import TypeDef, GetSetProperty
from rpython.rtyper.lltypesystem import lltype, rffi
from pypy.module._rawffi.interp_rawffi import write_ptr
from pypy.module._rawffi.structure import W_Structure
from pypy.module._rawffi.interp_rawffi import (W_DataInstance, letter2tp,
     unwrap_value, unpack_argshapes, got_libffi_error)
from rpython.rlib.clibffi import USERDATA_P, CallbackFuncPtr, FUNCFLAG_CDECL
from rpython.rlib.clibffi import ffi_type_void, LibFFIError
from rpython.rlib import rweakref
from pypy.module._rawffi.tracker import tracker
from pypy.interpreter.error import OperationError
from pypy.interpreter import gateway

app = gateway.applevel('''
    def tbprint(tb, err):
        import traceback, sys
        traceback.print_tb(tb)
        print >>sys.stderr, err
''', filename=__file__)

tbprint = app.interphook("tbprint")

def callback(ll_args, ll_res, ll_userdata):
    userdata = rffi.cast(USERDATA_P, ll_userdata)
    callback_ptr = global_counter.get(userdata.addarg)
    w_callable = callback_ptr.w_callable
    argtypes = callback_ptr.argtypes
    space = callback_ptr.space
    try:
        args_w = [None] * len(argtypes)
        for i in range(len(argtypes)):
            argtype = argtypes[i]
Example #25
0
    _initialize_set(space, w_set, w_iterable)


def init__Frozenset(space, w_set, __args__):
    w_iterable, = __args__.parse('set', (['some_iterable'], None, None),
                                 [space.newtuple([])])
    if w_set.hash == -1:
        _initialize_set(space, w_set, w_iterable)
        hash__Frozenset(space, w_set)


app = gateway.applevel("""
    def repr__Set(s):
        return '%s(%s)' % (s.__class__.__name__, [x for x in s])

    def reduce__Set(s):
        dict = getattr(s,'__dict__', None)
        return (s.__class__, (tuple(s),), dict)

""",
                       filename=__file__)

repr__Set = app.interphook('repr__Set')
repr__Frozenset = app.interphook('repr__Set')

set_reduce__Set = app.interphook('reduce__Set')
frozenset_reduce__Frozenset = app.interphook('reduce__Set')

from pypy.objspace.std import frozensettype
from pypy.objspace.std import settype

register_all(vars(), settype, frozensettype)
Example #26
0
File: vm.py Project: Debug-Orz/Sypy
saved, and restored afterwards.  This is intended to be called from
a debugger from a checkpoint, to recursively debug some other code."""
    return space.getexecutioncontext().call_tracing(w_func, w_args)


app = gateway.applevel('''
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield

class windows_version_info:
    __metaclass__ = structseqtype

    name = "sys.getwindowsversion"

    major = structseqfield(0, "Major version number")
    minor = structseqfield(1, "Minor version number")
    build = structseqfield(2, "Build number")
    platform = structseqfield(3, "Operating system platform")
    service_pack = structseqfield(4, "Latest Service Pack installed on the system")

    # Because the indices aren't consecutive, they aren't included when
    # unpacking and other such operations.
    service_pack_major = structseqfield(10, "Service Pack major version number")
    service_pack_minor = structseqfield(11, "Service Pack minor version number")
    suite_mask = structseqfield(12, "Bit mask identifying available product suites")
    product_type = structseqfield(13, "System product type")
''')


def getwindowsversion(space):
    from pypy.rlib import rwin32
    info = rwin32.GetVersionEx()
Example #27
0
from pypy.interpreter import gateway
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.unroll import unrolling_iterable


app = gateway.applevel("""
def syntax_warning(msg, fn, lineno, offset):
    import warnings
    try:
        warnings.warn_explicit(msg, SyntaxWarning, fn, lineno)
    except SyntaxWarning:
        raise SyntaxError(msg, fn, lineno, offset)
""", filename=__file__)
_emit_syntax_warning = app.interphook("syntax_warning")
del app

def syntax_warning(space, msg, fn, lineno, offset):
    """Raise an applevel SyntaxWarning.

    If the user has set this warning to raise an error, a SyntaxError will be
    raised."""
    w_msg = space.wrap(msg)
    w_filename = space.wrap(fn)
    w_lineno = space.wrap(lineno)
    w_offset = space.wrap(offset)
    _emit_syntax_warning(space, w_msg, w_filename, w_lineno, w_offset)


def parse_future(tree, feature_flags):
    from pypy.interpreter.astcompiler import ast
    future_lineno = 0
Example #28
0
def dict_get__Dict_ANY_ANY(space, w_dict, w_lookup, w_default):
    return w_dict.content.get(w_lookup, w_default)

app = gateway.applevel('''
    def dictrepr(currently_in_repr, d):
        # Now we only handle one implementation of dicts, this one.
        # The fix is to move this to dicttype.py, and do a
        # multimethod lookup mapping str to StdObjSpace.str
        # This cannot happen until multimethods are fixed. See dicttype.py
            dict_id = id(d)
            if dict_id in currently_in_repr:
                return '{...}'
            currently_in_repr[dict_id] = 1
            try:
                items = []
                # XXX for now, we cannot use iteritems() at app-level because
                #     we want a reasonable result instead of a RuntimeError
                #     even if the dict is mutated by the repr() in the loop.
                for k, v in dict.items(d):
                    items.append(repr(k) + ": " + repr(v))
                return "{" +  ', '.join(items) + "}"
            finally:
                try:
                    del currently_in_repr[dict_id]
                except:
                    pass
''', filename=__file__)

dictrepr = app.interphook("dictrepr")

def repr__Dict(space, w_dict):
Example #29
0
from pypy.interpreter import gateway
from pypy.rlib import rfloat, rbigint
from pypy.rpython.lltypesystem import rffi

app = gateway.applevel("""
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield
class float_info:
    __metaclass__ = structseqtype

    max = structseqfield(0)
    max_exp = structseqfield(1)
    max_10_exp = structseqfield(2)
    min = structseqfield(3)
    min_exp = structseqfield(4)
    min_10_exp = structseqfield(5)
    dig = structseqfield(6)
    mant_dig = structseqfield(7)
    epsilon = structseqfield(8)
    radix = structseqfield(9)
    rounds = structseqfield(10)

class long_info:
    __metaclass__ = structseqtype
    bits_per_digit = structseqfield(0)
    sizeof_digit = structseqfield(1)
""")


def get_float_info(space):
    info_w = [
Example #30
0
app = gateway.applevel(r'''
import sys

def unicode_expandtabs__Unicode_ANY(self, tabsize):
    parts = self.split(u'\t')
    result = [ parts[0] ]
    prevsize = 0
    for ch in parts[0]:
        prevsize += 1
        if ch in (u"\n", u"\r"):
            prevsize = 0
    for i in range(1, len(parts)):
        pad = tabsize - prevsize % tabsize
        result.append(u' ' * pad)
        nextpart = parts[i]
        result.append(nextpart)
        prevsize = 0
        for ch in nextpart:
            prevsize += 1
            if ch in (u"\n", u"\r"):
                prevsize = 0
    return u''.join(result)

def unicode_translate__Unicode_ANY(self, table):
    result = []
    for unichar in self:
        try:
            newval = table[ord(unichar)]
        except KeyError:
            result.append(unichar)
        else:
            if newval is None:
                continue
            elif isinstance(newval, int):
                if newval < 0 or newval > sys.maxunicode:
                    raise TypeError("character mapping must be in range(0x%x)"%(sys.maxunicode + 1,))
                result.append(unichr(newval))
            elif isinstance(newval, unicode):
                result.append(newval)
            else:
                raise TypeError("character mapping must return integer, None or unicode")
    return ''.join(result)

def unicode_encode__Unicode_ANY_ANY(unistr, encoding=None, errors=None):
    import codecs, sys
    if encoding is None:
        encoding = sys.getdefaultencoding()

    encoder = codecs.getencoder(encoding)
    if errors is None:
        retval, lenght = encoder(unistr)
    else:
        retval, length = encoder(unistr, errors)
    if not isinstance(retval,str):
        raise TypeError("encoder did not return a string object (type=%s)" %
                        type(retval).__name__)
    return retval

# XXX: These should probably be written on interplevel 

def unicode_partition__Unicode_Unicode(unistr, unisub):
    pos = unistr.find(unisub)
    if pos == -1:
        return (unistr, u'', u'')
    else:
        return (unistr[:pos], unisub, unistr[pos+len(unisub):])

def unicode_rpartition__Unicode_Unicode(unistr, unisub):
    pos = unistr.rfind(unisub)
    if pos == -1:
        return (u'', u'', unistr)
    else:
        return (unistr[:pos], unisub, unistr[pos+len(unisub):])

def unicode_startswith__Unicode_Tuple_ANY_ANY(unistr, prefixes, start, end):
    for prefix in prefixes:
        if unistr.startswith(prefix):
            return True
    return False

def unicode_endswith__Unicode_Tuple_ANY_ANY(unistr, suffixes, start, end):
    for suffix in suffixes:
        if unistr.endswith(suffix):
            return True
    return False

''')
Example #31
0
        setattr(W_DictMultiObject, method, make_method(method))

_add_indirections()


app = applevel('''
    def dictrepr(currently_in_repr, d):
        if len(d) == 0:
            return "{}"
        dict_id = id(d)
        if dict_id in currently_in_repr:
            return '{...}'
        currently_in_repr[dict_id] = 1
        try:
            items = []
            # XXX for now, we cannot use iteritems() at app-level because
            #     we want a reasonable result instead of a RuntimeError
            #     even if the dict is mutated by the repr() in the loop.
            for k, v in dict.items(d):
                items.append(repr(k) + ": " + repr(v))
            return "{" +  ', '.join(items) + "}"
        finally:
            try:
                del currently_in_repr[dict_id]
            except:
                pass
''', filename=__file__)

dictrepr = app.interphook("dictrepr")


W_DictMultiObject.typedef = StdTypeDef("dict",
Example #32
0
from pypy.interpreter.pyparser.pythonlexer import Source, match_encoding_declaration
from pypy.interpreter.astcompiler.consts import CO_FUTURE_WITH_STATEMENT
import pypy.interpreter.pyparser.pytoken as pytoken
import pypy.interpreter.pyparser.ebnfparse as ebnfparse
from pypy.interpreter.pyparser.ebnflexer import GrammarSource
from pypy.interpreter.pyparser.ebnfgrammar import GRAMMAR_GRAMMAR
import pypy.interpreter.pyparser.grammar as grammar
from pypy.interpreter.pyparser.pythonutil import build_parser_for_version
from pypy.interpreter.pyparser import symbol

from codeop import PyCF_DONT_IMPLY_DEDENT


##  files encoding management ############################################
_recode_to_utf8 = gateway.applevel(r'''
    def _recode_to_utf8(text, encoding):
        return unicode(text, encoding).encode("utf-8")
''').interphook('_recode_to_utf8')

def recode_to_utf8(space, text, encoding):
    return space.str_w(_recode_to_utf8(space, space.wrap(text),
                                          space.wrap(encoding)))
def _normalize_encoding(encoding):
    """returns normalized name for <encoding>

    see dist/src/Parser/tokenizer.c 'get_normal_name()'
    for implementation details / reference

    NOTE: for now, parser.suite() raises a MemoryError when
          a bad encoding is used. (SF bug #979739)
    """
    if encoding is None:
Example #33
0
saved, and restored afterwards.  This is intended to be called from
a debugger from a checkpoint, to recursively debug some other code."""
    return space.getexecutioncontext().call_tracing(w_func, w_args)


app = gateway.applevel('''
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield

class windows_version_info(metaclass=structseqtype):

    name = "sys.getwindowsversion"

    major = structseqfield(0, "Major version number")
    minor = structseqfield(1, "Minor version number")
    build = structseqfield(2, "Build number")
    platform = structseqfield(3, "Operating system platform")
    service_pack = structseqfield(4, "Latest Service Pack installed on the system")

    # Because the indices aren't consecutive, they aren't included when
    # unpacking and other such operations.
    service_pack_major = structseqfield(10, "Service Pack major version number")
    service_pack_minor = structseqfield(11, "Service Pack minor version number")
    suite_mask = structseqfield(12, "Bit mask identifying available product suites")
    product_type = structseqfield(13, "System product type")
    _platform_version = structseqfield(14, "Diagnostic version number")
''')


def getwindowsversion(space):
    from rpython.rlib import rwin32
    info = rwin32.GetVersionEx()
Example #34
0
        else:
            # Make a shallow copy to more easily handle the reversal case
            sequence2 = list(sequence2)
    for i in range(len2):
        items[start] = sequence2[i]
        start += step


app = gateway.applevel("""
    def listrepr(currently_in_repr, l):
        'The app-level part of repr().'
        list_id = id(l)
        if list_id in currently_in_repr:
            return '[...]'
        currently_in_repr[list_id] = 1
        try:
            return "[" + ", ".join([repr(x) for x in l]) + ']'
        finally:
            try:
                del currently_in_repr[list_id]
            except:
                pass
""",
                       filename=__file__)

listrepr = app.interphook("listrepr")


def repr__List(space, w_list):
    if len(w_list.wrappeditems) == 0:
        return space.wrap('[]')
    ec = space.getexecutioncontext()
Example #35
0
        else:
            # Make a shallow copy to more easily handle the reversal case
            sequence2 = list(sequence2)
    for i in range(len2):
        items[start] = sequence2[i]
        start += step
    return space.w_None

app = gateway.applevel("""
    def listrepr(currently_in_repr, l):
        'The app-level part of repr().'
        list_id = id(l)
        if list_id in currently_in_repr:
            return '[...]'
        currently_in_repr[list_id] = 1
        try:
            return "[" + ", ".join([repr(x) for x in l]) + ']'
        finally:
            try:
                del currently_in_repr[list_id]
            except:
                pass
""", filename=__file__) 

listrepr = app.interphook("listrepr")

def repr__List(space, w_list):
    if len(w_list.wrappeditems) == 0:
        return space.wrap('[]')
    w_currently_in_repr = space.getexecutioncontext()._py_repr
    return listrepr(space, w_currently_in_repr, w_list)
Example #36
0
    if (space.config.objspace.std.withmultilist or
        space.config.objspace.std.withrangelist):
        return range_withspecialized_implementation(space, start,
                                                    step, howmany)
    res_w = [None] * howmany
    v = start
    for idx in range(howmany):
        res_w[idx] = space.wrap(v)
        v += step
    return space.newlist(res_w)
range_int = range
range_int.unwrap_spec = [ObjSpace, W_Root, W_Root, W_Root]
del range # don't hide the builtin one

range_fallback = applevel(getsource(app_range), getfile(app_range)
                          ).interphook('range')

def range_withspecialized_implementation(space, start, step, howmany):
    if space.config.objspace.std.withrangelist:
        from pypy.objspace.std.rangeobject import W_RangeListObject
        return W_RangeListObject(start, step, howmany)
    if space.config.objspace.std.withmultilist:
        from pypy.objspace.std.listmultiobject import W_ListMultiObject
        from pypy.objspace.std.listmultiobject import RangeImplementation
        impl = RangeImplementation(space, start, step, howmany)
        return W_ListMultiObject(space, impl)




def all(space, w_S):
Example #37
0
        Decrease the usecount of the socketobject. If the
        usecount reaches 0 close the socket.
        Intended only to be used by socket._socketobject
        """
        self.usecount -= 1
        if self.usecount > 0:
            return
        self.close_w(space)


app_makefile = gateway.applevel(r'''
def makefile(self, mode="r", buffersize=-1):
    """makefile([mode[, buffersize]]) -> file object

    Return a regular file object corresponding to the socket.
    The mode and buffersize arguments are as for the built-in open() function.
    """
    import os
    newfd = os.dup(self.fileno())
    return os.fdopen(newfd, mode, buffersize)
''',
                                filename=__file__).interphook('makefile')


@unwrap_spec(family=int, type=int, proto=int)
def newsocket(space, w_subtype, family=AF_INET, type=SOCK_STREAM, proto=0):
    self = space.allocate_instance(W_Socket, w_subtype)
    try:
        sock = RSocket(family, type, proto)
    except SocketError as e:
        raise converted_error(space, e)
    W_Socket.__init__(self, space, sock)
Example #38
0
app = gateway.applevel('''
"NOT_RPYTHON"
import __builtin__

class fake_code(object):
    co_name = "?"
    co_filename = "?"
    co_firstlineno = 0

class fake_frame(object):
    f_back = None
    f_builtins = __builtin__.__dict__
    f_code = fake_code()
    f_exc_traceback = None
    f_exc_type = None
    f_exc_value = None
    f_globals = {}
    f_lasti = -1
    f_lineno = 0
    f_locals = {}
    f_restricted = False
    f_trace = None

    def __init__(self, f):
        if f is not None:
            for name in ["f_builtins", "f_code", "f_globals", "f_lasti",
                         "f_lineno"]:
                setattr(self, name, getattr(f, name))
''')
Example #39
0
app = gateway.applevel(r'''
    """ applevel implementation of certain system properties, imports
    and other helpers"""
    import sys
    
    def sys_stdout():
        try: 
            return sys.stdout
        except AttributeError:
            raise RuntimeError("lost sys.stdout")

    def print_expr(obj):
        try:
            displayhook = sys.displayhook
        except AttributeError:
            raise RuntimeError("lost sys.displayhook")
        displayhook(obj)

    def print_item_to(x, stream):
        if file_softspace(stream, False):
           stream.write(" ")
        stream.write(str(x))

        # add a softspace unless we just printed a string which ends in a '\t'
        # or '\n' -- or more generally any whitespace character but ' '
        if isinstance(x, str) and x and x[-1].isspace() and x[-1]!=' ':
            return 
        # XXX add unicode handling
        file_softspace(stream, True)
    print_item_to._annspecialcase_ = "specialize:argtype(0)"

    def print_item(x):
        print_item_to(x, sys_stdout())
    print_item._annspecialcase_ = "flowspace:print_item"

    def print_newline_to(stream):
        stream.write("\n")
        file_softspace(stream, False)

    def print_newline():
        print_newline_to(sys_stdout())
    print_newline._annspecialcase_ = "flowspace:print_newline"

    def file_softspace(file, newflag):
        try:
            softspace = file.softspace
        except AttributeError:
            softspace = 0
        try:
            file.softspace = newflag
        except AttributeError:
            pass
        return softspace
''',
                       filename=__file__)
Example #40
0
        return space.get_and_call_function(round, w_number)
    else:
        return space.get_and_call_function(round, w_number, w_ndigits)

# ____________________________________________________________

iter_sentinel = gateway.applevel('''
    # NOT_RPYTHON  -- uses yield
    # App-level implementation of the iter(callable,sentinel) operation.

    def iter_generator(callable_, sentinel):
        while 1:
            try:
                result = callable_()
            except StopIteration:
                return
            if result == sentinel:
                return
            yield result

    def iter_sentinel(callable_, sentinel):
        if not callable(callable_):
            raise TypeError('iter(v, w): v must be callable')
        return iter_generator(callable_, sentinel)

''', filename=__file__).interphook("iter_sentinel")

def iter(space, w_collection_or_callable, w_sentinel=None):
    """iter(collection) -> iterator over the elements of the collection.

iter(callable, sentinel) -> iterator calling callable() until it returns
                            the sentinel.
Example #41
0
app = gateway.applevel("""
    from _operator import index

    def evaluate_slice_index(x):
        try:
            return index(x)
        except TypeError:
            raise TypeError("slice indices must be integers or "
                            "None or have an __index__ method")

    def _getlongindices(start, stop, step, length):
        if step is None:
            step = 1
        else:
            step = evaluate_slice_index(step)
            if step == 0:
                raise ValueError("slice step cannot be zero")

        # Find lower and upper bounds for start and stop.
        if step < 0:
            lower = -1
            upper = length - 1
        else:
            lower = 0
            upper = length

        # Compute start.
        if start is None:
            start = upper if step < 0 else lower
        else:
            start = evaluate_slice_index(start)
            if start < 0:
                start += length
                if start < lower:
                    start = lower
            else:
                if start > upper:
                    start = upper

        # Compute stop.
        if stop is None:
            stop = lower if step < 0 else upper
        else:
            stop = evaluate_slice_index(stop)
            if stop < 0:
                stop += length
                if stop < lower:
                    stop = lower
            else:
                if stop > upper:
                    stop = upper

        return (start, stop, step)

    def indices(start, stop, step, length):
        length = index(length)
        if length < 0:
            raise ValueError("length should not be negative")
        return _getlongindices(start, stop, step, length)

""", filename=__file__)
Example #42
0
        StrOption("runcommand",
                  "program passed in as CMD (terminates option list)",
                  default=None,
                  cmdline="-c"),
        StrOption(
            "warn",
            "warning control (arg is action:message:category:module:lineno)",
            default=None,
            cmdline="-W"),
    ])

pypy_init = gateway.applevel('''
def pypy_init(import_site):
    if import_site:
        try:
            import site
        except:
            import sys
            print >> sys.stderr, "import site\' failed"
''').interphook('pypy_init')


def set_compiler(option, opt, value, parser):
    from pypy.translator.platform import set_platform
    set_platform('host', value)


def main_(argv=None):
    starttime = time.time()
    config, parser = option.get_standard_options()
    interactiveconfig = Config(cmdline_optiondescr)
Example #43
0
import time as t
gmtime = t.gmtime()
date = t.strftime("%b %d %Y", gmtime)
time = t.strftime("%H:%M:%S", gmtime)
del t

# ____________________________________________________________

app = gateway.applevel('''
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield
class version_info:
    __metaclass__ = structseqtype

    major        = structseqfield(0, "Major release number")
    minor        = structseqfield(1, "Minor release number")
    micro        = structseqfield(2, "Patch release number")
    releaselevel = structseqfield(3,
                       "'alpha', 'beta', 'candidate', or 'release'")
    serial       = structseqfield(4, "Serial release number")
''')


def get_api_version(space):
    return space.newint(CPYTHON_API_VERSION)


def get_version_info(space):
    w_version_info = app.wget(space, "version_info")
    # run at translation time
Example #44
0
    if isinf(z):
        raise oefmt(space.w_OverflowError,
                    "rounded value too large to represent")
    return space.wrap(z)

# ____________________________________________________________

iter_sentinel = gateway.applevel('''
    # NOT_RPYTHON  -- uses yield
    # App-level implementation of the iter(callable,sentinel) operation.

    def iter_generator(callable_, sentinel):
        while 1:
            result = callable_()
            if result == sentinel:
                return
            yield result

    def iter_sentinel(callable_, sentinel):
        if not callable(callable_):
            raise TypeError, 'iter(v, w): v must be callable'
        return iter_generator(callable_, sentinel)

''', filename=__file__).interphook("iter_sentinel")

def iter(space, w_collection_or_callable, w_sentinel=None):
    """iter(collection) -> iterator over the elements of the collection.

iter(callable, sentinel) -> iterator calling callable() until it returns
                            the sentinal.
"""
Example #45
0
        else:
            return modcompile(space, w_compileAST)


ASTType = STType

app = applevel("""
    def mycompile(tup, filename):
        import compiler
        transformer = compiler.transformer.Transformer()
        compileAST = transformer.compile_node(tup)
        compiler.misc.set_filename(filename, compileAST)
        return compileAST

    def exprcompile(compileAST):
        import compiler
        gen = compiler.pycodegen.ExpressionCodeGenerator(compileAST)
        return gen.getCode()

    def modcompile(compileAST):
        import compiler
        gen = compiler.pycodegen.ModuleCodeGenerator(compileAST)
        return gen.getCode()
""",
               filename=__file__)

mycompile = app.interphook("mycompile")
exprcompile = app.interphook("exprcompile")
modcompile = app.interphook("modcompile")

STType.typedef = TypeDef(
Example #46
0

def marshal_w__Unicode(space, w_unicode, m):
    s = space.str_w(unicodehelper.PyUnicode_EncodeUTF8(space, w_unicode))
    m.atom_str(TYPE_UNICODE, s)


def unmarshal_Unicode(space, u, tc):
    return unicodehelper.PyUnicode_DecodeUTF8(space, space.wrap(u.get_str()))


register(TYPE_UNICODE, unmarshal_Unicode)

app = gateway.applevel(r'''
    def tuple_to_set(datalist, frozen=False):
        if frozen:
            return frozenset(datalist)
        return set(datalist)
''')

tuple_to_set = app.interphook('tuple_to_set')


# not directly supported:
def marshal_w_set(space, w_set, m):
    # cannot access this list directly, because it's
    # type is not exactly known through applevel.
    lis_w = space.viewiterable(w_set)
    m.put_tuple_w(TYPE_SET, lis_w)


handled_by_any.append(('set', marshal_w_set))
Example #47
0
               default=False, cmdline="-O"),
    BoolOption("no_site_import", "do not 'import site' on initialization",
               default=False, cmdline="-S"),
    StrOption("runmodule",
              "library module to be run as a script (terminates option list)",
              default=None, cmdline="-m"),
    StrOption("runcommand",
              "program passed in as CMD (terminates option list)",
              default=None, cmdline="-c"),
    ])

pypy_init = gateway.applevel('''
def pypy_init(import_site):
    if import_site:
        try:
            import site
        except:
            import sys
            print >> sys.stderr, "import site\' failed"
''').interphook('pypy_init')

def getenv_w(space, name):
    w_os = space.getbuiltinmodule('os')
    w_environ = space.getattr(w_os, space.wrap('environ'))
    w_v = space.call_method(w_environ, 'get', space.wrap(name))
    try:
        return space.str_w(w_v)
    except:
        return None

Example #48
0
    if not w_newcls.is_heaptype():
        raise OperationError(space.w_TypeError,
                             space.wrap("__class__ assignment: only for heap types"))
    w_oldcls = space.type(w_obj)
    assert isinstance(w_oldcls, W_TypeObject)
    if w_oldcls.get_full_instance_layout() == w_newcls.get_full_instance_layout():
        w_obj.setclass(space, w_newcls)
    else:
        raise operationerrfmt(space.w_TypeError,
                              "__class__ assignment: '%s' object layout differs from '%s'",
                              w_oldcls.getname(space), w_newcls.getname(space))


app = gateway.applevel("""
def _abstract_method_error(typ):
    methods = ", ".join(sorted(typ.__abstractmethods__))
    err = "Can't instantiate abstract class %s with abstract methods %s"
    raise TypeError(err % (typ.__name__, methods))
""")
_abstract_method_error = app.interphook("_abstract_method_error")


def descr__new__(space, w_type, __args__):
    from pypy.objspace.std.objectobject import W_ObjectObject
    from pypy.objspace.std.typetype import _precheck_for_new
    # don't allow arguments if the default object.__init__() is about
    # to be called
    w_type = _precheck_for_new(space, w_type)
    w_parentinit, w_ignored = w_type.lookup_where('__init__')
    if w_parentinit is space.w_object:
        try:
            __args__.fixedunpack(0)
Example #49
0
@elidable_promote()
def _pure_issubtype(w_sub, w_type, version_tag1, version_tag2):
    return _issubtype(w_sub, w_type)


# ____________________________________________________________

abstract_mro = gateway.applevel("""
    def abstract_mro(klass):
        # abstract/classic mro
        mro = []
        stack = [klass]
        while stack:
            klass = stack.pop()
            if klass not in mro:
                mro.append(klass)
                if not isinstance(klass.__bases__, tuple):
                    raise TypeError, '__bases__ must be a tuple'
                stack += klass.__bases__[::-1]
        return mro
""",
                                filename=__file__).interphook("abstract_mro")


def get_mro(space, klass):
    if isinstance(klass, W_TypeObject):
        return list(klass.mro_w)
    else:
        return space.unpackiterable(abstract_mro(space, klass))
Example #50
0
               "library module to be run as a script (terminates option list)",
               default=False, cmdline="-m"),
    BoolOption("runcommand",
               "program passed in as CMD (terminates option list)",
               default=False, cmdline="-c"),
    StrOption("warn",
              "warning control (arg is action:message:category:module:lineno)",
              default=None, cmdline="-W"),
 
    ])

pypy_init = gateway.applevel('''
def pypy_init(import_site):
    if import_site:
        try:
            import site
        except:
            import sys
            print("'import site' failed", file=sys.stderr)
''').interphook('pypy_init')


def set_compiler(option, opt, value, parser):
    from rpython.translator.platform import set_platform
    set_platform('host', value)

def main_(argv=None):
    starttime = time.time()
    config, parser = option.get_standard_options()
    interactiveconfig = Config(cmdline_optiondescr)
    to_optparse(interactiveconfig, parser=parser)
Example #51
0
    else:
        w_dict.delitem(w_key)
        return w_item

app = gateway.applevel('''
    def dictrepr(currently_in_repr, d):
        # Now we only handle one implementation of dicts, this one.
        # The fix is to move this to dicttype.py, and do a
        # multimethod lookup mapping str to StdObjSpace.str
        # This cannot happen until multimethods are fixed. See dicttype.py
            dict_id = id(d)
            if dict_id in currently_in_repr:
                return '{...}'
            currently_in_repr[dict_id] = 1
            try:
                items = []
                # XXX for now, we cannot use iteritems() at app-level because
                #     we want a reasonable result instead of a RuntimeError
                #     even if the dict is mutated by the repr() in the loop.
                for k, v in dict.items(d):
                    items.append(repr(k) + ": " + repr(v))
                return "{" +  ', '.join(items) + "}"
            finally:
                try:
                    del currently_in_repr[dict_id]
                except:
                    pass
''', filename=__file__)

dictrepr = app.interphook("dictrepr")

def repr__DictMulti(space, w_dict):
Example #52
0
app = gateway.applevel(r'''
    def _classdir(klass):
        """__dir__ for type objects

        This includes all attributes of klass and all of the base
        classes recursively.
        """
        names = set()
        ns = getattr(klass, '__dict__', None)
        if ns is not None:
            names.update(ns)
        bases = getattr(klass, '__bases__', None)
        if bases is not None:
            # Note that since we are only interested in the keys, the order
            # we merge classes is unimportant
            for base in bases:
                names.update(_classdir(base))
        return names

    def _objectdir(obj):
        """__dir__ for generic objects

         Returns __dict__, __class__ and recursively up the
         __class__.__bases__ chain.
        """
        names = set()
        ns = getattr(obj, '__dict__', None)
        if isinstance(ns, dict):
            names.update(ns)
        klass = getattr(obj, '__class__', None)
        if klass is not None:
            names.update(_classdir(klass))
        return names
''', filename=__file__)
Example #53
0
    #w_real = space.call_function(space.w_float,space.wrap(w_self.realval))
    #w_imag = space.call_function(space.w_float,space.wrap(-w_self.imagval))
    return space.newcomplex(w_self.realval,-w_self.imagval)

app = gateway.applevel(""" 
    import math
    def possint(f):
        ff = math.floor(f)
        if f == ff:
            return int(ff)
        return f

    def repr__Complex(f):
        if not f.real:
            return repr(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+repr(possint(f.real)) + sign + repr(possint(f.imag))+'j)'

    def str__Complex(f):
        if not f.real:
            return str(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+str(possint(f.real)) + sign + str(possint(f.imag))+'j)'

""", filename=__file__) 

repr__Complex = app.interphook('repr__Complex') 
str__Complex = app.interphook('str__Complex') 
Example #54
0
from rpython.rlib import rbigint, rfloat
from rpython.rtyper.lltypesystem import rffi


app = gateway.applevel("""
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield
class float_info:
    __metaclass__ = structseqtype

    max = structseqfield(0)
    max_exp = structseqfield(1)
    max_10_exp = structseqfield(2)
    min = structseqfield(3)
    min_exp = structseqfield(4)
    min_10_exp = structseqfield(5)
    dig = structseqfield(6)
    mant_dig = structseqfield(7)
    epsilon = structseqfield(8)
    radix = structseqfield(9)
    rounds = structseqfield(10)

class long_info:
    __metaclass__ = structseqtype
    bits_per_digit = structseqfield(0)
    sizeof_digit = structseqfield(1)
""")


def get_float_info(space):
    info_w = [
Example #55
0
app = gateway.applevel('''
def unicode_from_encoded_object(obj, encoding, errors):
    import codecs, sys
    if encoding is None:
        encoding = sys.getdefaultencoding()
    decoder = codecs.getdecoder(encoding)
    if errors is None:
        retval, length = decoder(obj)
    else:
        retval, length = decoder(obj, errors)
    if not isinstance(retval, unicode):
        raise TypeError("decoder did not return an unicode object (type=%s)" %
                        type(retval).__name__)
    return retval

def unicode_from_object(obj):
    if isinstance(obj, str):
        res = obj
    else:
        try:
            unicode_method = obj.__unicode__
        except AttributeError:
            res = str(obj)
        else:
            res = unicode_method()
    if isinstance(res, unicode):
        return res
    return unicode_from_encoded_object(res, None, "strict")
    
''')
unicode_from_object = app.interphook('unicode_from_object')
Example #56
0
app = gateway.applevel(r'''
    """ applevel implementation of certain system properties, imports
    and other helpers"""
    import sys
    
    def sys_stdout():
        try: 
            return sys.stdout
        except AttributeError:
            raise RuntimeError("lost sys.stdout")

    def print_expr(obj):
        try:
            displayhook = sys.displayhook
        except AttributeError:
            raise RuntimeError("lost sys.displayhook")
        displayhook(obj)

    def print_item_to(x, stream):
        if file_softspace(stream, False):
           stream.write(" ")
        stream.write(str(x))

        # add a softspace unless we just printed a string which ends in a '\t'
        # or '\n' -- or more generally any whitespace character but ' '
        if isinstance(x, str) and x and x[-1].isspace() and x[-1]!=' ':
            return 
        # XXX add unicode handling
        file_softspace(stream, True)
    print_item_to._annspecialcase_ = "specialize:argtype(0)"

    def print_item(x):
        print_item_to(x, sys_stdout())
    print_item._annspecialcase_ = "flowspace:print_item"

    def print_newline_to(stream):
        stream.write("\n")
        file_softspace(stream, False)

    def print_newline():
        print_newline_to(sys_stdout())
    print_newline._annspecialcase_ = "flowspace:print_newline"

    def file_softspace(file, newflag):
        try:
            softspace = file.softspace
        except AttributeError:
            softspace = 0
        try:
            file.softspace = newflag
        except AttributeError:
            pass
        return softspace
''', filename=__file__)
Example #57
0
            return self.space.w_None
        else:
            return self.space.wrap(self.maxlen)


app = gateway.applevel("""
    def dequerepr(currently_in_repr, d):
        'The app-level part of repr().'
        deque_id = id(d)
        if deque_id in currently_in_repr:
            listrepr = '[...]'
        else:
            currently_in_repr[deque_id] = 1
            try:
                listrepr = "[" + ", ".join([repr(x) for x in d]) + ']'
            finally:
                try:
                    del currently_in_repr[deque_id]
                except:
                    pass
        if d.maxlen is None:
            maxlenrepr = ''
        else:
            maxlenrepr = ', maxlen=%d' % (d.maxlen,)
        return 'deque(%s%s)' % (listrepr, maxlenrepr)
""",
                       filename=__file__)

dequerepr = app.interphook("dequerepr")


def descr__new__(space, w_subtype, __args__):
Example #58
0
                  code, consts_w[:], names, varnames, filename,
                  name, firstlineno, lnotab, freevars, cellvars)
    return space.wrap(code)
register(TYPE_CODE, unmarshal_pycode)

def marshal_w__Unicode(space, w_unicode, m):
    s = unicodehelper.PyUnicode_EncodeUTF8(space, space.unicode_w(w_unicode))
    m.atom_str(TYPE_UNICODE, s)

def unmarshal_Unicode(space, u, tc):
    return space.wrap(unicodehelper.PyUnicode_DecodeUTF8(space, u.get_str()))
register(TYPE_UNICODE, unmarshal_Unicode)

app = gateway.applevel(r'''
    def tuple_to_set(datalist, frozen=False):
        if frozen:
            return frozenset(datalist)
        return set(datalist)
''')

tuple_to_set = app.interphook('tuple_to_set')

# not directly supported:
def marshal_w_set(space, w_set, m):
    # cannot access this list directly, because it's
    # type is not exactly known through applevel.
    lis_w = space.fixedview(w_set)
    m.put_tuple_w(TYPE_SET, lis_w)

handled_by_any.append( ('set', marshal_w_set) )

# not directly supported:
Example #59
0
    # prebuilt integer's intval.  This makes sure that the intval field
    # is present in the cache in the common case where it is quickly
    # reused.  (we could use a prefetch hint if we had that)
    w_res.intval = x
    return w_res


divmod_near = applevel('''
       def divmod_near(a, b):
           """Return a pair (q, r) such that a = b * q + r, and abs(r)
           <= abs(b)/2, with equality possible only if q is even.  In
           other words, q == a / b, rounded to the nearest integer using
           round-half-to-even."""
           q, r = divmod(a, b)
           # round up if either r / b > 0.5, or r / b == 0.5 and q is
           # odd.  The expression r / b > 0.5 is equivalent to 2 * r > b
           # if b is positive, 2 * r < b if b negative.
           greater_than_half = 2*r > b if b > 0 else 2*r < b
           exactly_half = 2*r == b
           if greater_than_half or exactly_half and q % 2 == 1:
               q += 1
               r -= b
           return q, r
''', filename=__file__).interphook('divmod_near')


def _recover_with_smalllong(space):
    """True if there is a chance that a SmallLong would fit when an Int
    does not
    """
    return (space.config.objspace.std.withsmalllong and