コード例 #1
0
ファイル: intobject.py プロジェクト: purepython/pypy
    int_w = unwrap

    def uint_w(w_self, space):
        intval = w_self.intval
        if intval < 0:
            raise OperationError(
                space.w_ValueError,
                space.wrap("cannot convert negative integer to unsigned"))
        else:
            return r_uint(intval)

    def bigint_w(w_self, space):
        return rbigint.fromint(w_self.intval)


registerimplementation(W_IntObject)

# NB: This code is shared by smallintobject.py, and thus no other Int
# multimethods should be invoked from these implementations. Instead, add an
# alias and then teach copy_multimethods in smallintobject.py to override
# it. See int__Int for example.


def repr__Int(space, w_int1):
    a = w_int1.intval
    res = str(a)
    return space.wrap(res)


str__Int = repr__Int
コード例 #2
0
ファイル: tupleobject.py プロジェクト: ieure/pypy
    _immutable_fields_ = ['wrappeditems[*]']

    def __init__(w_self, wrappeditems):
        make_sure_not_resized(wrappeditems)
        w_self.wrappeditems = wrappeditems   # a list of wrapped values

    def __repr__(w_self):
        """ representation for debugging purposes """
        reprlist = [repr(w_item) for w_item in w_self.wrappeditems]
        return "%s(%s)" % (w_self.__class__.__name__, ', '.join(reprlist))

    def unwrap(w_tuple, space):
        items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems]
        return tuple(items)

registerimplementation(W_TupleObject)


def len__Tuple(space, w_tuple):
    result = len(w_tuple.wrappeditems)
    return wrapint(space, result)

def getitem__Tuple_ANY(space, w_tuple, w_index):
    # getindex_w should get a second argument space.w_IndexError,
    # but that doesn't exist the first time this is called.
    try:
        w_IndexError = space.w_IndexError
    except AttributeError:
        w_IndexError = None
    index = space.getindex_w(w_index, w_IndexError, "tuple index")
    try:
コード例 #3
0
ファイル: bytearrayobject.py プロジェクト: ieure/pypy
    new_bytearray
)
from pypy.tool.sourcetools import func_with_new_name


class W_BytearrayObject(W_Object):
    from pypy.objspace.std.bytearraytype import bytearray_typedef as typedef

    def __init__(w_self, data):
        w_self.data = data

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%s)" % (w_self.__class__.__name__, ''.join(w_self.data))

registerimplementation(W_BytearrayObject)

init_signature = Signature(['source', 'encoding', 'errors'], None, None)
init_defaults = [None, None, None]

def init__Bytearray(space, w_bytearray, __args__):
    # this is on the silly side
    w_source, w_encoding, w_errors = __args__.parse_obj(
            None, 'bytearray', init_signature, init_defaults)

    if w_source is None:
        w_source = space.wrap('')
    if w_encoding is None:
        w_encoding = space.w_None
    if w_errors is None:
        w_errors = space.w_None
コード例 #4
0
from pypy.interpreter.mixedmodule import MixedModule
from pypy.module.array.interp_array import types, W_ArrayBase
from pypy.objspace.std.model import registerimplementation

for mytype in types.values():
    registerimplementation(mytype.w_class)


class Module(MixedModule):

    interpleveldefs = {
        'array': 'interp_array.W_ArrayBase',
        'ArrayType': 'interp_array.W_ArrayBase',
    }

    appleveldefs = {}
コード例 #5
0
ファイル: listobject.py プロジェクト: gorakhargosh/pypy
    def __init__(w_self, wrappeditems):
        w_self.wrappeditems = wrappeditems

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%s)" % (w_self.__class__.__name__, w_self.wrappeditems)

    def unwrap(w_list, space):
        items = [space.unwrap(w_item) for w_item in w_list.wrappeditems]# XXX generic mixed types unwrap
        return list(items)

    def append(w_list, w_item):
        w_list.wrappeditems.append(w_item)

registerimplementation(W_ListObject)


init_signature = Signature(['sequence'], None, None)
init_defaults = [None]

def init__List(space, w_list, __args__):
    from pypy.objspace.std.tupleobject import W_TupleObject
    # this is on the silly side
    w_iterable, = __args__.parse_obj(
            None, 'list', init_signature, init_defaults)
    items_w = w_list.wrappeditems
    del items_w[:]
    if w_iterable is not None:
        # unfortunately this is duplicating space.unpackiterable to avoid
        # assigning a new RPython list to 'wrappeditems', which defeats the
コード例 #6
0
        str = w_self.str[w_self.start:w_self.stop]
        w_self.str = str
        w_self.start = 0
        w_self.stop = len(str)
        return str

    def str_w(w_self, space):
        return w_self.force()

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%r[%d:%d])" % (w_self.__class__.__name__, w_self.str,
                                  w_self.start, w_self.stop)


registerimplementation(W_StringSliceObject)


def delegate_slice2str(space, w_strslice):
    return wrapstr(space, w_strslice.force())


def delegate_slice2unicode(space, w_strslice):
    w_str = wrapstr(space, w_strslice.force())
    return delegate_String2Unicode(space, w_str)


