Beispiel #1
0
    def test_multiple_inheritance(self):
        class W_A(W_Root):
            a = 1
            b = 2

        class W_C(W_A):
            b = 3

        W_A.typedef = typedef.TypeDef(
            "A",
            a=typedef.interp_attrproperty("a", cls=W_A),
            b=typedef.interp_attrproperty("b", cls=W_A),
        )

        class W_B(W_Root):
            pass

        def standalone_method(space, w_obj):
            if isinstance(w_obj, W_A):
                return space.w_True
            else:
                return space.w_False

        W_B.typedef = typedef.TypeDef("B", c=interp2app(standalone_method))
        W_C.typedef = typedef.TypeDef("C", (
            W_A.typedef,
            W_B.typedef,
        ))

        w_o1 = self.space.wrap(W_C())
        w_o2 = self.space.wrap(W_B())
        w_c = self.space.gettypefor(W_C)
        w_b = self.space.gettypefor(W_B)
        w_a = self.space.gettypefor(W_A)
        assert w_c.mro_w == [
            w_c,
            w_a,
            w_b,
            self.space.w_object,
        ]
        for w_tp in w_c.mro_w:
            assert self.space.isinstance_w(w_o1, w_tp)

        def assert_attr(w_obj, name, value):
            assert self.space.unwrap(
                self.space.getattr(w_obj, self.space.wrap(name))) == value

        def assert_method(w_obj, name, value):
            assert self.space.unwrap(self.space.call_method(w_obj,
                                                            name)) == value

        assert_attr(w_o1, "a", 1)
        assert_attr(w_o1, "b", 3)
        assert_method(w_o1, "c", True)
        assert_method(w_o2, "c", False)
Beispiel #2
0
def test_with_new_with_allocate_instance_subclass():
    py.test.skip("dealloction for now segfaults")
    def mytype_new(space, w_subtype, x):
        w_obj = space.allocate_instance(W_MyType, w_subtype)
        W_MyType.__init__(space.interp_w(W_MyType, w_obj), space, x)
        return w_obj
    mytype_new.unwrap_spec = [ObjSpace, W_Root, int]

    W_MyType.typedef = TypeDef("MyType",
                               __new__ = interp2app(mytype_new),
                               x = interp_attrproperty("x", W_MyType))
    space = CPyObjSpace()

    def build():
        w_type = space.gettypefor(W_MyType)
        return space.call_function(w_type, space.wrap(42))

    fn = compile(build, [],
                 annotatorpolicy = CPyAnnotatorPolicy(space))
    res = fn(expected_extra_mallocs=1)
    assert type(res).__name__ == 'MyType'
    assert res.x == 42

    class MyType2(type(res)):
        pass

    res2 = MyType2(42)
    assert type(res2) is MyType2
    assert res2.x == 42

    del res2
    import gc
    gc.collect()
Beispiel #3
0
def test_with_new_with_allocate_instance():
    def mytype_new(space, w_subtype, x):
        w_obj = space.allocate_instance(W_MyType, w_subtype)
        W_MyType.__init__(space.interp_w(W_MyType, w_obj), space, x)
        return w_obj
    mytype_new.unwrap_spec = [ObjSpace, W_Root, int]

    W_MyType.typedef = TypeDef("MyType",
                               __new__ = interp2app(mytype_new),
                               x = interp_attrproperty("x", W_MyType))
    space = CPyObjSpace()

    def build():
        w_type = space.gettypefor(W_MyType)
        return space.call_function(w_type, space.wrap(42))

    w_obj = build()
    w_name = space.getattr(space.type(w_obj), space.wrap('__name__'))
    assert space.unwrap(w_name) == 'MyType'
    assert space.int_w(space.getattr(w_obj, space.wrap('x'))) == 42

    fn = compile(build, [],
                 annotatorpolicy = CPyAnnotatorPolicy(space))
    res = fn(expected_extra_mallocs=1)
    assert type(res).__name__ == 'MyType'
    assert res.x == 42
Beispiel #4
0
def test_interp_attrproperty():
    W_MyType.typedef = TypeDef("MyType",
                               x = interp_attrproperty("x", W_MyType))
    space = CPyObjSpace()

    def mytest(w_myobj):
        myobj = space.interp_w(W_MyType, w_myobj, can_be_None=True)
        if myobj is None:
            myobj = W_MyType(space)
            myobj.x = 1
        myobj.x *= 2
        w_myobj = space.wrap(myobj)
        w_x = space.wrap(myobj.x)
        return space.newtuple([w_myobj, w_x])

    def fn(obj):
        w_obj = W_Object(obj)
        w_res = mytest(w_obj)
        return w_res.value
    fn.allow_someobjects = True

    fn = compile(fn, [object],
                 annotatorpolicy = CPyAnnotatorPolicy(space))

    res, x = fn(None, expected_extra_mallocs=1)
    assert type(res).__name__ == 'MyType'
    assert x == 2
    assert res.x == 2

    res2, x = fn(res, expected_extra_mallocs=1)
    assert res2 is res
    assert x == 4
    assert res.x == 4
Beispiel #5
0
def patch_pypy():
    # Patch-out virtualizables from PyPy so that translation works
    try:
        # TODO: what if first delattr fails?
        delattr(PyFrame, '_virtualizable_')
        delattr(PyPyJitDriver, 'virtualizables')
    except AttributeError:
        pass

    PyStdObjSpace.current_python_process = QuasiConstant(None, W_PythonProcess)
    PyStdObjSpace.getexecutioncontext = new_getexecutioncontext

    PyFrame.__init__ = __init__frame
    PyFrame.execute_frame = new_execute_frame
    PyFrame.block_handles_exception = block_handles_exception
    PyFrame.has_exception_handler = has_exception_handler
    PyFrame.handle_operation_error = new_handle_operation_error

    PyCode.__init__ = __init__pycode
    PyCode._immutable_fields_.extend(['_co_names[*]', 'co_source'])

    # Add app-level `co_source` to PyCode (this is hacky)
    w_code_type = py_space.fromcache(TypeCache).getorbuild(PyCode.typedef)
    w_code_type.dict_w['co_source'] = interp_attrproperty(
        'co_source', cls=PyCode, wrapfn="newtext_or_none")

    PythonAstCompiler.compile = new_compile
Beispiel #6
0
def patch_unicodedb():
    from pypy.module.unicodedata import unicodedb_4_1_0
    from pypy.module.unicodedata.interp_ucd import UCD, methods, \
         unichr_to_code_w
    from pypy.interpreter.gateway import W_Root, ObjSpace, NoneNotWrapped
    from unicodedb import _casefold
    from pypy.interpreter.typedef import TypeDef, interp_attrproperty
    from pypy.interpreter.gateway import  interp2app

    def casefold(code):
        try:
            return _casefold[code]
        except KeyError:
            return [code]

    unicodedb_4_1_0.casefold = casefold

    # patch the app-level, so it's exposed
    def interp_casefold(self, space, w_unichr):
        code = unichr_to_code_w(space, w_unichr)
        return space.newlist([space.wrap(c) for c in casefold(code)])
    unwrap_spec = ['self', ObjSpace, W_Root]
    
    UCD.casefold = interp_casefold
    methods['casefold'] = interp2app(UCD.casefold, unwrap_spec=unwrap_spec)
    UCD.typedef = TypeDef("unicodedata.UCD",
                          __doc__ = "",
                          unidata_version = interp_attrproperty('version', UCD),
                          **methods)
Beispiel #7
0
def patch_unicodedb():
    from pypy.module.unicodedata import unicodedb_4_1_0
    from pypy.module.unicodedata.interp_ucd import UCD, methods, \
         unichr_to_code_w
    from pypy.interpreter.gateway import W_Root, ObjSpace, NoneNotWrapped
    from unicodedb import _casefold
    from pypy.interpreter.typedef import TypeDef, interp_attrproperty
    from pypy.interpreter.gateway import interp2app

    def casefold(code):
        try:
            return _casefold[code]
        except KeyError:
            return [code]

    unicodedb_4_1_0.casefold = casefold

    # patch the app-level, so it's exposed
    def interp_casefold(self, space, w_unichr):
        code = unichr_to_code_w(space, w_unichr)
        return space.newlist([space.wrap(c) for c in casefold(code)])

    unwrap_spec = ['self', ObjSpace, W_Root]

    UCD.casefold = interp_casefold
    methods['casefold'] = interp2app(UCD.casefold, unwrap_spec=unwrap_spec)
    UCD.typedef = TypeDef("unicodedata.UCD",
                          __doc__="",
                          unidata_version=interp_attrproperty('version', UCD),
                          **methods)
Beispiel #8
0
def wrap_many(cls, names):
    d = {}
    for name in names:
        if "duration" in name:
            wrapfn = "newfloat"
        else:
            wrapfn = "newint"
        d[name] = interp_attrproperty(name, cls=cls, wrapfn=wrapfn)
    return d