# ____________________________________________________________


def contains__StringSlice_String(space, w_self, w_sub):
コード例 #7
0
ファイル: longobject.py プロジェクト: Debug-Orz/Sypy
    def bigint_w(w_self, space):
        return w_self.num

    def __repr__(self):
        return '<W_LongObject(%d)>' % self.num.tolong()

    def is_symbolic(self):
        if isinstance(self.__is_symbolic, bool):
            return self.__is_symbolic
        return self.__is_symbolic.boolval

    def set_symbolic(w_self, s):
        w_self.__is_symbolic = s


registerimplementation(W_LongObject)

def newlong(space, bigint, w_symbolic=False):
    """Turn the bigint into a W_LongObject.  If withsmalllong is enabled,
    check if the bigint would fit in a smalllong, and return a
    W_SmallLongObject instead if it does.
    """
    if space.config.objspace.std.withsmalllong:
        try:
            z = bigint.tolonglong()
        except OverflowError:
            pass
        else:
            from pypy.objspace.std.smalllongobject import W_SmallLongObject
            return W_SmallLongObject(z, w_symbolic)
    return W_LongObject(bigint, w_symbolic)
コード例 #8
0
        else:
            return w_one.div(self.pow_positive_int(-n))

    def pow_positive_int(self, n):
        mask = 1
        w_result = w_one
        while mask > 0 and n >= mask:
            if n & mask:
                w_result = w_result.mul(self)
            mask <<= 1
            self = self.mul(self)

        return w_result


registerimplementation(W_ComplexObject)

w_one = W_ComplexObject(1, 0)


def delegate_Bool2Complex(space, w_bool):
    return W_ComplexObject(w_bool.boolval, 0.0)


def delegate_Int2Complex(space, w_int):
    return W_ComplexObject(w_int.intval, 0.0)


def delegate_Long2Complex(space, w_long):
    try:
        dval = w_long.tofloat()
コード例 #9
0
ファイル: rangeobject.py プロジェクト: gorakhargosh/pypy
        except OperationError, e:
            w_rangeiter.w_seq = None
            if not e.match(space, space.w_IndexError):
                raise
            raise OperationError(space.w_StopIteration, space.w_None)
    else:
        if index >= w_rangelist.length:
            w_rangeiter.w_seq = None
            raise OperationError(space.w_StopIteration, space.w_None)
        w_item = wrapint(
            space,
            w_rangelist.getitem_unchecked(index))
    w_rangeiter.index = index + 1
    return w_item

# XXX __length_hint__()
##def len__RangeIter(space,  w_rangeiter):
##    if w_rangeiter.w_seq is None:
##        return wrapint(space, 0)
##    index = w_rangeiter.index
##    w_length = space.len(w_rangeiter.w_seq)
##    w_len = space.sub(w_length, wrapint(space, index))
##    if space.is_true(space.lt(w_len, wrapint(space, 0))):
##        w_len = wrapint(space, 0)
##    return w_len

registerimplementation(W_RangeListObject)
registerimplementation(W_RangeIterObject)

register_all(vars(), listtype)
コード例 #10
0
ファイル: iterobject.py プロジェクト: purepython/pypy
   """
    def __init__(w_self, w_seq, wrappeditems):
        W_AbstractSeqIterObject.__init__(w_self, w_seq)
        w_self.tupleitems = wrappeditems


class W_ReverseSeqIterObject(W_Object):
    from pypy.objspace.std.itertype import reverse_iter_typedef as typedef

    def __init__(w_self, space, w_seq, index=-1):
        w_self.w_seq = w_seq
        w_self.w_len = space.len(w_seq)
        w_self.index = space.int_w(w_self.w_len) + index


registerimplementation(W_SeqIterObject)
registerimplementation(W_FastListIterObject)
registerimplementation(W_FastTupleIterObject)
registerimplementation(W_ReverseSeqIterObject)


def iter__SeqIter(space, w_seqiter):
    return w_seqiter


def next__SeqIter(space, w_seqiter):
    if w_seqiter.w_seq is None:
        raise OperationError(space.w_StopIteration, space.w_None)
    try:
        w_item = space.getitem(w_seqiter.w_seq, space.wrap(w_seqiter.index))
    except OperationError, e:
コード例 #11
0
ファイル: strjoinobject.py プロジェクト: njues/Sypy
        w_self.joined_strs = [res]
        w_self.until = 1
        return res

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%r, %r)" % (w_self.__class__.__name__, w_self.joined_strs,
                               w_self.until)

    def unwrap(w_self, space):
        return w_self.force()

    str_w = unwrap


registerimplementation(W_StringJoinObject)


def delegate_join2str(space, w_strjoin):
    return wrapstr(space, w_strjoin.force())


def delegate_join2unicode(space, w_strjoin):
    w_str = wrapstr(space, w_strjoin.force())
    return delegate_String2Unicode(space, w_str)


def len__StringJoin(space, w_self):
    result = 0
    for i in range(w_self.until):
        result += len(w_self.joined_strs[i])
コード例 #12
0
ファイル: smallintobject.py プロジェクト: njues/Sypy
    int_w = unwrap

    def uint_w(w_self, space):
        intval = w_self.intval
        if intval < 0:
            raise OperationError(
                space.w_ValueError,
                space.wrap("cannot convert negative integer to unsigned"))
        else:
            return r_uint(intval)

    def bigint_w(w_self, space):
        return rbigint.fromint(w_self.intval)


registerimplementation(W_SmallIntObject)


def delegate_SmallInt2Int(space, w_small):
    return W_IntObject(w_small.intval)


def delegate_SmallInt2Long(space, w_small):
    return space.newlong(w_small.intval)


def delegate_SmallInt2Float(space, w_small):
    return space.newfloat(float(w_small.intval))


def delegate_SmallInt2Complex(space, w_small):
コード例 #13
0
ファイル: ropeobject.py プロジェクト: gorakhargosh/pypy
        if type(w_self) is W_RopeObject:
            return w_self
        return W_RopeObject(w_self._node)

W_RopeObject.EMPTY = W_RopeObject(rope.LiteralStringNode.EMPTY)
W_RopeObject.PREBUILT = [W_RopeObject(rope.LiteralStringNode.PREBUILT[i])
                             for i in range(256)]
del i


def rope_w(space, w_str):
    if isinstance(w_str, W_RopeObject):
        return w_str._node
    return rope.LiteralStringNode(space.str_w(w_str))

registerimplementation(W_RopeObject)

class W_RopeIterObject(W_Object):
    from pypy.objspace.std.itertype import iter_typedef as typedef

    def __init__(w_self, w_rope, index=0):
        w_self.node = node = w_rope._node
        w_self.item_iter = rope.ItemIterator(node)
        w_self.index = index

registerimplementation(W_RopeIterObject)

def _is_generic(space, w_self, fun):
    l = w_self._node.length()
    if l == 0:
        return space.w_False
コード例 #14
0
        else:
            return self.w_str._value

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%r[:%d])" % (w_self.__class__.__name__, w_self.builder,
                                w_self.length)

    def unwrap(self, space):
        return self.force()

    def str_w(self, space):
        return self.force()


registerimplementation(W_StringBufferObject)

# ____________________________________________________________


def joined2(str1, str2):
    builder = StringBuilder()
    builder.append(str1)
    builder.append(str2)
    return W_StringBufferObject(builder)


# ____________________________________________________________


def delegate_buf2str(space, w_strbuf):
コード例 #15
0
ファイル: unicodeobject.py プロジェクト: nipengadmaster/pypy
        return w_self._value

    def create_if_subclassed(w_self):
        if type(w_self) is W_UnicodeObject:
            return w_self
        return W_UnicodeObject(w_self._value)

    def str_w(self, space):
        return space.str_w(space.str(self))

    def unicode_w(self, space):
        return self._value

W_UnicodeObject.EMPTY = W_UnicodeObject(u'')

registerimplementation(W_UnicodeObject)

# Helper for converting int/long
def unicode_to_decimal_w(space, w_unistr):
    if not isinstance(w_unistr, W_UnicodeObject):
        raise operationerrfmt(space.w_TypeError,
                              "expected unicode, got '%s'",
                              space.type(w_unistr).getname(space))
    unistr = w_unistr._value
    result = ['\0'] * len(unistr)
    digits = [ '0', '1', '2', '3', '4',
               '5', '6', '7', '8', '9']
    for i in xrange(len(unistr)):
        uchr = ord(unistr[i])
        if unicodedb.isspace(uchr):
            result[i] = ' '
コード例 #16
0
        # XXX should this use the default encoding?
        from pypy.objspace.std.unicodetype import plain_str2unicode
        return plain_str2unicode(space, w_self._node.flatten_string())

W_RopeObject.EMPTY = W_RopeObject(rope.LiteralStringNode.EMPTY)
W_RopeObject.PREBUILT = [W_RopeObject(rope.LiteralStringNode.PREBUILT[i])
                             for i in range(256)]
del i


def rope_w(space, w_str):
    if isinstance(w_str, W_RopeObject):
        return w_str._node
    return rope.LiteralStringNode(space.str_w(w_str))

registerimplementation(W_RopeObject)

class W_RopeIterObject(iterobject.W_AbstractIterObject):
    from pypy.objspace.std.itertype import iter_typedef as typedef

    def __init__(w_self, w_rope, index=0):
        w_self.node = node = w_rope._node
        w_self.item_iter = rope.ItemIterator(node)
        w_self.index = index

registerimplementation(W_RopeIterObject)

def _is_generic(space, w_self, fun):
    l = w_self._node.length()
    if l == 0:
        return space.w_False
コード例 #17
0
ファイル: longobject.py プロジェクト: njues/Sypy
    def bigint_w(w_self, space):
        return w_self.num

    def __repr__(self):
        return '<W_LongObject(%d)>' % self.num.tolong()

    def is_symbolic(self):
        if isinstance(self.__is_symbolic, bool):
            return self.__is_symbolic
        return self.__is_symbolic.boolval

    def set_symbolic(w_self, s):
        w_self.__is_symbolic = s


registerimplementation(W_LongObject)


def newlong(space, bigint, w_symbolic=False):
    """Turn the bigint into a W_LongObject.  If withsmalllong is enabled,
    check if the bigint would fit in a smalllong, and return a
    W_SmallLongObject instead if it does.
    """
    if space.config.objspace.std.withsmalllong:
        try:
            z = bigint.tolonglong()
        except OverflowError:
            pass
        else:
            from pypy.objspace.std.smalllongobject import W_SmallLongObject
            return W_SmallLongObject(z, w_symbolic)
コード例 #18
0
    """This is a implementation of the app-level 'float' type.
    The constructor takes an RPython float as an argument."""
    from pypy.objspace.std.floattype import float_typedef as typedef
    _immutable_fields_ = ['floatval']

    def __init__(w_self, floatval):
        w_self.floatval = floatval

    def unwrap(w_self, space):
        return w_self.floatval

    def __repr__(self):
        return "<W_FloatObject(%f)>" % self.floatval


registerimplementation(W_FloatObject)


# bool-to-float delegation
def delegate_Bool2Float(space, w_bool):
    return W_FloatObject(float(w_bool.boolval))


# int-to-float delegation
def delegate_Int2Float(space, w_intobj):
    return W_FloatObject(float(w_intobj.intval))


# long-to-float delegation
def delegate_Long2Float(space, w_longobj):
    try:
コード例 #19
0
    def unwrap(w_self, space):
        return int(w_self.intval)
    int_w = unwrap

    def uint_w(w_self, space):
        intval = w_self.intval
        if intval < 0:
            raise OperationError(space.w_ValueError,
                                 space.wrap("cannot convert negative integer to unsigned"))
        else:
            return r_uint(intval)

    def bigint_w(w_self, space):
        return rbigint.fromint(w_self.intval)

registerimplementation(W_IntObject)

# NB: This code is shared by smallintobject.py, and thus no other Int
# multimethods should be invoked from these implementations. Instead, add an
# alias and then teach copy_multimethods in smallintobject.py to override
# it. See int__Int for example.

def repr__Int(space, w_int1):
    a = w_int1.intval
    res = str(a)
    return space.wrap(res)

str__Int = repr__Int

def format__Int_ANY(space, w_int, w_format_spec):
    return newformat.run_formatter(space, w_format_spec, "format_int_or_long",
コード例 #20
0
ファイル: __init__.py プロジェクト: Debug-Orz/Sypy
from pypy.interpreter.mixedmodule import MixedModule
from pypy.module.array.interp_array import types, W_ArrayBase
from pypy.objspace.std.model import registerimplementation

for mytype in types.values():
    registerimplementation(mytype.w_class)


class Module(MixedModule):

    interpleveldefs = {
        'array': 'interp_array.W_ArrayBase',
        'ArrayType': 'interp_array.W_ArrayBase',
    }

    appleveldefs = {
    }
コード例 #21
0
ファイル: complexobject.py プロジェクト: craigkerstiens/pypy
            return self.pow_positive_int(n)
        else:
            return w_one.div(self.pow_positive_int(-n))

    def pow_positive_int(self, n):
        mask = 1
        w_result = w_one
        while mask > 0 and n >= mask:
            if n & mask:
                w_result = w_result.mul(self)
            mask <<= 1
            self = self.mul(self)

        return w_result

registerimplementation(W_ComplexObject)

w_one = W_ComplexObject(1, 0)


def delegate_Bool2Complex(space, w_bool):
    return W_ComplexObject(w_bool.boolval, 0.0)

def delegate_Int2Complex(space, w_int):
    return W_ComplexObject(w_int.intval, 0.0)

def delegate_Long2Complex(space, w_long):
    try:
        dval =  w_long.tofloat()
    except OverflowError, e:
        raise OperationError(space.w_OverflowError, space.wrap(str(e)))
コード例 #22
0
ファイル: specialisedtupleobject.py プロジェクト: njues/Sypy
        #else:
        #    if w_type2 is space.w_int:
        #        return Cls_oi(space, w_arg1, w_arg2)
        #    elif w_type2 is space.w_str:
        #        return Cls_os(space, w_arg1, w_arg2)
        #    else:
        return Cls_oo(space, w_arg1, w_arg2)
        #
    #elif len(list_w) == 3:
    #    return Cls_ooo(space, list_w[0], list_w[1], list_w[2])
    else:
        raise NotSpecialised

# ____________________________________________________________

registerimplementation(W_SpecialisedTupleObject)

def delegate_SpecialisedTuple2Tuple(space, w_specialised):
    w_specialised.delegating()
    return W_TupleObject(w_specialised.tolist())

def len__SpecialisedTuple(space, w_tuple):
    return space.wrap(w_tuple.length())

def getitem__SpecialisedTuple_ANY(space, w_tuple, w_index):
    index = space.getindex_w(w_index, space.w_IndexError, "tuple index")
    if index < 0:
        index += w_tuple.length()
    try:
        return w_tuple.getitem(index)
    except IndexError:
コード例 #23
0
ファイル: strjoinobject.py プロジェクト: Debug-Orz/Sypy
            return w_self.joined_strs[0]
        res = "".join(w_self.joined_strs[:w_self.until])
        w_self.joined_strs = [res]
        w_self.until = 1
        return res

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%r, %r)" % (
            w_self.__class__.__name__, w_self.joined_strs, w_self.until)

    def unwrap(w_self, space):
        return w_self.force()
    str_w = unwrap

registerimplementation(W_StringJoinObject)

def delegate_join2str(space, w_strjoin):
    return wrapstr(space, w_strjoin.force())

def delegate_join2unicode(space, w_strjoin):
    w_str = wrapstr(space, w_strjoin.force())
    return delegate_String2Unicode(space, w_str)

def len__StringJoin(space, w_self):
    result = 0
    for i in range(w_self.until):
        result += len(w_self.joined_strs[i])
    return space.wrap(result)

def add__StringJoin_StringJoin(space, w_self, w_other):
コード例 #24
0
    def length(self, w_dict):
        return 0

    def iter(self, w_dict):
        return EmptyIteratorImplementation(self.space, self, w_dict)

    def clear(self, w_dict):
        return

    def popitem(self, w_dict):
        raise KeyError

    def view_as_kwargs(self, w_dict):
        return ([], [])

registerimplementation(W_DictMultiObject)

# DictImplementation lattice
# XXX fix me

# Iterator Implementation base classes

class IteratorImplementation(object):
    def __init__(self, space, strategy, implementation):
        self.space = space
        self.strategy = strategy
        self.dictimplementation = implementation
        self.len = implementation.length()
        self.pos = 0

    def next(self):
コード例 #25
0
ファイル: smalllongobject.py プロジェクト: njues/Sypy
    def bigint_w(w_self, space):
        return w_self.asbigint()

    def is_symbolic(w_self):
        # Int values are non symbolic, should be a cleaner way #HACK
        if isinstance(w_self.__is_symbolic, W_SmallLongObject):
            return False
        elif isinstance(w_self.__is_symbolic, bool):
            return w_self.__is_symbolic
        return w_self.__is_symbolic.boolval

    def set_symbolic(w_self, s):
        w_self.__is_symbolic = s


registerimplementation(W_SmallLongObject)

# ____________________________________________________________


def llong_mul_ovf(a, b):
    # xxx duplication of the logic from translator/c/src/int.h
    longprod = a * b
    doubleprod = float(a) * float(b)
    doubled_longprod = float(longprod)

    # Fast path for normal case:  small multiplicands, and no info
    # is lost in either method.
    if doubled_longprod == doubleprod:
        return longprod
コード例 #26
0
    def unwrap(w_self, space):
        return w_self.boolval

    def int_w(w_self, space):
        return int(w_self.boolval)

    def uint_w(w_self, space):
        intval = int(w_self.boolval)
        return r_uint(intval)

    def bigint_w(w_self, space):
        return rbigint.fromint(int(w_self.boolval))


registerimplementation(W_BoolObject)

W_BoolObject.w_False = W_BoolObject(False)
W_BoolObject.w_True  = W_BoolObject(True)

# bool-to-int delegation requires translating the .boolvar attribute
# to an .intval one
def delegate_Bool2IntObject(space, w_bool):
    return W_IntObject(int(w_bool.boolval))

def delegate_Bool2SmallInt(space, w_bool):
    from pypy.objspace.std.smallintobject import W_SmallIntObject
    return W_SmallIntObject(int(w_bool.boolval))   # cannot overflow


def nonzero__Bool(space, w_bool):
コード例 #27
0
ファイル: floatobject.py プロジェクト: craigkerstiens/pypy
class W_FloatObject(W_AbstractFloatObject):
    """This is a implementation of the app-level 'float' type.
    The constructor takes an RPython float as an argument."""
    from pypy.objspace.std.floattype import float_typedef as typedef
    _immutable_fields_ = ['floatval']

    def __init__(w_self, floatval):
        w_self.floatval = floatval

    def unwrap(w_self, space):
        return w_self.floatval

    def __repr__(self):
        return "<W_FloatObject(%f)>" % self.floatval

registerimplementation(W_FloatObject)

# bool-to-float delegation
def delegate_Bool2Float(space, w_bool):
    return W_FloatObject(float(w_bool.boolval))

# int-to-float delegation
def delegate_Int2Float(space, w_intobj):
    return W_FloatObject(float(w_intobj.intval))

# long-to-float delegation
def delegate_Long2Float(space, w_longobj):
    try:
        return W_FloatObject(w_longobj.tofloat())
    except OverflowError:
        raise OperationError(space.w_OverflowError,
コード例 #28
0
        str = w_self.str[w_self.start:w_self.stop]
        w_self.str = str
        w_self.start = 0
        w_self.stop = len(str)
        return str

    def str_w(w_self, space):
        return w_self.force()

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%r[%d:%d])" % (w_self.__class__.__name__,
                                  w_self.str, w_self.start, w_self.stop)


registerimplementation(W_StringSliceObject)


def delegate_slice2str(space, w_strslice):
    return wrapstr(space, w_strslice.force())

def delegate_slice2unicode(space, w_strslice):
    w_str = wrapstr(space, w_strslice.force())
    return delegate_String2Unicode(space, w_str)

# ____________________________________________________________

def contains__StringSlice_String(space, w_self, w_sub):
    sub = w_sub._value
    return space.newbool(w_self.str.find(sub, w_self.start, w_self.stop) >= 0)
コード例 #29
0
ファイル: proxyobject.py プロジェクト: njues/Sypy
    typedef = PyTraceback.typedef


class W_TransparentCode(W_Transparent):
    typedef = PyCode.typedef


class W_TransparentFrame(W_Transparent):
    typedef = PyFrame.typedef


class W_TransparentGenerator(W_Transparent):
    typedef = GeneratorIterator.typedef


class W_TransparentList(W_TransparentObject):
    from pypy.objspace.std.listobject import W_ListObject as original
    from pypy.objspace.std.listtype import list_typedef as typedef


class W_TransparentDict(W_TransparentObject):
    from pypy.objspace.std.dictmultiobject import W_DictMultiObject as original
    from pypy.objspace.std.dicttype import dict_typedef as typedef


registerimplementation(W_TransparentList)
registerimplementation(W_TransparentDict)

register_type(W_TransparentList)
register_type(W_TransparentDict)
コード例 #30
0
                                             new_bytearray)
from pypy.tool.sourcetools import func_with_new_name


class W_BytearrayObject(W_Object):
    from pypy.objspace.std.bytearraytype import bytearray_typedef as typedef

    def __init__(w_self, data):
        w_self.data = data

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%s)" % (w_self.__class__.__name__, ''.join(w_self.data))


registerimplementation(W_BytearrayObject)

init_signature = Signature(['source', 'encoding', 'errors'], None, None)
init_defaults = [None, None, None]


def init__Bytearray(space, w_bytearray, __args__):
    # this is on the silly side
    w_source, w_encoding, w_errors = __args__.parse_obj(
        None, 'bytearray', init_signature, init_defaults)

    if w_source is None:
        w_source = space.wrap('')
    if w_encoding is None:
        w_encoding = space.w_None
    if w_errors is None:
コード例 #31
0
        return w_obj

class W_FrozensetObject(W_BaseSetObject):
    from pypy.objspace.std.frozensettype import frozenset_typedef as typedef
    hash = 0

    def _newobj(w_self, space, rdict_w):
        """Make a new frozenset by taking ownership of 'rdict_w'."""
        if type(w_self) is W_FrozensetObject:
            return W_FrozensetObject(space, rdict_w)
        w_type = space.type(w_self)
        w_obj = space.allocate_instance(W_FrozensetObject, w_type)
        W_FrozensetObject.__init__(w_obj, space, rdict_w)
        return w_obj

registerimplementation(W_BaseSetObject)
registerimplementation(W_SetObject)
registerimplementation(W_FrozensetObject)

class W_SetIterObject(W_Object):
    from pypy.objspace.std.settype import setiter_typedef as typedef

    def __init__(w_self, setdata):
        w_self.content = content = setdata
        w_self.len = len(content)
        w_self.pos = 0
        w_self.iterator = w_self.content.iterkeys()

    def next_entry(w_self):
        for w_key in w_self.iterator:
            return w_key
コード例 #32
0
ファイル: smallintobject.py プロジェクト: Debug-Orz/Sypy
        return int(w_self.intval)
    int_w = unwrap

    def uint_w(w_self, space):
        intval = w_self.intval
        if intval < 0:
            raise OperationError(space.w_ValueError,
                                 space.wrap("cannot convert negative integer to unsigned"))
        else:
            return r_uint(intval)

    def bigint_w(w_self, space):
        return rbigint.fromint(w_self.intval)


registerimplementation(W_SmallIntObject)


def delegate_SmallInt2Int(space, w_small):
    return W_IntObject(w_small.intval)

def delegate_SmallInt2Long(space, w_small):
    return space.newlong(w_small.intval)

def delegate_SmallInt2Float(space, w_small):
    return space.newfloat(float(w_small.intval))

def delegate_SmallInt2Complex(space, w_small):
    return space.newcomplex(float(w_small.intval), 0.0)

def add__SmallInt_SmallInt(space, w_a, w_b):
コード例 #33
0
        self.space.hash(w_key)
        raise KeyError

    def length(self, w_dict):
        return 0

    def iter(self, w_dict):
        return EmptyIteratorImplementation(self.space, w_dict)

    def clear(self, w_dict):
        return

    def popitem(self, w_dict):
        raise KeyError

registerimplementation(W_DictMultiObject)

# DictImplementation lattice
# XXX fix me

# Iterator Implementation base classes

class IteratorImplementation(object):
    def __init__(self, space, implementation):
        self.space = space
        self.dictimplementation = implementation
        self.len = implementation.length()
        self.pos = 0

    def next(self):
        if self.dictimplementation is None:
コード例 #34
0
ファイル: proxyobject.py プロジェクト: ieure/pypy
    PyFrame, PyCode

class W_TransparentFunction(W_Transparent):
    typedef = Function.typedef

class W_TransparentTraceback(W_Transparent):
    typedef = PyTraceback.typedef

class W_TransparentCode(W_Transparent):
    typedef = PyCode.typedef

class W_TransparentFrame(W_Transparent):
    typedef = PyFrame.typedef

class W_TransparentGenerator(W_Transparent):
    typedef = GeneratorIterator.typedef

class W_TransparentList(W_TransparentObject):
    from pypy.objspace.std.listobject import W_ListObject as original
    from pypy.objspace.std.listtype import list_typedef as typedef

class W_TransparentDict(W_TransparentObject):
    from pypy.objspace.std.dictmultiobject import W_DictMultiObject as original
    from pypy.objspace.std.dicttype import dict_typedef as typedef

registerimplementation(W_TransparentList)
registerimplementation(W_TransparentDict)

register_type(W_TransparentList)
register_type(W_TransparentDict)
コード例 #35
0
class W_FrozensetObject(W_BaseSetObject):
    from pypy.objspace.std.frozensettype import frozenset_typedef as typedef
    hash = 0

    def _newobj(w_self, space, w_iterable):
        """Make a new frozenset by taking ownership of 'w_iterable'."""
        if type(w_self) is W_FrozensetObject:
            return W_FrozensetObject(space, w_iterable)
        w_type = space.type(w_self)
        w_obj = space.allocate_instance(W_FrozensetObject, w_type)
        W_FrozensetObject.__init__(w_obj, space, w_iterable)
        return w_obj


registerimplementation(W_BaseSetObject)
registerimplementation(W_SetObject)
registerimplementation(W_FrozensetObject)


class SetStrategy(object):
    def __init__(self, space):
        self.space = space

    def get_empty_dict(self):
        """ Returns an empty dictionary depending on the strategy. Used to initalize a new storage. """
        raise NotImplementedError

    def get_empty_storage(self):
        """ Returns an empty storage (erased) object. Used to initialize an empty set."""
        raise NotImplementedError
コード例 #36
0
ファイル: smalltupleobject.py プロジェクト: sota/pypy-old
                mult += 82520 + z + z
            x += 97531
            return space.wrap(intmask(x))

    cls.__name__ = "W_SmallTupleObject%s" % n
    return cls

W_SmallTupleObject2 = make_specialized_class(2)
W_SmallTupleObject3 = make_specialized_class(3)
W_SmallTupleObject4 = make_specialized_class(4)
W_SmallTupleObject5 = make_specialized_class(5)
W_SmallTupleObject6 = make_specialized_class(6)
W_SmallTupleObject7 = make_specialized_class(7)
W_SmallTupleObject8 = make_specialized_class(8)

registerimplementation(W_SmallTupleObject)

def delegate_SmallTuple2Tuple(space, w_small):
    return W_TupleObject(w_small.tolist())

def len__SmallTuple(space, w_tuple):
    return space.wrap(w_tuple.length())

def getitem__SmallTuple_ANY(space, w_tuple, w_index):
    index = space.getindex_w(w_index, space.w_IndexError, "tuple index")
    if index < 0:
        index += w_tuple.length()
    try:
        return w_tuple.getitem(index)
    except IndexError:
        raise OperationError(space.w_IndexError,
コード例 #37
0
ファイル: noneobject.py プロジェクト: Debug-Orz/Sypy
"""
  None Object implementation

  ok and tested