Beispiel #9
0
    def test_multiple_inheritance(self):
        class W_A(W_Root):
            a = 1
            b = 2
        class W_C(W_A):
            b = 3
        W_A.typedef = typedef.TypeDef("A",
            a = typedef.interp_attrproperty("a", cls=W_A),
            b = typedef.interp_attrproperty("b", cls=W_A),
        )
        class W_B(W_Root):
            pass
        def standalone_method(space, w_obj):
            if isinstance(w_obj, W_A):
                return space.w_True
            else:
                return space.w_False
        W_B.typedef = typedef.TypeDef("B",
            c = interp2app(standalone_method)
        )
        W_C.typedef = typedef.TypeDef("C", (W_A.typedef, W_B.typedef,))

        w_o1 = self.space.wrap(W_C())
        w_o2 = self.space.wrap(W_B())
        w_c = self.space.gettypefor(W_C)
        w_b = self.space.gettypefor(W_B)
        w_a = self.space.gettypefor(W_A)
        assert w_c.mro_w == [
            w_c,
            w_a,
            w_b,
            self.space.w_object,
        ]
        for w_tp in w_c.mro_w:
            assert self.space.isinstance_w(w_o1, w_tp)
        def assert_attr(w_obj, name, value):
            assert self.space.unwrap(self.space.getattr(w_obj, self.space.wrap(name))) == value
        def assert_method(w_obj, name, value):
            assert self.space.unwrap(self.space.call_method(w_obj, name)) == value
        assert_attr(w_o1, "a", 1)
        assert_attr(w_o1, "b", 3)
        assert_method(w_o1, "c", True)
        assert_method(w_o2, "c", False)
Beispiel #10
0
                                set,
                                del_,
                                doc,
                                cls=None,
                                use_closure=True,
                                tag="cpyext_2")


# change the typedef name
W_MemberDescr.typedef = TypeDef(
    "member_descriptor",
    __get__=interp2app(GetSetProperty.descr_property_get),
    __set__=interp2app(GetSetProperty.descr_property_set),
    __delete__=interp2app(GetSetProperty.descr_property_del),
    __name__=interp_attrproperty('name',
                                 cls=GetSetProperty,
                                 wrapfn="newtext_or_none"),
    __objclass__=GetSetProperty(GetSetProperty.descr_get_objclass),
    __doc__=interp_attrproperty('doc',
                                cls=GetSetProperty,
                                wrapfn="newtext_or_none"),
)
assert not W_MemberDescr.typedef.acceptable_as_base_class  # no __new__