"""

from pypy.objspace.std.model import registerimplementation, W_Object
from pypy.objspace.std.register_all import register_all

class W_NoneObject(W_Object):
    from pypy.objspace.std.nonetype import none_typedef as typedef

    def unwrap(w_self, space):
        return None

registerimplementation(W_NoneObject)

W_NoneObject.w_None = W_NoneObject()

def nonzero__None(space, w_none):
    return space.w_False

def repr__None(space, w_none):
    return space.wrap('None')

register_all(vars())

コード例 #38
0
        """ representation for debugging purposes """
        reprlist = [repr(w_item) for w_item in w_self.wrappeditems]
        return "%s(%s)" % (w_self.__class__.__name__, ', '.join(reprlist))

    def unwrap(w_tuple, space):
        items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems]
        return tuple(items)

    def tolist(self):
        return self.wrappeditems

    def getitems_copy(self):
        return self.wrappeditems[:]  # returns a resizable list


registerimplementation(W_TupleObject)


def len__Tuple(space, w_tuple):
    result = len(w_tuple.wrappeditems)
    return wrapint(space, result)


def getitem__Tuple_ANY(space, w_tuple, w_index):
    # getindex_w should get a second argument space.w_IndexError,
    # but that doesn't exist the first time this is called.
    try:
        w_IndexError = space.w_IndexError
    except AttributeError:
        w_IndexError = None
    index = space.getindex_w(w_index, w_IndexError, "tuple index")
コード例 #39
0
   directly their RPython-level list of wrapped objects.
   """ 
   def __init__(w_self, w_seq, wrappeditems):
        W_AbstractSeqIterObject.__init__(w_self, w_seq)
        w_self.tupleitems = wrappeditems

class W_ReverseSeqIterObject(W_Object):
    from pypy.objspace.std.itertype import reverse_iter_typedef as typedef
    
    def __init__(w_self, space, w_seq, index=-1):
        w_self.w_seq = w_seq
        w_self.w_len = space.len(w_seq)
        w_self.index = space.int_w(w_self.w_len) + index


registerimplementation(W_SeqIterObject)
registerimplementation(W_FastListIterObject)
registerimplementation(W_FastTupleIterObject)
registerimplementation(W_ReverseSeqIterObject)

def iter__SeqIter(space, w_seqiter):
    return w_seqiter

def next__SeqIter(space, w_seqiter):
    if w_seqiter.w_seq is None:
        raise OperationError(space.w_StopIteration, space.w_None) 
    try:
        w_item = space.getitem(w_seqiter.w_seq, space.wrap(w_seqiter.index))
    except OperationError, e:
        w_seqiter.w_seq = None
        if not e.match(space, space.w_IndexError):
コード例 #40
0
    def uint_w(w_self, space):
        a = w_self.longlong
        if a < 0:
            raise OperationError(space.w_ValueError, space.wrap(
                "cannot convert negative integer to unsigned int"))
        b = r_uint(a)
        if r_longlong(b) == a:
            return b
        else:
            raise OperationError(space.w_OverflowError, space.wrap(
                "long int too large to convert to unsigned int"))

    def bigint_w(w_self, space):
        return w_self.asbigint()