@bootstrap_function
def init_memberdescrobject(space):
    make_typedescr(
        W_MemberDescr.typedef,
        basestruct=cts.gettype('PyMemberDescrObject'),
        attach=memberdescr_attach,
Beispiel #11
0
W_SRE_Pattern.typedef = TypeDef(
    'SRE_Pattern',
    __new__=interp2app(SRE_Pattern__new__),
    __copy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __deepcopy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __weakref__=make_weakref_descr(W_SRE_Pattern),
    findall=interp2app(W_SRE_Pattern.findall_w),
    finditer=interp2app(W_SRE_Pattern.finditer_w),
    match=interp2app(W_SRE_Pattern.match_w),
    scanner=interp2app(W_SRE_Pattern.finditer_w),  # reuse finditer()
    search=interp2app(W_SRE_Pattern.search_w),
    split=interp2app(W_SRE_Pattern.split_w),
    sub=interp2app(W_SRE_Pattern.sub_w),
    subn=interp2app(W_SRE_Pattern.subn_w),
    flags=interp_attrproperty('flags', W_SRE_Pattern),
    groupindex=interp_attrproperty_w('w_groupindex', W_SRE_Pattern),
    groups=interp_attrproperty('num_groups', W_SRE_Pattern),
    pattern=interp_attrproperty_w('w_pattern', W_SRE_Pattern),
)

# ____________________________________________________________
#
# SRE_Match class


class W_SRE_Match(Wrappable):
    flatten_cache = None

    def __init__(self, srepat, ctx):
        self.space = srepat.space
Beispiel #12
0
W_SRE_Pattern.typedef = TypeDef(
    'SRE_Pattern',
    __new__=interp2app(SRE_Pattern__new__),
    __copy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __deepcopy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __weakref__=make_weakref_descr(W_SRE_Pattern),
    findall=interp2app(W_SRE_Pattern.findall_w),
    finditer=interp2app(W_SRE_Pattern.finditer_w),
    match=interp2app(W_SRE_Pattern.match_w),
    scanner=interp2app(W_SRE_Pattern.finditer_w),  # reuse finditer()
    search=interp2app(W_SRE_Pattern.search_w),
    split=interp2app(W_SRE_Pattern.split_w),
    sub=interp2app(W_SRE_Pattern.sub_w),
    subn=interp2app(W_SRE_Pattern.subn_w),
    flags=interp_attrproperty('flags', W_SRE_Pattern, wrapfn="newint"),
    groupindex=interp_attrproperty_w('w_groupindex', W_SRE_Pattern),
    groups=interp_attrproperty('num_groups', W_SRE_Pattern, wrapfn="newint"),
    pattern=interp_attrproperty_w('w_pattern', W_SRE_Pattern),
)
W_SRE_Pattern.typedef.acceptable_as_base_class = False

# ____________________________________________________________
#
# SRE_Match class


class W_SRE_Match(W_Root):
    flatten_cache = None

    def __init__(self, srepat, ctx):
Beispiel #13
0
        # I could not figure out a case in which flush() in CPython
        # doesn't simply return an empty string without complaining.
        return self.space.wrap("")

    flush.unwrap_spec = ['self', int]


def Decompress___new__(space, w_subtype, wbits=rzlib.MAX_WBITS):
    """
    Create a new Decompress and call its initializer.
    """
    stream = space.allocate_instance(Decompress, w_subtype)
    stream = space.interp_w(Decompress, stream)
    Decompress.__init__(stream, space, wbits)
    return space.wrap(stream)


Decompress___new__.unwrap_spec = [ObjSpace, W_Root, int]

Decompress.typedef = TypeDef(
    'Decompress',
    __new__=interp2app(Decompress___new__),
    decompress=interp2app(Decompress.decompress),
    flush=interp2app(Decompress.flush),
    unused_data=interp_attrproperty('unused_data', Decompress),
    unconsumed_tail=interp_attrproperty('unconsumed_tail', Decompress),
    __doc__="""decompressobj([wbits]) -- Return a decompressor object.

Optional arg wbits is the window buffer size.
""")
Beispiel #14
0
    def build(self, space, r, stop):
        builder = Utf8StringBuilder(stop * 3)
        for i in range(stop):
            builder.append_code(r[i])
        return space.newutf8(builder.build(), stop)


methods = {}
for methodname in """
        _get_code lookup name decimal digit numeric category east_asian_width
        bidirectional combining mirrored decomposition normalize
        """.split():
    methods[methodname] = interp2app(getattr(UCD, methodname))

UCD.typedef = TypeDef("unicodedata.UCD",
                      __doc__="",
                      unidata_version=interp_attrproperty('version',
                                                          UCD,
                                                          wrapfn="newtext"),
                      **methods)

ucd_3_2_0 = UCD(unicodedb_3_2_0)
ucd_5_2_0 = UCD(unicodedb_5_2_0)
ucd = ucd_5_2_0

# This is the default unicodedb used in various places:
# - the unicode type
# - the regular expression engine
unicodedb = ucd._unicodedb
Beispiel #15
0
            fmax = (r_longlong(1) << (self.bitsize - 1)) - 1
            if fmax == 0:
                fmax = 1  # special case to let "int x:1" receive "1"
        else:
            is_signed = False
            fmin = r_longlong(0)
            fmax = r_longlong((r_ulonglong(1) << self.bitsize) - 1)
        if value < fmin or value > fmax:
            raise oefmt(
                space.w_OverflowError,
                "value %d outside the range allowed by the bit field "
                "width: %d <= x <= %d", value, fmin, fmax)
        rawmask = ((r_ulonglong(1) << self.bitsize) - 1) << self.bitshift
        rawvalue = r_ulonglong(value) << self.bitshift
        rawfielddata = misc.read_raw_unsigned_data(cdata, ctype.size)
        rawfielddata = (rawfielddata & ~rawmask) | (rawvalue & rawmask)
        if is_signed:
            misc.write_raw_signed_data(cdata, rawfielddata, ctype.size)
        else:
            misc.write_raw_unsigned_data(cdata, rawfielddata, ctype.size)


W_CField.typedef = TypeDef(
    '_cffi_backend.CField',
    type=interp_attrproperty('ctype', W_CField),
    offset=interp_attrproperty('offset', W_CField),
    bitshift=interp_attrproperty('bitshift', W_CField),
    bitsize=interp_attrproperty('bitsize', W_CField),
)
W_CField.typedef.acceptable_as_base_class = False
Beispiel #16
0
        self.name = name
        self.w_ffitype = w_ffitype
        self.offset = -1

    def __repr__(self):
        return '<Field %s %s>' % (self.name, self.w_ffitype.name)

@unwrap_spec(name=str)
def descr_new_field(space, w_type, name, w_ffitype):
    w_ffitype = space.interp_w(W_FFIType, w_ffitype)
    return W_Field(name, w_ffitype)

W_Field.typedef = TypeDef(
    'Field',
    __new__ = interp2app(descr_new_field),
    name = interp_attrproperty('name', W_Field),
    ffitype = interp_attrproperty('w_ffitype', W_Field),
    offset = interp_attrproperty('offset', W_Field),
    )


# ==============================================================================

class FFIStructOwner(object):
    """
    The only job of this class is to stay outside of the reference cycle
    W__StructDescr -> W_FFIType -> W__StructDescr and free the ffistruct
    """

    def __init__(self, ffistruct):
        self.ffistruct = ffistruct
Beispiel #17
0
        return space.wrap(Method(space, w_function, w_obj, w_cls))
    else:
        return w_function

def cclassmethod_descr_get(space, w_function, w_obj, w_cls=None):
    if not w_cls:
        w_cls = space.type(w_obj)
    return space.wrap(Method(space, w_function, w_cls, space.w_None))


W_PyCFunctionObject.typedef = TypeDef(
    'builtin_function_or_method',
    __call__ = interp2app(cfunction_descr_call),
    __doc__ = GetSetProperty(W_PyCFunctionObject.get_doc),
    __module__ = interp_attrproperty_w('w_module', cls=W_PyCFunctionObject),
    __name__ = interp_attrproperty('name', cls=W_PyCFunctionObject),
    )
W_PyCFunctionObject.typedef.acceptable_as_base_class = False

W_PyCMethodObject.typedef = TypeDef(
    'method',
    __get__ = interp2app(cmethod_descr_get),
    __call__ = interp2app(cmethod_descr_call),
    __name__ = interp_attrproperty('name', cls=W_PyCMethodObject),
    __objclass__ = interp_attrproperty_w('w_objclass', cls=W_PyCMethodObject),
    __repr__ = interp2app(W_PyCMethodObject.descr_method_repr),
    )
W_PyCMethodObject.typedef.acceptable_as_base_class = False

W_PyCClassMethodObject.typedef = TypeDef(
    'classmethod',
Beispiel #18
0
        except rzlib.RZlibError:
            string = ""
        else:
            string, finished, unused_len = result
            self._save_unconsumed_input(data, finished, unused_len)
        return space.wrap(string)


@unwrap_spec(wbits=int)
def Decompress___new__(space, w_subtype, wbits=rzlib.MAX_WBITS):
    """
    Create a new Decompress and call its initializer.
    """
    stream = space.allocate_instance(Decompress, w_subtype)
    stream = space.interp_w(Decompress, stream)
    Decompress.__init__(stream, space, wbits)
    return space.wrap(stream)


Decompress.typedef = TypeDef(
    'Decompress',
    __new__ = interp2app(Decompress___new__),
    decompress = interp2app(Decompress.decompress),
    flush = interp2app(Decompress.flush),
    unused_data = interp_attrproperty('unused_data', Decompress),
    unconsumed_tail = interp_attrproperty('unconsumed_tail', Decompress),
    __doc__ = """decompressobj([wbits]) -- Return a decompressor object.

Optional arg wbits is the window buffer size.
""")
Beispiel #19
0
        except OSError, e:
            raise wrap_oserror(space, e, exception_name='w_IOError')

        return w_size

W_FileIO.typedef = TypeDef(
    'FileIO', W_RawIOBase.typedef,
    __new__  = interp2app(W_FileIO.descr_new.im_func),
    __init__  = interp2app(W_FileIO.descr_init),
    __repr__ = interp2app(W_FileIO.repr_w),

    seek = interp2app(W_FileIO.seek_w),
    tell = interp2app(W_FileIO.tell_w),
    write = interp2app(W_FileIO.write_w),
    read = interp2app(W_FileIO.read_w),
    readinto = interp2app(W_FileIO.readinto_w),
    readall = interp2app(W_FileIO.readall_w),
    truncate = interp2app(W_FileIO.truncate_w),
    close = interp2app(W_FileIO.close_w),

    readable = interp2app(W_FileIO.readable_w),
    writable = interp2app(W_FileIO.writable_w),
    seekable = interp2app(W_FileIO.seekable_w),
    fileno = interp2app(W_FileIO.fileno_w),
    isatty = interp2app(W_FileIO.isatty_w),
    name = interp_member_w('w_name', cls=W_FileIO),
    closefd = interp_attrproperty('closefd', cls=W_FileIO),
    mode = GetSetProperty(W_FileIO.descr_get_mode),
    )

Beispiel #20
0
bind(addr) -- bind the socket to a local address
close() -- close the socket
connect(addr) -- connect the socket to a remote address
connect_ex(addr) -- connect, return an error code instead of an exception
dup() -- return a new socket object identical to the current one [*]
fileno() -- return underlying file descriptor
getpeername() -- return remote address [*]
getsockname() -- return local address
getsockopt(level, optname[, buflen]) -- get socket options
gettimeout() -- return timeout or None
listen(n) -- start listening for incoming connections
makefile([mode, [bufsize]]) -- return a file object for the socket [*]
recv(buflen[, flags]) -- receive data
recvfrom(buflen[, flags]) -- receive data and sender's address
sendall(data[, flags]) -- send all data
send(data[, flags]) -- send data, may not send all of it
sendto(data[, flags], addr) -- send data to a given address
setblocking(0 | 1) -- set or clear the blocking I/O flag
setsockopt(level, optname, value) -- set socket options
settimeout(None | float) -- set or clear the timeout
shutdown(how) -- shut down traffic in one or both directions

 [*] not available on all platforms!""",
    __new__ = descr_socket_new,
    __weakref__ = make_weakref_descr(W_RSocket),
    type = interp_attrproperty('type', W_RSocket),
    proto = interp_attrproperty('proto', W_RSocket),
    family = interp_attrproperty('family', W_RSocket),
    ** socketmethods
    )
Beispiel #21
0
        if start + len(value) != stop:
            raise OperationError(space.w_ValueError,
                                 space.wrap("cannot resize array"))
        ll_buffer = self.ll_buffer
        for i in range(len(value)):
            ll_buffer[start + i] = value[i]


W_ArrayInstance.typedef = TypeDef(
    'ArrayInstance',
    __repr__=interp2app(W_ArrayInstance.descr_repr),
    __setitem__=interp2app(W_ArrayInstance.descr_setitem),
    __getitem__=interp2app(W_ArrayInstance.descr_getitem),
    __len__=interp2app(W_ArrayInstance.getlength),
    buffer=GetSetProperty(W_ArrayInstance.getbuffer),
    shape=interp_attrproperty('shape', W_ArrayInstance),
    free=interp2app(W_ArrayInstance.free),
    byptr=interp2app(W_ArrayInstance.byptr),
    itemaddress=interp2app(W_ArrayInstance.descr_itemaddress),
)
W_ArrayInstance.typedef.acceptable_as_base_class = False


class W_ArrayInstanceAutoFree(W_ArrayInstance):
    def __init__(self, space, shape, length):
        W_ArrayInstance.__init__(self, space, shape, length, 0)

    @rgc.must_be_light_finalizer
    def __del__(self):
        if self.ll_buffer:
            self._free()
Beispiel #22
0
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

Note:  open() is an alias for file().
""",
    __new__  = interp2app(descr_file__new__),
    fdopen   = interp2app(descr_file_fdopen, as_classmethod=True),
    name     = interp_attrproperty_w('w_name', cls=W_File, doc="file name"),
    mode     = interp_attrproperty('mode', cls=W_File,
                              doc = "file mode ('r', 'U', 'w', 'a', "
                                    "possibly with 'b' or '+' added)"),
    encoding = interp_attrproperty('encoding', cls=W_File),
    errors = interp_attrproperty('errors', cls=W_File),
    closed   = GetSetProperty(descr_file_closed, cls=W_File,
                              doc="True if the file is closed"),
    newlines = GetSetProperty(descr_file_newlines, cls=W_File,
                              doc="end-of-line convention used in this file"),
    softspace= GetSetProperty(descr_file_softspace,
                              descr_file_setsoftspace,
                              cls=W_File,
                              doc="Support for 'print'."),
    __repr__ = interp2app(W_File.file__repr__),
    writelines = interp2app(W_File.file_writelines),
    __exit__ = interp2app(W_File.file__exit__),
    __weakref__ = make_weakref_descr(W_File),
Beispiel #23
0
        start, stop = self.decodeslice(space, w_slice)
        value = space.str_w(w_value)
        if start + len(value) != stop:
            raise oefmt(space.w_ValueError, "cannot resize array")
        ll_buffer = self.ll_buffer
        for i in range(len(value)):
            ll_buffer[start + i] = value[i]

W_ArrayInstance.typedef = TypeDef(
    'ArrayInstance',
    __repr__    = interp2app(W_ArrayInstance.descr_repr),
    __setitem__ = interp2app(W_ArrayInstance.descr_setitem),
    __getitem__ = interp2app(W_ArrayInstance.descr_getitem),
    __len__     = interp2app(W_ArrayInstance.getlength),
    buffer      = GetSetProperty(W_ArrayInstance.getbuffer),
    shape       = interp_attrproperty('shape', W_ArrayInstance),
    free        = interp2app(W_ArrayInstance.free),
    byptr       = interp2app(W_ArrayInstance.byptr),
    itemaddress = interp2app(W_ArrayInstance.descr_itemaddress),
)
W_ArrayInstance.typedef.acceptable_as_base_class = False


class W_ArrayInstanceAutoFree(W_ArrayInstance):
    def __init__(self, space, shape, length):
        W_ArrayInstance.__init__(self, space, shape, length, 0)

    @rgc.must_be_light_finalizer
    def __del__(self):
        if self.ll_buffer:
            self._free()
Beispiel #24
0
    if space.is_true(space.isinstance(w_shapeinfo, space.w_tuple)):
        w_size, w_alignment = space.fixedview(w_shapeinfo, expected_length=2)
        S = W_Structure(space, None, space.int_w(w_size), space.int_w(w_alignment))
    else:
        fields = unpack_fields(space, w_shapeinfo)
        S = W_Structure(space, fields, 0, 0)
    return space.wrap(S)


W_Structure.typedef = TypeDef(
    "Structure",
    __new__=interp2app(descr_new_structure),
    __call__=interp2app(W_Structure.descr_call),
    __repr__=interp2app(W_Structure.descr_repr),
    fromaddress=interp2app(W_Structure.fromaddress),
    size=interp_attrproperty("size", W_Structure),
    alignment=interp_attrproperty("alignment", W_Structure),
    fieldoffset=interp2app(W_Structure.descr_fieldoffset),
    size_alignment=interp2app(W_Structure.descr_size_alignment),
)
W_Structure.typedef.acceptable_as_base_class = False


def push_field(self, num, value):
    ptr = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[num])
    TP = lltype.typeOf(value)
    T = lltype.Ptr(rffi.CArray(TP))
    rffi.cast(T, ptr)[0] = value


push_field._annspecialcase_ = "specialize:argtype(2)"
Beispiel #25
0
W_SRE_Pattern.typedef = TypeDef(
    'SRE_Pattern',
    __new__      = interp2app(SRE_Pattern__new__),
    __copy__     = interp2app(W_SRE_Pattern.cannot_copy_w),
    __deepcopy__ = interp2app(W_SRE_Pattern.cannot_copy_w),
    __weakref__  = make_weakref_descr(W_SRE_Pattern),
    findall      = interp2app(W_SRE_Pattern.findall_w),
    finditer     = interp2app(W_SRE_Pattern.finditer_w),
    match        = interp2app(W_SRE_Pattern.match_w),
    scanner      = interp2app(W_SRE_Pattern.finditer_w),    # reuse finditer()
    search       = interp2app(W_SRE_Pattern.search_w),
    split        = interp2app(W_SRE_Pattern.split_w),
    sub          = interp2app(W_SRE_Pattern.sub_w),
    subn         = interp2app(W_SRE_Pattern.subn_w),
    flags        = interp_attrproperty('flags', W_SRE_Pattern),
    groupindex   = interp_attrproperty_w('w_groupindex', W_SRE_Pattern),
    groups       = interp_attrproperty('num_groups', W_SRE_Pattern),
    pattern      = interp_attrproperty_w('w_pattern', W_SRE_Pattern),
)

# ____________________________________________________________
#
# SRE_Match class

class W_SRE_Match(Wrappable):
    flatten_cache = None

    def __init__(self, srepat, ctx):
        self.space = srepat.space
        self.srepat = srepat
Beispiel #26
0
    def __init__(self, space):
        W_IOError.__init__(self, space)
        self.written = 0

    @unwrap_spec(written=int)
    def descr_init(self, space, w_errno, w_strerror, written=0):
        W_IOError.descr_init(self, space, [w_errno, w_strerror])
        self.written = written

W_BlockingIOError.typedef = TypeDef(
    'BlockingIOError', W_IOError.typedef,
    __doc__ = ("Exception raised when I/O would block on a non-blocking "
               "I/O stream"),
    __new__  = generic_new_descr(W_BlockingIOError),
    __init__ = interp2app(W_BlockingIOError.descr_init),
    characters_written = interp_attrproperty('written', W_BlockingIOError),
    )

DEFAULT_BUFFER_SIZE = 8 * 1024

@unwrap_spec(mode=str, buffering=int,
             encoding="str_or_None", errors="str_or_None",
             newline="str_or_None", closefd=bool)
def open(space, w_file, mode="r", buffering=-1, encoding=None, errors=None,
    newline=None, closefd=True):
    from pypy.module._io.interp_bufferedio import (W_BufferedRandom,
        W_BufferedWriter, W_BufferedReader)

    if not (space.isinstance_w(w_file, space.w_basestring) or
        space.isinstance_w(w_file, space.w_int) or
        space.isinstance_w(w_file, space.w_long)):
Beispiel #27
0
    if space.is_true(space.isinstance(w_shapeinfo, space.w_tuple)):
        w_size, w_alignment = space.fixedview(w_shapeinfo, expected_length=2)
        S = W_Structure(space, None, space.int_w(w_size),
                                     space.int_w(w_alignment), union)
    else:
        fields = unpack_fields(space, w_shapeinfo)
        S = W_Structure(space, fields, 0, 0, union, pack)
    return space.wrap(S)

W_Structure.typedef = TypeDef(
    'Structure',
    __new__     = interp2app(descr_new_structure),
    __call__    = interp2app(W_Structure.descr_call),
    __repr__    = interp2app(W_Structure.descr_repr),
    fromaddress = interp2app(W_Structure.fromaddress),
    size        = interp_attrproperty('size', W_Structure),
    alignment   = interp_attrproperty('alignment', W_Structure),
    fieldoffset = interp2app(W_Structure.descr_fieldoffset),
    fieldsize   = interp2app(W_Structure.descr_fieldsize),
    size_alignment = interp2app(W_Structure.descr_size_alignment),
    get_ffi_type   = interp2app(W_Structure.descr_get_ffi_type),
)
W_Structure.typedef.acceptable_as_base_class = False

def LOW_BIT(x):
    return x & 0xFFFF
def NUM_BITS(x):
    return x >> 16
def BIT_MASK(x):
    return (1 << x) - 1
Beispiel #28
0
                    if bzerror != BZ_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)