registerimplementation(W_SmallLongObject)

# ____________________________________________________________

def llong_mul_ovf(a, b):
    # xxx duplication of the logic from translator/c/src/int.h
    longprod = a * b
    doubleprod = float(a) * float(b)
    doubled_longprod = float(longprod)

    # Fast path for normal case:  small multiplicands, and no info
    # is lost in either method.
    if doubled_longprod == doubleprod:
        return longprod

    # Somebody somewhere lost info.  Close enough, or way off?  Note
コード例 #41
0
ファイル: strbufobject.py プロジェクト: charred/pypy
            return s
        else:
            return self.w_str._value

    def __repr__(w_self):
        """ representation for debugging purposes """
        return "%s(%r[:%d])" % (
            w_self.__class__.__name__, w_self.builder, w_self.length)

    def unwrap(self, space):
        return self.force()

    def str_w(self, space):
        return self.force()

registerimplementation(W_StringBufferObject)

# ____________________________________________________________

def joined2(str1, str2):
    builder = StringBuilder()
    builder.append(str1)
    builder.append(str2)
    return W_StringBufferObject(builder)

# ____________________________________________________________

def delegate_buf2str(space, w_strbuf):
    w_strbuf.force()
    return w_strbuf.w_str
コード例 #42
0
  None Object implementation

  ok and tested