W_BZ2Decompressor.typedef = TypeDef("BZ2Decompressor",
    __doc__ = W_BZ2Decompressor.__doc__,
    __new__ = interp2app(descr_decompressor__new__),
    unused_data = interp_attrproperty("unused_data", W_BZ2Decompressor),
    decompress = interp2app(W_BZ2Decompressor.decompress),
)


@unwrap_spec(data='bufferstr', compresslevel=int)
def compress(space, data, compresslevel=9):
    """compress(data [, compresslevel=9]) -> string

    Compress data in one shot. If you want to compress data sequentially,
    use an instance of BZ2Compressor instead. The compresslevel parameter, if
    given, must be a number between 1 and 9."""

    if compresslevel < 1 or compresslevel > 9:
        raise OperationError(space.w_ValueError,
            space.wrap("compresslevel must be between 1 and 9"))
Beispiel #29
0
            if fmax == 0:
                fmax = 1  # special case to let "int x:1" receive "1"
        else:
            is_signed = False
            fmin = r_longlong(0)
            fmax = r_longlong((r_ulonglong(1) << self.bitsize) - 1)
        if value < fmin or value > fmax:
            raise oefmt(
                space.w_OverflowError,
                "value %d outside the range allowed by the bit field "
                "width: %d <= x <= %d", value, fmin, fmax)
        rawmask = ((r_ulonglong(1) << self.bitsize) - 1) << self.bitshift
        rawvalue = r_ulonglong(value) << self.bitshift
        rawfielddata = misc.read_raw_unsigned_data(cdata, ctype.size)
        rawfielddata = (rawfielddata & ~rawmask) | (rawvalue & rawmask)
        if is_signed:
            misc.write_raw_signed_data(cdata, rawfielddata, ctype.size)
        else:
            misc.write_raw_unsigned_data(cdata, rawfielddata, ctype.size)


W_CField.typedef = TypeDef(
    '_cffi_backend.CField',
    type=interp_attrproperty_w('ctype', W_CField),
    offset=interp_attrproperty('offset', W_CField, wrapfn="newint"),
    bitshift=interp_attrproperty('bitshift', W_CField, wrapfn="newint"),
    bitsize=interp_attrproperty('bitsize', W_CField, wrapfn="newint"),
    flags=interp_attrproperty('flags', W_CField, wrapfn="newint"),
)
W_CField.typedef.acceptable_as_base_class = False
Beispiel #30
0
            try:
                status = roci.OCIErrorGet(
                    handle, 1, lltype.nullptr(roci.oratext.TO), codeptr,
                    textbuf, BUFSIZE, handleType)
                if status != roci.OCI_SUCCESS:
                    raise OperationError(
                        get(space).w_InternalError,
                        space.wrap("No Oracle error?"))

                self.code = codeptr[0]
                self.w_message = config.w_string(space, textbuf)
            finally:
                lltype.free(codeptr, flavor='raw')
                rffi.keep_buffer_alive_until_here(textbuf, text)

            if config.WITH_UNICODE:
                # XXX remove double zeros at the end
                pass

    def desc_str(self):
        return self.w_message