"""

from pypy.objspace.std.model import registerimplementation, W_Object
from pypy.objspace.std.register_all import register_all


class W_NoneObject(W_Object):
    from pypy.objspace.std.nonetype import none_typedef as typedef

    def unwrap(w_self, space):
        return None


registerimplementation(W_NoneObject)

W_NoneObject.w_None = W_NoneObject()


def nonzero__None(space, w_none):
    return space.w_False


def repr__None(space, w_none):
    return space.wrap('None')


register_all(vars())
コード例 #43
0
    def __str__(w_self):
        return str(w_self.boolval) + " Symbolic: " + \
            str(w_self.is_symbolic())

    def is_symbolic(w_self):
        # Int values are non symbolic, should be a cleaner way #HACK
        if isinstance(w_self.__is_symbolic, bool):
            return w_self.__is_symbolic
        return w_self.__is_symbolic.boolval

    def set_symbolic(w_self, s):
        w_self.__is_symbolic = s


registerimplementation(W_BoolObject)

W_BoolObject.w_False = W_BoolObject(False)
W_BoolObject.w_True = W_BoolObject(True)


# bool-to-int delegation requires translating the .boolvar attribute
# to an .intval one
def delegate_Bool2IntObject(space, w_bool):
    return W_IntObject(int(w_bool.boolval))


def delegate_Bool2SmallInt(space, w_bool):
    from pypy.objspace.std.smallintobject import W_SmallIntObject
    return W_SmallIntObject(int(w_bool.boolval))  # cannot overflow
コード例 #44
0
    def extend(self, items_w):
        """Appends the given list of wrapped items."""
        self.strategy.extend(self, items_w)

    def reverse(self):
        """Reverses the list."""
        self.strategy.reverse(self)

    def sort(self, reverse):
        """Sorts the list ascending or descending depending on
        argument reverse. Argument must be unwrapped."""
        self.strategy.sort(self, reverse)


registerimplementation(W_ListObject)


class ListStrategy(object):
    def __init__(self, space):
        self.space = space

    def init_from_list_w(self, w_list, list_w):
        raise NotImplementedError

    def clone(self, w_list):
        raise NotImplementedError

    def copy_into(self, w_list, w_other):
        raise NotImplementedError