W_Error.typedef = TypeDef(
    'Error',
    __str__ = interp2app(W_Error.desc_str),
    code = interp_attrproperty('code', W_Error),
    message = interp_attrproperty_w('w_message', W_Error))


Beispiel #31
0
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

Note:  open() is an alias for file().
""",
    __new__=interp2app(descr_file__new__),
    fdopen=interp2app(descr_file_fdopen, as_classmethod=True),
    name=interp_attrproperty('name', cls=W_File, doc="file name"),
    mode=interp_attrproperty('mode',
                             cls=W_File,
                             doc="file mode ('r', 'U', 'w', 'a', "
                             "possibly with 'b' or '+' added)"),
    encoding=interp_attrproperty('encoding', cls=W_File),
    closed=GetSetProperty(descr_file_closed,
                          cls=W_File,
                          doc="True if the file is closed"),
    newlines=GetSetProperty(descr_file_newlines,
                            cls=W_File,
                            doc="end-of-line convention used in this file"),
    softspace=GetSetProperty(descr_file_softspace,
                             descr_file_setsoftspace,
                             cls=W_File,
                             doc="Support for 'print'."),
Beispiel #32
0
    def is_void(self):
        return self is app_types.void

    def is_struct(self):
        return libffi.types.is_struct(self.get_ffitype())

    def is_char_p(self):
        return self is app_types.char_p

    def is_unichar_p(self):
        return self is app_types.unichar_p


W_FFIType.typedef = TypeDef(
    'FFIType',
    name = interp_attrproperty('name', W_FFIType),
    __repr__ = interp2app(W_FFIType.repr),
    deref_pointer = interp2app(W_FFIType.descr_deref_pointer),
    sizeof = interp2app(W_FFIType.descr_sizeof),
    )


def build_ffi_types():
    types = [
        # note: most of the type name directly come from the C equivalent,
        # with the exception of bytes: in C, ubyte and char are equivalent,
        # but for here the first expects a number while the second a 1-length
        # string
        W_FFIType('slong',     libffi.types.slong),
        W_FFIType('sint',      libffi.types.sint),
        W_FFIType('sshort',    libffi.types.sshort),
Beispiel #33
0
                self.environment.checkForError(
                    status,
                    "ObjectType_Describe(): get attribute param descriptor")
                attribute = W_ObjectAttribute(connection, paramptr[0])
            finally:
                lltype.free(paramptr, flavor='raw')

            self.attributes.append(attribute)
            self.attributesByName[attribute.name] = attribute

    def get_attributes(self, space):
        return space.newlist([space.wrap(attr) for attr in self.attributes])

W_ObjectType.typedef = TypeDef(
    'ObjectType',
    schema = interp_attrproperty('schema', W_ObjectType),
    name = interp_attrproperty('name', W_ObjectType),
    attributes = GetSetProperty(W_ObjectType.get_attributes),
    )

class W_ObjectAttribute(Wrappable):
    def __init__(self, connection, param):
        self.initialize(connection, param)

    def initialize(self, connection, param):
        # determine the name of the attribute
        nameptr = lltype.malloc(rffi.CArrayPtr(roci.oratext).TO, 1,
                                flavor='raw')
        lenptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1,
                               flavor='raw')
        try:
Beispiel #34
0
        return space.wrap(self.string_position)

    def fset_string_position(space, self, w_value):
        self.start = space.int_w(w_value)

    def get_char_ord(self, p):
        raise NotImplementedError

getset_start = GetSetProperty(W_State.fget_start, W_State.fset_start, cls=W_State)
getset_string_position = GetSetProperty(W_State.fget_string_position,
                                     W_State.fset_string_position, cls=W_State)

W_State.typedef = TypeDef("W_State",
    string = interp_attrproperty_w("w_string", W_State),
    start = getset_start,
    end = interp_attrproperty("end", W_State),
    string_position = getset_string_position,
    pos = interp_attrproperty("pos", W_State),
    lastindex = interp_attrproperty("lastindex", W_State),
    reset = interp2app(W_State.w_reset),
    create_regs = interp2app(W_State.w_create_regs),
)


class W_StringState(W_State):
    if THREE_VERSIONS_OF_CORE:
        rsre.insert_sre_methods(locals(), 'str')

    def unwrap_object(self):
        self.string = self.space.str_w(self.w_string)
        return len(self.string)
Beispiel #35
0
    def __init__(self, space):
        W_IOError.__init__(self, space)
        self.written = 0

    @unwrap_spec(written=int)
    def descr_init(self, space, w_errno, w_strerror, written=0):
        W_IOError.descr_init(self, space, [w_errno, w_strerror])
        self.written = written

W_BlockingIOError.typedef = TypeDef(
    'BlockingIOError', W_IOError.typedef,
    __doc__ = ("Exception raised when I/O would block on a non-blocking "
               "I/O stream"),
    __new__  = generic_new_descr(W_BlockingIOError),
    __init__ = interp2app(W_BlockingIOError.descr_init),
    characters_written = interp_attrproperty('written', W_BlockingIOError,
        wrapfn="newint"),
    )

DEFAULT_BUFFER_SIZE = 8 * 1024

@unwrap_spec(mode='text', buffering=int,
             encoding="text_or_none", errors="text_or_none",
             newline="text_or_none", closefd=bool)
def open(space, w_file, mode="r", buffering=-1, encoding=None, errors=None,
    newline=None, closefd=True):
    from pypy.module._io.interp_bufferedio import (W_BufferedRandom,
        W_BufferedWriter, W_BufferedReader)

    if not (space.isinstance_w(w_file, space.w_basestring) or
        space.isinstance_w(w_file, space.w_int) or
        space.isinstance_w(w_file, space.w_long)):
Beispiel #36
0
W_Dtype.typedef = TypeDef("dtype",
    __module__ = "numpypy",
    __new__ = interp2app(descr__new__),

    __str__= interp2app(W_Dtype.descr_str),
    __repr__ = interp2app(W_Dtype.descr_repr),
    __eq__ = interp2app(W_Dtype.descr_eq),
    __ne__ = interp2app(W_Dtype.descr_ne),
    __getitem__ = interp2app(W_Dtype.descr_getitem),
    __len__ = interp2app(W_Dtype.descr_len),

    __reduce__ = interp2app(W_Dtype.descr_reduce),
    __setstate__ = interp2app(W_Dtype.descr_setstate),

    type = interp_attrproperty_w("w_box_type", cls=W_Dtype),
    kind = interp_attrproperty("kind", cls=W_Dtype),
    char = interp_attrproperty("char", cls=W_Dtype),
    num = interp_attrproperty("num", cls=W_Dtype),
    byteorder = interp_attrproperty("byteorder", cls=W_Dtype),
    itemsize = GetSetProperty(W_Dtype.descr_get_itemsize),
    alignment = GetSetProperty(W_Dtype.descr_get_alignment),

    subdtype = GetSetProperty(W_Dtype.descr_get_subdtype),
    str = GetSetProperty(W_Dtype.descr_get_str),
    name = interp_attrproperty("name", cls=W_Dtype),
    base = GetSetProperty(W_Dtype.descr_get_base),
    shape = GetSetProperty(W_Dtype.descr_get_shape),
    isnative = GetSetProperty(W_Dtype.descr_get_isnative),
    fields = GetSetProperty(W_Dtype.descr_get_fields),
    names = GetSetProperty(W_Dtype.descr_get_names),
)
Beispiel #37
0
    def is_namespace(self):
        return self.space.w_False

    def get_base_names(self):
        bases = []
        num_bases = capi.c_num_bases(self)
        for i in range(num_bases):
            base_name = capi.c_base_name(self, i)
            bases.append(self.space.wrap(base_name))
        return self.space.newlist(bases)


W_CPPClass.typedef = TypeDef(
    "CPPClass",
    type_name=interp_attrproperty("name", W_CPPClass),
    get_base_names=interp2app(W_CPPClass.get_base_names),
    get_method_names=interp2app(W_CPPClass.get_method_names),
    get_overload=interp2app(W_CPPClass.get_overload, unwrap_spec=["self", str]),
    get_datamember_names=interp2app(W_CPPClass.get_datamember_names),
    get_datamember=interp2app(W_CPPClass.get_datamember, unwrap_spec=["self", str]),
    is_namespace=interp2app(W_CPPClass.is_namespace),
    dispatch=interp2app(W_CPPClass.dispatch, unwrap_spec=["self", str, str]),
)
W_CPPClass.typedef.acceptable_as_base_class = False


class W_ComplexCPPClass(W_CPPClass):
    _immutable_ = True

    def get_cppthis(self, cppinstance, calling_scope):
Beispiel #38
0
    else:
        return w_function


def cclassmethod_descr_get(space, w_function, w_obj, w_cls=None):
    if not w_cls:
        w_cls = space.type(w_obj)
    return space.wrap(Method(space, w_function, w_cls, space.w_None))


W_PyCFunctionObject.typedef = TypeDef(
    'builtin_function_or_method',
    __call__=interp2app(cfunction_descr_call),
    __doc__=GetSetProperty(W_PyCFunctionObject.get_doc),
    __module__=interp_attrproperty_w('w_module', cls=W_PyCFunctionObject),
    __name__=interp_attrproperty('name', cls=W_PyCFunctionObject),
)
W_PyCFunctionObject.typedef.acceptable_as_base_class = False

W_PyCMethodObject.typedef = TypeDef(
    'method',
    __get__=interp2app(cmethod_descr_get),
    __call__=interp2app(cmethod_descr_call),
    __name__=interp_attrproperty('name', cls=W_PyCMethodObject),
    __objclass__=interp_attrproperty_w('w_objclass', cls=W_PyCMethodObject),
    __repr__=interp2app(W_PyCMethodObject.descr_method_repr),
)
W_PyCMethodObject.typedef.acceptable_as_base_class = False

W_PyCClassMethodObject.typedef = TypeDef(
    'classmethod',
Beispiel #39
0
]

dtypes_by_alias = unrolling_iterable([
    (alias, dtype)
    for dtype in ALL_DTYPES
    for alias in dtype.aliases
])
dtypes_by_apptype = unrolling_iterable([
    (apptype, dtype)
    for dtype in ALL_DTYPES
    for apptype in dtype.applevel_types
])
dtypes_by_num_bytes = unrolling_iterable(sorted([
    (dtype.num_bytes, dtype)
    for dtype in ALL_DTYPES
]))

W_Dtype.typedef = TypeDef("dtype",
    __module__ = "numpy",
    __new__ = interp2app(W_Dtype.descr__new__.im_func),

    __repr__ = interp2app(W_Dtype.descr_repr),
    __str__ = interp2app(W_Dtype.descr_str),

    num = interp_attrproperty("num", cls=W_Dtype),
    kind = interp_attrproperty("kind", cls=W_Dtype),
    itemsize = interp_attrproperty("num_bytes", cls=W_Dtype),
    shape = GetSetProperty(W_Dtype.descr_get_shape),
)
W_Dtype.typedef.acceptable_as_base_class = False
Beispiel #40
0
W_FileIO.typedef = TypeDef(
    '_io.FileIO', W_RawIOBase.typedef,
    __new__  = interp2app(W_FileIO.descr_new.im_func),
    __init__  = interp2app(W_FileIO.descr_init),
    __repr__ = interp2app(W_FileIO.repr_w),
    __getstate__ = interp2app(W_FileIO.getstate_w),

    seek = interp2app(W_FileIO.seek_w),
    tell = interp2app(W_FileIO.tell_w),
    write = interp2app(W_FileIO.write_w),
    read = interp2app(W_FileIO.read_w),
    readinto = interp2app(W_FileIO.readinto_w),
    readall = interp2app(W_FileIO.readall_w),
    truncate = interp2app(W_FileIO.truncate_w),
    close = interp2app(W_FileIO.close_w),

    readable = interp2app(W_FileIO.readable_w),
    writable = interp2app(W_FileIO.writable_w),
    seekable = interp2app(W_FileIO.seekable_w),
    fileno = interp2app(W_FileIO.fileno_w),
    isatty = interp2app(W_FileIO.isatty_w),
    _dealloc_warn = interp2app(W_FileIO._dealloc_warn_w),
    name = interp_member_w('w_name', cls=W_FileIO),
    closefd = interp_attrproperty(
        'closefd', cls=W_FileIO,
        doc="True if the file descriptor will be closed"),
    mode = GetSetProperty(W_FileIO.descr_get_mode,
                          doc="String giving the file mode"),
    )

Beispiel #41
0
        return Method(space, w_function, w_obj, w_cls)
    else:
        return w_function

def cclassmethod_descr_get(space, w_function, w_obj, w_cls=None):
    if not w_cls:
        w_cls = space.type(w_obj)
    return Method(space, w_function, w_cls, space.w_None)


W_PyCFunctionObject.typedef = TypeDef(
    'builtin_function_or_method',
    __call__ = interp2app(cfunction_descr_call),
    __doc__ = GetSetProperty(W_PyCFunctionObject.get_doc),
    __module__ = interp_attrproperty_w('w_module', cls=W_PyCFunctionObject),
    __name__ = interp_attrproperty('name', cls=W_PyCFunctionObject,
        wrapfn="newtext_or_none"),
    )
W_PyCFunctionObject.typedef.acceptable_as_base_class = False

W_PyCMethodObject.typedef = TypeDef(
    'method_descriptor',
    __get__ = interp2app(cmethod_descr_get),
    __call__ = interp2app(W_PyCMethodObject.descr_call),
    __name__ = interp_attrproperty('name', cls=W_PyCMethodObject,
        wrapfn="newtext_or_none"),
    __objclass__ = interp_attrproperty_w('w_objclass', cls=W_PyCMethodObject),
    __repr__ = interp2app(W_PyCMethodObject.descr_method_repr),
    )
W_PyCMethodObject.typedef.acceptable_as_base_class = False

W_PyCClassMethodObject.typedef = TypeDef(
Beispiel #42
0
                      res_dtype, w_lhs, w_rhs, out)
        w_lhs.add_invalidates(w_res)
        w_rhs.add_invalidates(w_res)
        if out:
            w_res.get_concrete()
        return w_res


W_Ufunc.typedef = TypeDef("ufunc",
    __module__ = "numpypy",

    __call__ = interp2app(W_Ufunc.descr_call),
    __repr__ = interp2app(W_Ufunc.descr_repr),

    identity = GetSetProperty(W_Ufunc.descr_get_identity),
    nin = interp_attrproperty("argcount", cls=W_Ufunc),

    reduce = interp2app(W_Ufunc.descr_reduce),
)


def find_binop_result_dtype(space, dt1, dt2, promote_to_float=False,
    promote_bools=False, int_only=False):
    # dt1.num should be <= dt2.num
    if dt1.num > dt2.num:
        dt1, dt2 = dt2, dt1
    if int_only and (not dt1.is_int_type() or not dt2.is_int_type()):
        raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
    # Some operations promote op(bool, bool) to return int8, rather than bool
    if promote_bools and (dt1.kind == dt2.kind == interp_dtype.BOOLLTR):
        return interp_dtype.get_dtype_cache(space).w_int8dtype
Beispiel #43
0
    def is_void(self):
        return self is app_types.void

    def is_struct(self):
        return libffi.types.is_struct(self.get_ffitype())

    def is_char_p(self):
        return self is app_types.char_p

    def is_unichar_p(self):
        return self is app_types.unichar_p


W_FFIType.typedef = TypeDef(
    'FFIType',
    name=interp_attrproperty('name', W_FFIType),
    __repr__=interp2app(W_FFIType.repr),
    deref_pointer=interp2app(W_FFIType.descr_deref_pointer),
    sizeof=interp2app(W_FFIType.descr_sizeof),
)


def build_ffi_types():
    types = [
        # note: most of the type name directly come from the C equivalent,
        # with the exception of bytes: in C, ubyte and char are equivalent,
        # but for here the first expects a number while the second a 1-length
        # string
        W_FFIType('slong', libffi.types.slong),
        W_FFIType('sint', libffi.types.sint),
        W_FFIType('sshort', libffi.types.sshort),
Beispiel #44
0
        if not self.w_calls:
            calls_repr = "None"
        else:
            calls_repr = space.text_w(space.repr(self.w_calls))
        return space.newtext('("%s", %d, %d, %f, %f, %s)' %
                             (frame_repr, self.callcount, self.reccallcount,
                              self.tt, self.it, calls_repr))

    def get_code(self, space):
        return returns_code(space, self.frame)


W_StatsEntry.typedef = TypeDef(
    '_lsprof.StatsEntry',
    code=GetSetProperty(W_StatsEntry.get_code),
    callcount=interp_attrproperty('callcount', W_StatsEntry, wrapfn="newint"),
    reccallcount=interp_attrproperty('reccallcount',
                                     W_StatsEntry,
                                     wrapfn="newint"),
    inlinetime=interp_attrproperty('it', W_StatsEntry, wrapfn="newfloat"),
    totaltime=interp_attrproperty('tt', W_StatsEntry, wrapfn="newfloat"),
    calls=GetSetProperty(W_StatsEntry.get_calls),
    __repr__=interp2app(W_StatsEntry.repr),
)


class W_StatsSubEntry(W_Root):
    def __init__(self, space, frame, callcount, reccallcount, tt, it):
        self.frame = frame
        self.callcount = callcount
        self.reccallcount = reccallcount
Beispiel #45
0
            status = roci.OCIAttrGet(
                self.handle, roci.OCI_HTYPE_SPOOL,
                rffi.cast(roci.dvoidp, valueptr),
                lltype.nullptr(roci.Ptr(roci.ub4).TO),
                oci_attr_code,
                self.environment.errorHandle)
            return space.wrap(valueptr[0])
        finally:
            lltype.free(valueptr, flavor='raw')
    return GetSetProperty(fget, cls=W_SessionPool)

W_SessionPool.typedef = TypeDef(
    "SessionPool",
    __new__ = interp2app(W_SessionPool.descr_new.im_func),
    acquire = interp2app(W_SessionPool.acquire),
    release = interp2app(W_SessionPool.release),
    drop = interp2app(W_SessionPool.drop),

    username = interp_attrproperty_w('w_username', W_SessionPool),
    password = interp_attrproperty_w('w_password', W_SessionPool),
    tnsentry = interp_attrproperty_w('w_tnsentry', W_SessionPool),
    min = interp_attrproperty('minSessions', W_SessionPool),
    max = interp_attrproperty('maxSessions', W_SessionPool),
    increment = interp_attrproperty('sessionIncrement', W_SessionPool),
    homogeneous = interp_attrproperty('homogeneous', W_SessionPool),
    opened = computedProperty(roci.OCI_ATTR_SPOOL_OPEN_COUNT, roci.ub4),
    busy = computedProperty(roci.OCI_ATTR_SPOOL_BUSY_COUNT, roci.ub4),
    timeout = computedProperty(roci.OCI_ATTR_SPOOL_TIMEOUT, roci.ub4),
    getmode = computedProperty(roci.OCI_ATTR_SPOOL_GETMODE, roci.ub1),
    )
Beispiel #46
0
    def repr(self, space):
        frame_repr = space.str_w(space.repr(self.frame))
        if not self.w_calls:
            calls_repr = "None"
        else:
            calls_repr = space.str_w(space.repr(self.w_calls))
        return space.wrap('("%s", %d, %d, %f, %f, %s)' %
                          (frame_repr, self.callcount, self.reccallcount,
                           self.tt, self.it, calls_repr))

    repr.unwrap_spec = ['self', ObjSpace]


W_StatsEntry.typedef = TypeDef(
    'StatsEntry',
    code=interp_attrproperty('frame', W_StatsEntry),
    callcount=interp_attrproperty('callcount', W_StatsEntry),
    reccallcount=interp_attrproperty('reccallcount', W_StatsEntry),
    inlinetime=interp_attrproperty('it', W_StatsEntry),
    totaltime=interp_attrproperty('tt', W_StatsEntry),
    calls=GetSetProperty(W_StatsEntry.get_calls),
    __repr__=interp2app(W_StatsEntry.repr),
)


class W_StatsSubEntry(Wrappable):
    def __init__(self, space, frame, callcount, reccallcount, tt, it):
        self.frame = frame
        self.callcount = callcount
        self.reccallcount = reccallcount
        self.it = it
Beispiel #47
0
        w_size, w_alignment = space.fixedview(w_shapeinfo, expected_length=2)
        S = W_Structure(space, None, space.int_w(w_size),
                        space.int_w(w_alignment), union)
    else:
        fields = unpack_fields(space, w_shapeinfo)
        S = W_Structure(space, fields, 0, 0, union, pack)
    return space.wrap(S)


W_Structure.typedef = TypeDef(
    'Structure',
    __new__=interp2app(descr_new_structure),
    __call__=interp2app(W_Structure.descr_call),
    __repr__=interp2app(W_Structure.descr_repr),
    fromaddress=interp2app(W_Structure.fromaddress),
    size=interp_attrproperty('size', W_Structure),
    alignment=interp_attrproperty('alignment', W_Structure),
    fieldoffset=interp2app(W_Structure.descr_fieldoffset),
    fieldsize=interp2app(W_Structure.descr_fieldsize),
    size_alignment=interp2app(W_Structure.descr_size_alignment),
    get_ffi_type=interp2app(W_Structure.descr_get_ffi_type),
)
W_Structure.typedef.acceptable_as_base_class = False


def LOW_BIT(x):
    return x & 0xFFFF


def NUM_BITS(x):
    return x >> 16
Beispiel #48
0
    def get_char_ord(self, p):
        raise NotImplementedError


getset_start = GetSetProperty(W_State.fget_start,
                              W_State.fset_start,
                              cls=W_State)
getset_string_position = GetSetProperty(W_State.fget_string_position,
                                        W_State.fset_string_position,
                                        cls=W_State)

W_State.typedef = TypeDef(
    "W_State",
    string=interp_attrproperty_w("w_string", W_State),
    start=getset_start,
    end=interp_attrproperty("end", W_State),
    string_position=getset_string_position,
    pos=interp_attrproperty("pos", W_State),
    lastindex=interp_attrproperty("lastindex", W_State),
    reset=interp2app(W_State.w_reset),
    create_regs=interp2app(W_State.w_create_regs),
)


class W_StringState(W_State):
    if THREE_VERSIONS_OF_CORE:
        rsre.insert_sre_methods(locals(), 'str')

    def unwrap_object(self):
        self.string = self.space.str_w(self.w_string)
        return len(self.string)
Beispiel #49
0
    optional \"dialect\" parameter is discussed below.  The function
    also accepts optional keyword arguments which override settings
    provided by the dialect.

    The returned object is an iterator.  Each iteration returns a row
    of the CSV file (which can span multiple input lines)"""
    w_iter = space.iter(w_iterator)
    dialect = _build_dialect(space, w_dialect, w_delimiter, w_doublequote,
                             w_escapechar, w_lineterminator, w_quotechar,
                             w_quoting, w_skipinitialspace, w_strict)
    return W_Reader(space, dialect, w_iter)

W_Reader.typedef = TypeDef(
        '_csv.reader',
        dialect = interp_attrproperty_w('dialect', W_Reader),
        line_num = interp_attrproperty('line_num', W_Reader),
        __iter__ = interp2app(W_Reader.iter_w),
        next = interp2app(W_Reader.next_w),
        __doc__ = """CSV reader

Reader objects are responsible for reading and parsing tabular data
in CSV format.""")
W_Reader.typedef.acceptable_as_base_class = False

# ____________________________________________________________

class FieldLimit:
    limit = 128 * 1024   # max parsed field size
field_limit = FieldLimit()

@unwrap_spec(new_limit=int)
Beispiel #50
0
    '_io.FileIO', W_RawIOBase.typedef,
    __new__  = interp2app(W_FileIO.descr_new.im_func),
    __init__  = interp2app(W_FileIO.descr_init),
    __repr__ = interp2app(W_FileIO.repr_w),
    __getstate__ = interp2app(W_FileIO.getstate_w),

    seek = interp2app(W_FileIO.seek_w),
    tell = interp2app(W_FileIO.tell_w),
    write = interp2app(W_FileIO.write_w),
    read = interp2app(W_FileIO.read_w),
    readinto = interp2app(W_FileIO.readinto_w),
    readall = interp2app(W_FileIO.readall_w),
    truncate = interp2app(W_FileIO.truncate_w),
    close = interp2app(W_FileIO.close_w),

    readable = interp2app(W_FileIO.readable_w),
    writable = interp2app(W_FileIO.writable_w),
    seekable = interp2app(W_FileIO.seekable_w),
    fileno = interp2app(W_FileIO.fileno_w),
    isatty = interp2app(W_FileIO.isatty_w),
    _dealloc_warn = interp2app(W_FileIO._dealloc_warn_w),
    name = interp_member_w('w_name', cls=W_FileIO),
    closefd = interp_attrproperty(
        'closefd', cls=W_FileIO, wrapfn="newbool",
        doc="True if the file descriptor will be closed"),
    mode = GetSetProperty(W_FileIO.descr_get_mode,
                          doc="String giving the file mode"),
    _blksize = GetSetProperty(W_FileIO.get_blksize),
    )

Beispiel #51
0
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

Note:  open() is an alias for file().
""",
    __new__=interp2app(descr_file__new__),
    fdopen=interp2app(descr_file_fdopen, as_classmethod=True),
    name=interp_attrproperty_w('w_name', cls=W_File, doc="file name"),
    mode=interp_attrproperty('mode',
                             cls=W_File,
                             doc="file mode ('r', 'U', 'w', 'a', "
                             "possibly with 'b' or '+' added)",
                             wrapfn="newtext"),
    encoding=interp_attrproperty('encoding',
                                 cls=W_File,
                                 wrapfn="newtext_or_none"),
    errors=interp_attrproperty('errors', cls=W_File, wrapfn="newtext_or_none"),
    closed=GetSetProperty(descr_file_closed,
                          cls=W_File,
                          doc="True if the file is closed"),
    newlines=GetSetProperty(descr_file_newlines,
                            cls=W_File,
                            doc="end-of-line convention used in this file"),
    softspace=GetSetProperty(descr_file_softspace,
                             descr_file_setsoftspace,
                             cls=W_File,
Beispiel #52
0
                    if bzerror != BZ_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)


W_BZ2Decompressor.typedef = TypeDef("BZ2Decompressor",
    __doc__ = W_BZ2Decompressor.__doc__,
    __new__ = interp2app(descr_decompressor__new__),
    unused_data = interp_attrproperty("unused_data", W_BZ2Decompressor),
    decompress = interp2app(W_BZ2Decompressor.decompress),
)


@unwrap_spec(data='bufferstr', compresslevel=int)
def compress(space, data, compresslevel=9):
    """compress(data [, compresslevel=9]) -> string

    Compress data in one shot. If you want to compress data sequentially,
    use an instance of BZ2Compressor instead. The compresslevel parameter, if
    given, must be a number between 1 and 9."""

    if compresslevel < 1 or compresslevel > 9:
        raise OperationError(space.w_ValueError,
            space.wrap("compresslevel must be between 1 and 9"))
Beispiel #53
0
    Create a new Decompress and call its initializer.
    """
    w_stream = space.allocate_instance(Decompress, w_subtype)
    w_stream = space.interp_w(Decompress, w_stream)
    try:
        stream = rzlib.inflateInit(wbits)
    except rzlib.RZlibError as e:
        raise zlib_error(space, e.msg)
    except ValueError:
        raise oefmt(space.w_ValueError, "Invalid initialization option")
    Decompress.__init__(w_stream, space, stream, '', '')
    return w_stream


Decompress.typedef = TypeDef(
    'Decompress',
    __new__=interp2app(Decompress___new__),
    copy=interp2app(Decompress.copy),
    decompress=interp2app(Decompress.decompress),
    flush=interp2app(Decompress.flush),
    unused_data=interp_attrproperty('unused_data',
                                    Decompress,
                                    wrapfn="newbytes"),
    unconsumed_tail=interp_attrproperty('unconsumed_tail',
                                        Decompress,
                                        wrapfn="newbytes"),
    __doc__="""decompressobj([wbits]) -- Return a decompressor object.

Optional arg wbits is the window buffer size.
""")
Beispiel #54
0
if _MS_WINDOWS:
    name_spec = 'fsencode'
else:
    name_spec = 'fsencode_or_none'
@unwrap_spec(name=name_spec)
def descr_new_cdll(space, w_type, name):
    cdll = open_cdll(space, name)
    return W_CDLL(space, name, cdll)

W_CDLL.typedef = TypeDef(
    'CDLL',
    __new__     = interp2app(descr_new_cdll),
    ptr         = interp2app(W_CDLL.ptr),
    getaddressindll = interp2app(W_CDLL.getaddressindll),
    name        = interp_attrproperty('name', W_CDLL,
        wrapfn="newtext_or_none"),
    __doc__     = """ C Dynamically loaded library
use CDLL(libname) to create a handle to a C library (the argument is processed
the same way as dlopen processes it). On such a library you can call:
lib.ptr(func_name, argtype_list, restype)

where argtype_list is a list of single characters and restype is a single
character. The character meanings are more or less the same as in the struct
module, except that s has trailing \x00 added, while p is considered a raw
buffer.""" # xxx fix doc
)

unroll_letters_for_numbers = unrolling_iterable(TYPEMAP_NUMBER_LETTERS)
unroll_letters_for_floats = unrolling_iterable(TYPEMAP_FLOAT_LETTERS)

_ARM = rffi_platform.getdefined('__arm__', '')
Beispiel #55
0
                prev_combining = 0
                current = next
                continue

            result[next_insert] = next
            next_insert += 1
            if next_combining > prev_combining:
                prev_combining = next_combining

        result[starter_pos] = current

        return space.wrap(u''.join([unichr(i) for i in result[:next_insert]]))


methods = {}
for methodname in """
        _get_code lookup name decimal digit numeric category east_asian_width
        bidirectional combining mirrored decomposition normalize
        """.split():
    methods[methodname] = interp2app(getattr(UCD, methodname))


UCD.typedef = TypeDef("unicodedata.UCD",
                      __doc__ = "",
                      unidata_version = interp_attrproperty('version', UCD),
                      **methods)

ucd_3_2_0 = UCD(unicodedb_3_2_0)
ucd_5_2_0 = UCD(unicodedb_5_2_0)
ucd = ucd_5_2_0
Beispiel #56
0
        if sig == llapi.HPyFunc_VARARGS:
            return self.call_varargs_kw(space,
                                        h_self,
                                        __args__,
                                        skip_args,
                                        has_keywords=False)
        else:  # shouldn't happen!
            raise oefmt(space.w_RuntimeError, "unknown calling convention")


W_ExtensionFunction.typedef = TypeDef(
    'extension_function',
    __call__=interp2app(W_ExtensionFunction.descr_call),
    __doc__=interp_attrproperty('doc',
                                cls=W_ExtensionFunction,
                                wrapfn="newtext_or_none"),
)
W_ExtensionFunction.typedef.acceptable_as_base_class = False


class W_ExtensionMethod(W_ExtensionFunction):
    def __init__(self, space, name, sig, doc, cfuncptr, w_objclass):
        W_ExtensionFunction.__init__(self, space, name, sig, doc, cfuncptr,
                                     space.w_None)
        self.w_objclass = w_objclass

    def descr_call(self, space, __args__):
        # XXX: basically a copy of cpyext's W_PyCMethodObject.descr_call()
        if len(__args__.arguments_w) == 0:
            w_objclass = self.w_objclass
Beispiel #57
0
def _get_escapechar(space, dialect):
    if dialect.escapechar == '\0':
        return space.w_None
    return space.newtext(dialect.escapechar)

def _get_quotechar(space, dialect):
    if dialect.quotechar == '\0':
        return space.w_None
    return space.newtext(dialect.quotechar)


W_Dialect.typedef = TypeDef(
        '_csv.Dialect',
        __new__ = interp2app(W_Dialect___new__),

        delimiter        = interp_attrproperty('delimiter', W_Dialect,
            wrapfn='newtext'),
        doublequote      = interp_attrproperty('doublequote', W_Dialect,
            wrapfn='newbool'),
        escapechar       = GetSetProperty(_get_escapechar, cls=W_Dialect),
        lineterminator   = interp_attrproperty('lineterminator', W_Dialect,
            wrapfn='newtext'),
        quotechar        = GetSetProperty(_get_quotechar, cls=W_Dialect),
        quoting          = interp_attrproperty('quoting', W_Dialect,
            wrapfn='newint'),
        skipinitialspace = interp_attrproperty('skipinitialspace', W_Dialect,
            wrapfn='newbool'),
        strict           = interp_attrproperty('strict', W_Dialect,
            wrapfn='newbool'),

        __doc__ = """CSV dialect
Beispiel #58
0
        return space.wrap(subdialect)


def _get_escapechar(space, dialect):
    if dialect.escapechar == '\0':
        return space.w_None
    return space.wrap(dialect.escapechar)


def _get_quotechar(space, dialect):
    if dialect.quotechar == '\0':
        return space.w_None
    return space.wrap(dialect.quotechar)


W_Dialect.typedef = TypeDef(
    '_csv.Dialect',
    __new__=interp2app(W_Dialect___new__),
    delimiter=interp_attrproperty('delimiter', W_Dialect),
    doublequote=interp_attrproperty('doublequote', W_Dialect),
    escapechar=GetSetProperty(_get_escapechar, cls=W_Dialect),
    lineterminator=interp_attrproperty('lineterminator', W_Dialect),
    quotechar=GetSetProperty(_get_quotechar, cls=W_Dialect),
    quoting=interp_attrproperty('quoting', W_Dialect),
    skipinitialspace=interp_attrproperty('skipinitialspace', W_Dialect),
    strict=interp_attrproperty('strict', W_Dialect),
    __doc__="""CSV dialect

The Dialect type records CSV parsing and generation options.
""")
Beispiel #59
0
            fmin = -(r_longlong(1) << (self.bitsize - 1))
            fmax = (r_longlong(1) << (self.bitsize - 1)) - 1
            if fmax == 0:
                fmax = 1      # special case to let "int x:1" receive "1"
        else:
            is_signed = False
            fmin = r_longlong(0)
            fmax = r_longlong((r_ulonglong(1) << self.bitsize) - 1)
        if value < fmin or value > fmax:
            raise oefmt(space.w_OverflowError,
                        "value %d outside the range allowed by the bit field "
                        "width: %d <= x <= %d", value, fmin, fmax)
        rawmask = ((r_ulonglong(1) << self.bitsize) - 1) << self.bitshift
        rawvalue = r_ulonglong(value) << self.bitshift
        rawfielddata = misc.read_raw_unsigned_data(cdata, ctype.size)
        rawfielddata = (rawfielddata & ~rawmask) | (rawvalue & rawmask)
        if is_signed:
            misc.write_raw_signed_data(cdata, rawfielddata, ctype.size)
        else:
            misc.write_raw_unsigned_data(cdata, rawfielddata, ctype.size)


W_CField.typedef = TypeDef(
    '_cffi_backend.CField',
    type = interp_attrproperty('ctype', W_CField),
    offset = interp_attrproperty('offset', W_CField),
    bitshift = interp_attrproperty('bitshift', W_CField),
    bitsize = interp_attrproperty('bitsize', W_CField),
    )
W_CField.typedef.acceptable_as_base_class = False