Commits

Christian Rafael committed f3c1e34 Draft Merge

Mesclado pypy/pypy em default

Comments (0)

Files changed (73)

lib-python/2.7/test/test_codecs.py

 import unittest
 import codecs
 import locale
-import sys, StringIO, _testcapi
+import sys, StringIO
+try:
+    import _testcapi
+except ImportError:
+    _testcapi = None
 
 class Queue(object):
     """
                     decodedresult += reader.read()
                 self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
 
-            if encoding not in broken_incremental_coders:
+            if encoding not in broken_incremental_coders and _testcapi:
                 # check incremental decoder/encoder (fetched via the Python
                 # and C API) and iterencode()/iterdecode()
                 try:

lib-python/2.7/test/test_descr.py

File contents unchanged.

lib-python/2.7/test/test_traceback.py

 """Test cases for traceback module"""
 
-from _testcapi import traceback_print
+try:
+    from _testcapi import traceback_print
+except ImportError:
+    traceback_print = None
 from StringIO import StringIO
 import sys
 import unittest
 class TracebackFormatTests(unittest.TestCase):
 
     def test_traceback_format(self):
+        if traceback_print is None:
+            raise unittest.SkipTest('Requires _testcapi')
         try:
             raise KeyError('blah')
         except KeyError:

lib-python/2.7/test/test_unicode.py

         self.assertEqual("{}".format(u), '__unicode__ overridden')
 
     def test_encode_decimal(self):
-        from _testcapi import unicode_encodedecimal
+        try:
+            from _testcapi import unicode_encodedecimal
+        except ImportError:
+            raise unittest.SkipTest('Requires _testcapi')
         self.assertEqual(unicode_encodedecimal(u'123'),
                          b'123')
         self.assertEqual(unicode_encodedecimal(u'\u0663.\u0661\u0664'),

lib-python/conftest.py

     RegrTest('test_bz2.py', usemodules='bz2'),
     RegrTest('test_calendar.py'),
     RegrTest('test_call.py', core=True),
-    RegrTest('test_capi.py'),
+    RegrTest('test_capi.py', usemodules='cpyext'),
     RegrTest('test_cd.py'),
     RegrTest('test_cfgparser.py'),
     RegrTest('test_cgi.py'),
     RegrTest('test_cprofile.py'),
     RegrTest('test_crypt.py', usemodules='crypt'),
     RegrTest('test_csv.py', usemodules='_csv'),
-    RegrTest('test_ctypes.py', usemodules="_rawffi thread"),
+    RegrTest('test_ctypes.py', usemodules="_rawffi thread cpyext"),
     RegrTest('test_curses.py'),
     RegrTest('test_datetime.py', usemodules='binascii struct'),
     RegrTest('test_dbm.py'),

lib_pypy/_testcapi.py

     fp, filename, description = imp.find_module('_testcapi', path=[output_dir])
     imp.load_module('_testcapi', fp, filename, description)
 
-compile_shared()
+try:
+    import cpyext
+except ImportError:
+    raise ImportError("No module named '_testcapi'")
+else:
+    compile_shared()

pypy/config/pypyoption.py

      "rctime" , "select", "zipimport", "_lsprof",
      "crypt", "signal", "_rawffi", "termios", "zlib", "bz2",
      "struct", "_hashlib", "_md5", "_sha", "_minimal_curses", "cStringIO",
-     "thread", "itertools", "pyexpat", "_ssl", "cpyext", "array",
+     "thread", "itertools", "pyexpat", "_ssl", "array",
      "binascii", "_multiprocessing", '_warnings',
      "_collections", "_multibytecodec", "micronumpy", "_ffi",
-     "_continuation", "_cffi_backend", "_csv", "cppyy"]
+     "_continuation", "_cffi_backend", "_csv"] # "cpyext", "cppyy"]
+# disabled until problems are fixed
 ))
 
 translation_modules = default_modules.copy()

pypy/doc/whatsnew-head.rst

 
 .. branch: numpy-pickle
 Pickling of numpy arrays and dtypes (including record dtypes)
+
+.. branch: remove-array-smm
+Remove multimethods in the arraymodule
+
+.. branch: callback-stacklet
+Fixed bug when switching stacklets from a C callback
+
+.. branch: remove-set-smm
+Remove multi-methods on sets

pypy/goal/targetpypystandalone.py

     from rpython.rlib.entrypoint import entrypoint
     from rpython.rtyper.lltypesystem import rffi, lltype
 
+    w_pathsetter = space.appexec([], """():
+    def f(path):
+        import sys
+        sys.path[:] = path
+    return f
+    """)
+
     @entrypoint('main', [rffi.CCHARP, lltype.Signed], c_name='pypy_setup_home')
     def pypy_setup_home(ll_home, verbose):
         from pypy.module.sys.initpath import pypy_find_stdlib
             home = rffi.charp2str(ll_home)
         else:
             home = pypydir
-        if space.is_none(pypy_find_stdlib(space, home)):
+        w_path = pypy_find_stdlib(space, home)
+        if space.is_none(w_path):
             if verbose:
                 debug("Failed to find library based on pypy_find_stdlib")
             return 1
         space.startup()
+        space.call_function(w_pathsetter, w_path)
         # import site
         try:
             import_ = space.getattr(space.getbuiltinmodule('__builtin__'),

pypy/interpreter/baseobjspace.py

     def id(self, w_obj):
         w_result = w_obj.immutable_unique_id(self)
         if w_result is None:
-            w_result = self.wrap(compute_unique_id(w_obj))
+            # in the common case, returns an unsigned value
+            w_result = self.wrap(r_uint(compute_unique_id(w_obj)))
         return w_result
 
     def hash_w(self, w_obj):

pypy/interpreter/gateway.py

File contents unchanged.

pypy/module/__pypy__/__init__.py

         'validate_fd'               : 'interp_magic.validate_fd',
         'resizelist_hint'           : 'interp_magic.resizelist_hint',
         'newlist_hint'              : 'interp_magic.newlist_hint',
+        'add_memory_pressure'       : 'interp_magic.add_memory_pressure',
         'newdict'                   : 'interp_dict.newdict',
         'dictstrategy'              : 'interp_dict.dictstrategy',
     }

pypy/module/__pypy__/interp_magic.py

-from pypy.interpreter.baseobjspace import ObjSpace, W_Root
 from pypy.interpreter.error import OperationError, wrap_oserror
 from pypy.interpreter.gateway import unwrap_spec
 from rpython.rlib.objectmodel import we_are_translated
 from pypy.objspace.std.listobject import W_ListObject
 from pypy.objspace.std.typeobject import MethodCache
 from pypy.objspace.std.mapdict import IndexCache
-from rpython.rlib import rposix
+from rpython.rlib import rposix, rgc
 
 
 def internal_repr(space, w_object):
     bltn = BuiltinFunction(func)
     return space.wrap(bltn)
 
-@unwrap_spec(ObjSpace, W_Root, str)
+@unwrap_spec(meth=str)
 def lookup_special(space, w_obj, meth):
     """Lookup up a special method on an object."""
     if space.is_oldstyle_instance(w_obj):
 @unwrap_spec(sizehint=int)
 def newlist_hint(space, sizehint):
     return space.newlist_hint(sizehint)
+
+@unwrap_spec(estimate=int)
+def add_memory_pressure(estimate):
+    rgc.add_memory_pressure(estimate)

pypy/module/array/__init__.py

 from pypy.interpreter.mixedmodule import MixedModule
 
-from pypy.module.array.interp_array import types
-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',

pypy/module/array/interp_array.py

 
 from pypy.interpreter.buffer import RWBuffer
 from pypy.interpreter.error import OperationError
-from pypy.interpreter.gateway import interp2app, unwrap_spec
-from pypy.interpreter.typedef import GetSetProperty, make_weakref_descr
+from pypy.interpreter.gateway import interp2app, unwrap_spec, interpindirect2app
+from pypy.interpreter.typedef import GetSetProperty, make_weakref_descr, TypeDef
+from pypy.interpreter.baseobjspace import W_Root
 from pypy.module._file.interp_file import W_File
-from pypy.objspace.std.model import W_Object
-from pypy.objspace.std.multimethod import FailedToImplement
-from pypy.objspace.std.stdtypedef import SMM, StdTypeDef
-from pypy.objspace.std.register_all import register_all
 from rpython.rlib import jit
 from rpython.rlib.rarithmetic import ovfcheck, widen
 from rpython.rlib.unroll import unrolling_iterable
-from rpython.rlib.objectmodel import specialize, keepalive_until_here
+from rpython.rlib.objectmodel import keepalive_until_here
 from rpython.rtyper.lltypesystem import lltype, rffi
 
 
             if len(__args__.arguments_w) > 0:
                 w_initializer = __args__.arguments_w[0]
                 if space.type(w_initializer) is space.w_str:
-                    a.fromstring(space.str_w(w_initializer))
+                    a.descr_fromstring(space, space.str_w(w_initializer))
                 elif space.type(w_initializer) is space.w_list:
-                    a.fromlist(w_initializer)
+                    a.descr_fromlist(space, w_initializer)
                 else:
                     a.extend(w_initializer, True)
             break
     return a
 
 
-array_append = SMM('append', 2)
-array_extend = SMM('extend', 2)
-
-array_count = SMM('count', 2)
-array_index = SMM('index', 2)
-array_reverse = SMM('reverse', 1)
-array_remove = SMM('remove', 2)
-array_pop = SMM('pop', 2, defaults=(-1,))
-array_insert = SMM('insert', 3)
-
-array_tolist = SMM('tolist', 1)
-array_fromlist = SMM('fromlist', 2)
-array_tostring = SMM('tostring', 1)
-array_fromstring = SMM('fromstring', 2)
-array_tounicode = SMM('tounicode', 1)
-array_fromunicode = SMM('fromunicode', 2)
-array_tofile = SMM('tofile', 2)
-array_fromfile = SMM('fromfile', 3)
-
-array_buffer_info = SMM('buffer_info', 1)
-array_reduce = SMM('__reduce__', 1)
-array_copy = SMM('__copy__', 1)
-array_byteswap = SMM('byteswap', 1)
-
-
 def descr_itemsize(space, self):
     return space.wrap(self.itemsize)
 
 def descr_typecode(space, self):
     return space.wrap(self.typecode)
 
+arr_eq_driver = jit.JitDriver(greens = ['comp_func'], reds = 'auto')
+EQ, NE, LT, LE, GT, GE = range(6)
 
-class W_ArrayBase(W_Object):
-    @staticmethod
-    def register(typeorder):
-        typeorder[W_ArrayBase] = []
+def compare_arrays(space, arr1, arr2, comp_op, comp_func):
+    if (not isinstance(arr1, W_ArrayBase) or
+        not isinstance(arr2, W_ArrayBase)):
+        return space.w_NotImplemented
+    if comp_op == EQ and arr1.len != arr2.len:
+        return space.w_False
+    if comp_op == NE and arr1.len != arr2.len:
+        return space.w_True
+    lgt = min(arr1.len, arr2.len)
+    for i in range(lgt):
+        arr_eq_driver.jit_merge_point(comp_func=comp_func)
+        w_elem1 = arr1.w_getitem(space, i)
+        w_elem2 = arr2.w_getitem(space, i)
+        res = space.is_true(comp_func(w_elem1, w_elem2))
+        if comp_op == EQ:
+            if not res:
+                return space.w_False
+        elif comp_op == NE:
+            if res:
+                return space.w_True
+        elif comp_op == LT or comp_op == GT:
+            if res:
+                return space.w_True
+            elif not space.is_true(space.eq(w_elem1, w_elem2)):
+                return space.w_False
+        else:
+            if not res:
+                return space.w_False
+            elif not space.is_true(space.eq(w_elem1, w_elem2)):
+                return space.w_True
+    # we have some leftovers
+    if comp_op == EQ:
+        return space.w_True
+    elif comp_op == NE:
+        return space.w_False
+    if arr1.len == arr2.len:
+        if comp_op == LT or comp_op == GT:
+            return space.w_False
+        return space.w_True
+    if comp_op == LT or comp_op == LE:
+        if arr1.len < arr2.len:
+            return space.w_True
+        return space.w_False
+    if arr1.len > arr2.len:
+        return space.w_True
+    return space.w_False
 
-W_ArrayBase.typedef = StdTypeDef(
+UNICODE_ARRAY = lltype.Ptr(lltype.Array(lltype.UniChar,
+                                        hints={'nolength': True}))
+
+class W_ArrayBase(W_Root):
+    _attrs_ = ('space', 'len', 'allocated', '_lifeline_') # no buffer
+
+    def __init__(self, space):
+        self.space = space
+        self.len = 0
+        self.allocated = 0
+
+    def descr_append(self, space, w_x):
+        """ append(x)
+
+        Append new value x to the end of the array.
+        """
+        raise NotImplementedError
+
+    def descr_extend(self, space, w_x):
+        """ extend(array or iterable)
+
+        Append items to the end of the array.
+        """
+        self.extend(w_x)
+
+    def descr_count(self, space, w_val):
+        """ count(x)
+
+        Return number of occurrences of x in the array.
+        """
+        raise NotImplementedError
+
+    def descr_index(self, space, w_x):
+        """ index(x)
+
+        Return index of first occurrence of x in the array.
+        """
+        raise NotImplementedError
+
+    def descr_reverse(self, space):
+        """ reverse()
+
+        Reverse the order of the items in the array.
+        """
+        raise NotImplementedError
+
+    def descr_remove(self, space, w_val):
+        """ remove(x)
+
+        Remove the first occurrence of x in the array.
+        """
+        raise NotImplementedError
+
+    @unwrap_spec(i=int)
+    def descr_pop(self, space, i=-1):
+        """ pop([i])
+
+        Return the i-th element and delete it from the array. i defaults to -1.
+        """
+        raise NotImplementedError
+
+    @unwrap_spec(idx=int)
+    def descr_insert(self, space, idx, w_val):
+        """ insert(i,x)
+
+        Insert a new item x into the array before position i.
+        """
+        raise NotImplementedError
+
+    def descr_tolist(self, space):
+        """ tolist() -> list
+
+        Convert array to an ordinary list with the same items.
+        """
+        w_l = space.newlist([])
+        for i in range(self.len):
+            w_l.append(self.w_getitem(space, i))
+        return w_l
+
+    def descr_fromlist(self, space, w_lst):
+        """ fromlist(list)
+
+        Append items to array from list.
+        """
+        if not space.isinstance_w(w_lst, space.w_list):
+            raise OperationError(space.w_TypeError,
+                                 space.wrap("arg must be list"))
+        s = self.len
+        try:
+            self.fromsequence(w_lst)
+        except OperationError:
+            self.setlen(s)
+            raise
+
+    def descr_tostring(self, space):
+        """ tostring() -> string
+
+        Convert the array to an array of machine values and return the string
+        representation.
+        """
+        cbuf = self._charbuf_start()
+        s = rffi.charpsize2str(cbuf, self.len * self.itemsize)
+        self._charbuf_stop()
+        return self.space.wrap(s)
+
+    @unwrap_spec(s=str)
+    def descr_fromstring(self, space, s):
+        """ fromstring(string)
+
+        Appends items from the string, interpreting it as an array of machine
+        values,as if it had been read from a file using the fromfile() method).
+        """
+        if len(s) % self.itemsize != 0:
+            msg = 'string length not a multiple of item size'
+            raise OperationError(self.space.w_ValueError, self.space.wrap(msg))
+        oldlen = self.len
+        new = len(s) / self.itemsize
+        self.setlen(oldlen + new)
+        cbuf = self._charbuf_start()
+        for i in range(len(s)):
+            cbuf[oldlen * self.itemsize + i] = s[i]
+        self._charbuf_stop()
+
+    @unwrap_spec(w_f=W_File, n=int)
+    def descr_fromfile(self, space, w_f, n):
+        """ fromfile(f, n)
+
+        Read n objects from the file object f and append them to the end of the
+        array.  Also called as read.
+        """
+        try:
+            size = ovfcheck(self.itemsize * n)
+        except OverflowError:
+            raise MemoryError
+        w_item = space.call_method(w_f, 'read', space.wrap(size))
+        item = space.str_w(w_item)
+        if len(item) < size:
+            n = len(item) % self.itemsize
+            elems = max(0, len(item) - (len(item) % self.itemsize))
+            if n != 0:
+                item = item[0:elems]
+            self.descr_fromstring(space, item)
+            msg = "not enough items in file"
+            raise OperationError(space.w_EOFError, space.wrap(msg))
+        self.descr_fromstring(space, item)
+
+    @unwrap_spec(w_f=W_File)
+    def descr_tofile(self, space, w_f):
+        """ tofile(f)
+
+        Write all items (as machine values) to the file object f.  Also called as
+        write.
+        """
+        w_s = self.descr_tostring(space)
+        space.call_method(w_f, 'write', w_s)
+
+    def descr_fromunicode(self, space, w_ustr):
+        """ fromunicode(ustr)
+
+        Extends this array with data from the unicode string ustr.
+        The array must be a type 'u' array; otherwise a ValueError
+        is raised.  Use array.fromstring(ustr.decode(...)) to
+        append Unicode data to an array of some other type.
+        """
+        # XXX the following probable bug is not emulated:
+        # CPython accepts a non-unicode string or a buffer, and then
+        # behaves just like fromstring(), except that it strangely truncate
+        # string arguments at multiples of the unicode byte size.
+        # Let's only accept unicode arguments for now.
+        if self.typecode == 'u':
+            self.fromsequence(w_ustr)
+        else:
+            msg = "fromunicode() may only be called on type 'u' arrays"
+            raise OperationError(space.w_ValueError, space.wrap(msg))
+
+    def descr_tounicode(self, space):
+        """ tounicode() -> unicode
+
+        Convert the array to a unicode string.  The array must be
+        a type 'u' array; otherwise a ValueError is raised.  Use
+        array.tostring().decode() to obtain a unicode string from
+        an array of some other type.
+        """
+        if self.typecode == 'u':
+            buf = rffi.cast(UNICODE_ARRAY, self._buffer_as_unsigned())
+            return space.wrap(rffi.wcharpsize2unicode(buf, self.len))
+        else:
+            msg = "tounicode() may only be called on type 'u' arrays"
+            raise OperationError(space.w_ValueError, space.wrap(msg))
+
+    def descr_buffer_info(self, space):
+        """ buffer_info() -> (address, length)
+
+        Return a tuple (address, length) giving the current memory address and
+        the length in items of the buffer used to hold array's contents
+        The length should be multiplied by the itemsize attribute to calculate
+        the buffer length in bytes.
+        """
+        w_ptr = space.wrap(self._buffer_as_unsigned())
+        w_len = space.wrap(self.len)
+        return space.newtuple([w_ptr, w_len])
+
+    def descr_reduce(self, space):
+        """ Return state information for pickling.
+        """
+        if self.len > 0:
+            w_s = self.descr_tostring(space)
+            args = [space.wrap(self.typecode), w_s]
+        else:
+            args = [space.wrap(self.typecode)]
+        try:
+            dct = space.getattr(self, space.wrap('__dict__'))
+        except OperationError:
+            dct = space.w_None
+        return space.newtuple([space.type(self), space.newtuple(args), dct])
+
+    def descr_copy(self, space):
+        """ copy(array)
+
+        Return a copy of the array.
+        """
+        w_a = self.constructor(self.space)
+        w_a.setlen(self.len, overallocate=False)
+        rffi.c_memcpy(
+            rffi.cast(rffi.VOIDP, w_a._buffer_as_unsigned()),
+            rffi.cast(rffi.VOIDP, self._buffer_as_unsigned()),
+            self.len * self.itemsize
+        )
+        return w_a
+
+    def descr_byteswap(self, space):
+        """ byteswap()
+
+        Byteswap all items of the array.  If the items in the array are not 1, 2,
+        4, or 8 bytes in size, RuntimeError is raised.
+        """
+        if self.itemsize not in [1, 2, 4, 8]:
+            msg = "byteswap not supported for this array"
+            raise OperationError(space.w_RuntimeError, space.wrap(msg))
+        if self.len == 0:
+            return
+        bytes = self._charbuf_start()
+        tmp = [bytes[0]] * self.itemsize
+        for start in range(0, self.len * self.itemsize, self.itemsize):
+            stop = start + self.itemsize - 1
+            for i in range(self.itemsize):
+                tmp[i] = bytes[start + i]
+            for i in range(self.itemsize):
+                bytes[stop - i] = tmp[i]
+        self._charbuf_stop()
+
+    def descr_len(self, space):
+        return space.wrap(self.len)
+
+    def descr_eq(self, space, w_arr2):
+        "x.__eq__(y) <==> x==y"
+        return compare_arrays(space, self, w_arr2, EQ, space.eq)
+
+    def descr_ne(self, space, w_arr2):
+        "x.__ne__(y) <==> x!=y"
+        return compare_arrays(space, self, w_arr2, NE, space.ne)
+
+    def descr_lt(self, space, w_arr2):
+        "x.__lt__(y) <==> x<y"
+        return compare_arrays(space, self, w_arr2, LT, space.lt)
+
+    def descr_le(self, space, w_arr2):
+        "x.__le__(y) <==> x<=y"
+        return compare_arrays(space, self, w_arr2, LE, space.le)
+
+    def descr_gt(self, space, w_arr2):
+        "x.__gt__(y) <==> x>y"
+        return compare_arrays(space, self, w_arr2, GT, space.gt)
+
+    def descr_ge(self, space, w_arr2):
+        "x.__ge__(y) <==> x>=y"
+        return compare_arrays(space, self, w_arr2, GE, space.ge)
+
+    # Basic get/set/append/extend methods
+
+    def descr_getitem(self, space, w_idx):
+        "x.__getitem__(y) <==> x[y]"
+        if not space.isinstance_w(w_idx, space.w_slice):
+            idx, stop, step = space.decode_index(w_idx, self.len)
+            assert step == 0
+            return self.w_getitem(space, idx)
+        else:
+            return self.getitem_slice(space, w_idx)
+
+    def descr_getslice(self, space, w_i, w_j):
+        return space.getitem(self, space.newslice(w_i, w_j, space.w_None))
+
+
+    def descr_setitem(self, space, w_idx, w_item):
+        "x.__setitem__(i, y) <==> x[i]=y"
+        if space.isinstance_w(w_idx, space.w_slice):
+            self.setitem_slice(space, w_idx, w_item)
+        else:
+            self.setitem(space, w_idx, w_item)
+
+    def descr_setslice(self, space, w_start, w_stop, w_item):
+        self.setitem_slice(space,
+                           space.newslice(w_start, w_stop, space.w_None),
+                           w_item)
+
+    def descr_delitem(self, space, w_idx):
+        start, stop, step, size = self.space.decode_index4(w_idx, self.len)
+        if step != 1:
+            # I don't care about efficiency of that so far
+            w_lst = self.descr_tolist(space)
+            space.delitem(w_lst, w_idx)
+            self.setlen(0)
+            self.fromsequence(w_lst)
+            return
+        return self.delitem(space, start, stop)
+
+    def descr_delslice(self, space, w_start, w_stop):
+        self.descr_delitem(space, space.newslice(w_start, w_stop, space.w_None))
+
+    def descr_add(self, space, w_other):
+        raise NotImplementedError
+
+    def descr_inplace_add(self, space, w_other):
+        raise NotImplementedError
+
+    def descr_mul(self, space, w_repeat):
+        raise NotImplementedError
+
+    def descr_inplace_mul(self, space, w_repeat):
+        raise NotImplementedError
+
+    def descr_radd(self, space, w_other):
+        return self.descr_add(space, w_other)
+
+    def descr_rmul(self, space, w_repeat):
+        return self.descr_mul(space, w_repeat)
+
+    # Misc methods
+
+    def descr_buffer(self, space):
+        return space.wrap(ArrayBuffer(self))
+
+    def descr_repr(self, space):
+        if self.len == 0:
+            return space.wrap("array('%s')" % self.typecode)
+        elif self.typecode == "c":
+            r = space.repr(self.descr_tostring(space))
+            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
+            return space.wrap(s)
+        elif self.typecode == "u":
+            r = space.repr(self.descr_tounicode(space))
+            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
+            return space.wrap(s)
+        else:
+            r = space.repr(self.descr_tolist(space))
+            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
+            return space.wrap(s)
+
+W_ArrayBase.typedef = TypeDef(
     'array',
     __new__ = interp2app(w_array),
     __module__   = 'array',
+
+    __len__ = interp2app(W_ArrayBase.descr_len),
+    __eq__ = interp2app(W_ArrayBase.descr_eq),
+    __ne__ = interp2app(W_ArrayBase.descr_ne),
+    __lt__ = interp2app(W_ArrayBase.descr_lt),
+    __le__ = interp2app(W_ArrayBase.descr_le),
+    __gt__ = interp2app(W_ArrayBase.descr_gt),
+    __ge__ = interp2app(W_ArrayBase.descr_ge),
+
+    __getitem__ = interp2app(W_ArrayBase.descr_getitem),
+    __getslice__ = interp2app(W_ArrayBase.descr_getslice),
+    __setitem__ = interp2app(W_ArrayBase.descr_setitem),
+    __setslice__ = interp2app(W_ArrayBase.descr_setslice),
+    __delitem__ = interp2app(W_ArrayBase.descr_delitem),
+    __delslice__ = interp2app(W_ArrayBase.descr_delslice),
+
+    __add__ = interpindirect2app(W_ArrayBase.descr_add),
+    __iadd__ = interpindirect2app(W_ArrayBase.descr_inplace_add),
+    __mul__ = interpindirect2app(W_ArrayBase.descr_mul),
+    __imul__ = interpindirect2app(W_ArrayBase.descr_inplace_mul),
+    __radd__ = interp2app(W_ArrayBase.descr_radd),
+    __rmul__ = interp2app(W_ArrayBase.descr_rmul),
+
+    __buffer__ = interp2app(W_ArrayBase.descr_buffer),
+    __repr__ = interp2app(W_ArrayBase.descr_repr),
+
     itemsize = GetSetProperty(descr_itemsize),
     typecode = GetSetProperty(descr_typecode),
     __weakref__ = make_weakref_descr(W_ArrayBase),
+    append = interpindirect2app(W_ArrayBase.descr_append),
+    extend = interp2app(W_ArrayBase.descr_extend),
+    count = interpindirect2app(W_ArrayBase.descr_count),
+    index = interpindirect2app(W_ArrayBase.descr_index),
+    reverse = interpindirect2app(W_ArrayBase.descr_reverse),
+    remove = interpindirect2app(W_ArrayBase.descr_remove),
+    pop = interpindirect2app(W_ArrayBase.descr_pop),
+    insert = interpindirect2app(W_ArrayBase.descr_insert),
+
+    tolist = interp2app(W_ArrayBase.descr_tolist),
+    fromlist = interp2app(W_ArrayBase.descr_fromlist),
+    tostring = interp2app(W_ArrayBase.descr_tostring),
+    fromstring = interp2app(W_ArrayBase.descr_fromstring),
+    tofile = interp2app(W_ArrayBase.descr_tofile),
+    fromfile = interp2app(W_ArrayBase.descr_fromfile),
+    fromunicode = interp2app(W_ArrayBase.descr_fromunicode),
+    tounicode = interp2app(W_ArrayBase.descr_tounicode),
+
+    buffer_info = interp2app(W_ArrayBase.descr_buffer_info),
+    __copy__ = interp2app(W_ArrayBase.descr_copy),
+    __reduce__ = interp2app(W_ArrayBase.descr_reduce),
+    byteswap = interp2app(W_ArrayBase.descr_byteswap),
 )
-W_ArrayBase.typedef.registermethods(globals())
 
 
 class TypeCode(object):
     def __init__(self, itemtype, unwrap, canoverflow=False, signed=False):
         self.itemtype = itemtype
         self.bytes = rffi.sizeof(itemtype)
-        #self.arraytype = lltype.GcArray(itemtype)
         self.arraytype = lltype.Array(itemtype, hints={'nolength': True})
         self.unwrap = unwrap
         self.signed = signed
         itemsize = mytype.bytes
         typecode = mytype.typecode
 
-        @staticmethod
-        def register(typeorder):
-            typeorder[W_Array] = [(W_ArrayBase, None)]
+        _attrs_ = ('space', 'len', 'allocated', '_lifeline_', 'buffer')
 
         def __init__(self, space):
-            self.space = space
-            self.len = 0
-            self.allocated = 0
+            W_ArrayBase.__init__(self, space)
             self.buffer = lltype.nullptr(mytype.arraytype)
 
         def item_w(self, w_item):
                 raise
             self.setlen(oldlen + i)
 
-        def fromstring(self, s):
-            if len(s) % self.itemsize != 0:
-                msg = 'string length not a multiple of item size'
-                raise OperationError(self.space.w_ValueError, self.space.wrap(msg))
-            oldlen = self.len
-            new = len(s) / mytype.bytes
-            self.setlen(oldlen + new)
-            cbuf = self._charbuf_start()
-            for i in range(len(s)):
-                cbuf[oldlen * mytype.bytes + i] = s[i]
-            self._charbuf_stop()
-
-        def fromlist(self, w_lst):
-            s = self.len
-            try:
-                self.fromsequence(w_lst)
-            except OperationError:
-                self.setlen(s)
-                raise
-
         def extend(self, w_iterable, accept_different_array=False):
             space = self.space
             if isinstance(w_iterable, W_Array):
         def _charbuf_start(self):
             return rffi.cast(rffi.CCHARP, self.buffer)
 
+        def _buffer_as_unsigned(self):
+            return rffi.cast(lltype.Unsigned, self.buffer)
+
         def _charbuf_stop(self):
             keepalive_until_here(self)
 
                 item = float(item)
             return space.wrap(item)
 
-    # Basic get/set/append/extend methods
+        # interface
 
-    def len__Array(space, self):
-        return space.wrap(self.len)
+        def descr_append(self, space, w_x):
+            x = self.item_w(w_x)
+            self.setlen(self.len + 1)
+            self.buffer[self.len - 1] = x
 
-    def getitem__Array_ANY(space, self, w_idx):
-        idx, stop, step = space.decode_index(w_idx, self.len)
-        assert step == 0
-        return self.w_getitem(space, idx)
+        # List interface
+        def descr_count(self, space, w_val):
+            cnt = 0
+            for i in range(self.len):
+                # XXX jitdriver
+                w_item = self.w_getitem(space, i)
+                if space.is_true(space.eq(w_item, w_val)):
+                    cnt += 1
+            return space.wrap(cnt)
 
-    def getitem__Array_Slice(space, self, w_slice):
-        start, stop, step, size = space.decode_index4(w_slice, self.len)
-        w_a = mytype.w_class(self.space)
-        w_a.setlen(size, overallocate=False)
-        assert step != 0
-        j = 0
-        for i in range(start, stop, step):
-            w_a.buffer[j] = self.buffer[i]
-            j += 1
-        return w_a
+        def descr_index(self, space, w_val):
+            for i in range(self.len):
+                w_item = self.w_getitem(space, i)
+                if space.is_true(space.eq(w_item, w_val)):
+                    return space.wrap(i)
+            msg = 'array.index(x): x not in list'
+            raise OperationError(space.w_ValueError, space.wrap(msg))
 
-    def getslice__Array_ANY_ANY(space, self, w_i, w_j):
-        return space.getitem(self, space.newslice(w_i, w_j, space.w_None))
+        def descr_reverse(self, space):
+            b = self.buffer
+            for i in range(self.len / 2):
+                b[i], b[self.len - i - 1] = b[self.len - i - 1], b[i]
 
-    def setitem__Array_ANY_ANY(space, self, w_idx, w_item):
-        idx, stop, step = space.decode_index(w_idx, self.len)
-        if step != 0:
-            msg = 'can only assign array to array slice'
-            raise OperationError(self.space.w_TypeError, self.space.wrap(msg))
-        item = self.item_w(w_item)
-        self.buffer[idx] = item
+        def descr_pop(self, space, i):
+            if i < 0:
+                i += self.len
+            if i < 0 or i >= self.len:
+                msg = 'pop index out of range'
+                raise OperationError(space.w_IndexError, space.wrap(msg))
+            w_val = self.w_getitem(space, i)
+            while i < self.len - 1:
+                self.buffer[i] = self.buffer[i + 1]
+                i += 1
+            self.setlen(self.len - 1)
+            return w_val
 
-    def setitem__Array_Slice_Array(space, self, w_idx, w_item):
-        start, stop, step, size = self.space.decode_index4(w_idx, self.len)
-        assert step != 0
-        if w_item.len != size or self is w_item:
-            # XXX this is a giant slow hack
-            w_lst = array_tolist__Array(space, self)
-            w_item = space.call_method(w_item, 'tolist')
-            space.setitem(w_lst, w_idx, w_item)
-            self.setlen(0)
-            self.fromsequence(w_lst)
-        else:
+        def descr_remove(self, space, w_val):
+            w_idx = self.descr_index(space, w_val)
+            self.descr_pop(space, space.int_w(w_idx))
+
+        def descr_insert(self, space, idx, w_val):
+            if idx < 0:
+                idx += self.len
+            if idx < 0:
+                idx = 0
+            if idx > self.len:
+                idx = self.len
+
+            val = self.item_w(w_val)
+            self.setlen(self.len + 1)
+            i = self.len - 1
+            while i > idx:
+                self.buffer[i] = self.buffer[i - 1]
+                i -= 1
+            self.buffer[i] = val
+
+        def getitem_slice(self, space, w_idx):
+            start, stop, step, size = space.decode_index4(w_idx, self.len)
+            w_a = mytype.w_class(self.space)
+            w_a.setlen(size, overallocate=False)
+            assert step != 0
             j = 0
             for i in range(start, stop, step):
-                self.buffer[i] = w_item.buffer[j]
+                w_a.buffer[j] = self.buffer[i]
                 j += 1
+            return w_a
 
-    def setslice__Array_ANY_ANY_ANY(space, self, w_i, w_j, w_x):
-        space.setitem(self, space.newslice(w_i, w_j, space.w_None), w_x)
+        def setitem(self, space, w_idx, w_item):
+            idx, stop, step = space.decode_index(w_idx, self.len)
+            if step != 0:
+                msg = 'can only assign array to array slice'
+                raise OperationError(self.space.w_TypeError,
+                                     self.space.wrap(msg))
+            item = self.item_w(w_item)
+            self.buffer[idx] = item
 
-    def array_append__Array_ANY(space, self, w_x):
-        x = self.item_w(w_x)
-        self.setlen(self.len + 1)
-        self.buffer[self.len - 1] = x
+        def setitem_slice(self, space, w_idx, w_item):
+            if not isinstance(w_item, W_Array):
+                raise OperationError(space.w_TypeError, space.wrap(
+                    "can only assign to a slice array"))
+            start, stop, step, size = self.space.decode_index4(w_idx, self.len)
+            assert step != 0
+            if w_item.len != size or self is w_item:
+                # XXX this is a giant slow hack
+                w_lst = self.descr_tolist(space)
+                w_item = space.call_method(w_item, 'tolist')
+                space.setitem(w_lst, w_idx, w_item)
+                self.setlen(0)
+                self.fromsequence(w_lst)
+            else:
+                j = 0
+                for i in range(start, stop, step):
+                    self.buffer[i] = w_item.buffer[j]
+                    j += 1
 
-    def array_extend__Array_ANY(space, self, w_iterable):
-        self.extend(w_iterable)
+        # We can't look into this function until ptradd works with things (in the
+        # JIT) other than rffi.CCHARP
+        @jit.dont_look_inside
+        def delitem(self, space, i, j):
+            if i < 0:
+                i += self.len
+            if i < 0:
+                i = 0
+            if j < 0:
+                j += self.len
+            if j < 0:
+                j = 0
+            if j > self.len:
+                j = self.len
+            if i >= j:
+                return None
+            oldbuffer = self.buffer
+            self.buffer = lltype.malloc(mytype.arraytype,
+                          max(self.len - (j - i), 0), flavor='raw',
+                          add_memory_pressure=True)
+            if i:
+                rffi.c_memcpy(
+                    rffi.cast(rffi.VOIDP, self.buffer),
+                    rffi.cast(rffi.VOIDP, oldbuffer),
+                    i * mytype.bytes
+                )
+            if j < self.len:
+                rffi.c_memcpy(
+                    rffi.cast(rffi.VOIDP, rffi.ptradd(self.buffer, i)),
+                    rffi.cast(rffi.VOIDP, rffi.ptradd(oldbuffer, j)),
+                    (self.len - j) * mytype.bytes
+                )
+            self.len -= j - i
+            self.allocated = self.len
+            if oldbuffer:
+                lltype.free(oldbuffer, flavor='raw')
 
-    # List interface
-    def array_count__Array_ANY(space, self, w_val):
-        cnt = 0
-        for i in range(self.len):
-            w_item = self.w_getitem(space, i)
-            if space.is_true(space.eq(w_item, w_val)):
-                cnt += 1
-        return space.wrap(cnt)
+        # Add and mul methods
 
-    def array_index__Array_ANY(space, self, w_val):
-        for i in range(self.len):
-            w_item = self.w_getitem(space, i)
-            if space.is_true(space.eq(w_item, w_val)):
-                return space.wrap(i)
-        msg = 'array.index(x): x not in list'
-        raise OperationError(space.w_ValueError, space.wrap(msg))
+        def descr_add(self, space, w_other):
+            if not isinstance(w_other, W_Array):
+                return space.w_NotImplemented
+            a = mytype.w_class(space)
+            a.setlen(self.len + w_other.len, overallocate=False)
+            for i in range(self.len):
+                a.buffer[i] = self.buffer[i]
+            for i in range(w_other.len):
+                a.buffer[i + self.len] = w_other.buffer[i]
+            return a
 
-    def array_reverse__Array(space, self):
-        b = self.buffer
-        for i in range(self.len / 2):
-            b[i], b[self.len - i - 1] = b[self.len - i - 1], b[i]
+        def descr_inplace_add(self, space, w_other):
+            if not isinstance(w_other, W_Array):
+                return space.w_NotImplemented
+            oldlen = self.len
+            otherlen = w_other.len
+            self.setlen(oldlen + otherlen)
+            for i in range(otherlen):
+                self.buffer[oldlen + i] = w_other.buffer[i]
+            return self
 
-    def array_pop__Array_ANY(space, self, w_idx):
-        i = space.int_w(w_idx)
-        if i < 0:
-            i += self.len
-        if i < 0 or i >= self.len:
-            msg = 'pop index out of range'
-            raise OperationError(space.w_IndexError, space.wrap(msg))
-        w_val = self.w_getitem(space, i)
-        while i < self.len - 1:
-            self.buffer[i] = self.buffer[i + 1]
-            i += 1
-        self.setlen(self.len - 1)
-        return w_val
+        def descr_mul(self, space, w_repeat):
+            return _mul_helper(space, self, w_repeat, False)
 
-    def array_remove__Array_ANY(space, self, w_val):
-        w_idx = array_index__Array_ANY(space, self, w_val)
-        array_pop__Array_ANY(space, self, w_idx)
-
-    def array_insert__Array_ANY_ANY(space, self, w_idx, w_val):
-        idx = space.int_w(w_idx)
-        if idx < 0:
-            idx += self.len
-        if idx < 0:
-            idx = 0
-        if idx > self.len:
-            idx = self.len
-
-        val = self.item_w(w_val)
-        self.setlen(self.len + 1)
-        i = self.len - 1
-        while i > idx:
-            self.buffer[i] = self.buffer[i - 1]
-            i -= 1
-        self.buffer[i] = val
-
-    def delitem__Array_ANY(space, self, w_idx):
-        # XXX this is a giant slow hack
-        w_lst = array_tolist__Array(space, self)
-        space.delitem(w_lst, w_idx)
-        self.setlen(0)
-        self.fromsequence(w_lst)
-
-    # We can't look into this function until ptradd works with things (in the
-    # JIT) other than rffi.CCHARP
-    @jit.dont_look_inside
-    def delslice__Array_ANY_ANY(space, self, w_i, w_j):
-        i = space.int_w(w_i)
-        if i < 0:
-            i += self.len
-        if i < 0:
-            i = 0
-        j = space.int_w(w_j)
-        if j < 0:
-            j += self.len
-        if j < 0:
-            j = 0
-        if j > self.len:
-            j = self.len
-        if i >= j:
-            return None
-        oldbuffer = self.buffer
-        self.buffer = lltype.malloc(mytype.arraytype,
-                      max(self.len - (j - i), 0), flavor='raw',
-                      add_memory_pressure=True)
-        if i:
-            rffi.c_memcpy(
-                rffi.cast(rffi.VOIDP, self.buffer),
-                rffi.cast(rffi.VOIDP, oldbuffer),
-                i * mytype.bytes
-            )
-        if j < self.len:
-            rffi.c_memcpy(
-                rffi.cast(rffi.VOIDP, rffi.ptradd(self.buffer, i)),
-                rffi.cast(rffi.VOIDP, rffi.ptradd(oldbuffer, j)),
-                (self.len - j) * mytype.bytes
-            )
-        self.len -= j - i
-        self.allocated = self.len
-        if oldbuffer:
-            lltype.free(oldbuffer, flavor='raw')
-
-    # Add and mul methods
-
-    def add__Array_Array(space, self, other):
-        a = mytype.w_class(space)
-        a.setlen(self.len + other.len, overallocate=False)
-        for i in range(self.len):
-            a.buffer[i] = self.buffer[i]
-        for i in range(other.len):
-            a.buffer[i + self.len] = other.buffer[i]
-        return a
-
-    def inplace_add__Array_Array(space, self, other):
-        oldlen = self.len
-        otherlen = other.len
-        self.setlen(oldlen + otherlen)
-        for i in range(otherlen):
-            self.buffer[oldlen + i] = other.buffer[i]
-        return self
-
-    def mul__Array_ANY(space, self, w_repeat):
-        return _mul_helper(space, self, w_repeat, False)
-
-    def mul__ANY_Array(space, w_repeat, self):
-        return _mul_helper(space, self, w_repeat, False)
-
-    def inplace_mul__Array_ANY(space, self, w_repeat):
-        return _mul_helper(space, self, w_repeat, True)
+        def descr_inplace_mul(self, space, w_repeat):
+            return _mul_helper(space, self, w_repeat, True)
 
     def _mul_helper(space, self, w_repeat, is_inplace):
         try:
             repeat = space.getindex_w(w_repeat, space.w_OverflowError)
         except OperationError, e:
             if e.match(space, space.w_TypeError):
-                raise FailedToImplement
+                return space.w_NotImplemented
             raise
         repeat = max(repeat, 0)
         try:
                 a.buffer[r * oldlen + i] = self.buffer[i]
         return a
 
-    # Convertions
-
-    def array_tolist__Array(space, self):
-        w_l = space.newlist([])
-        for i in range(self.len):
-            w_l.append(self.w_getitem(space, i))
-        return w_l
-
-    def array_fromlist__Array_List(space, self, w_lst):
-        self.fromlist(w_lst)
-
-    def array_fromstring__Array_ANY(space, self, w_s):
-        self.fromstring(space.str_w(w_s))
-
-    def array_tostring__Array(space, self):
-        cbuf = self._charbuf_start()
-        s = rffi.charpsize2str(cbuf, self.len * mytype.bytes)
-        self._charbuf_stop()
-        return self.space.wrap(s)
-
-    def array_fromfile__Array_ANY_ANY(space, self, w_f, w_n):
-        if not isinstance(w_f, W_File):
-            msg = "arg1 must be open file"
-            raise OperationError(space.w_TypeError, space.wrap(msg))
-        n = space.int_w(w_n)
-
-        try:
-            size = ovfcheck(self.itemsize * n)
-        except OverflowError:
-            raise MemoryError
-        w_item = space.call_method(w_f, 'read', space.wrap(size))
-        item = space.str_w(w_item)
-        if len(item) < size:
-            n = len(item) % self.itemsize
-            elems = max(0, len(item) - (len(item) % self.itemsize))
-            if n != 0:
-                item = item[0:elems]
-            w_item = space.wrap(item)
-            array_fromstring__Array_ANY(space, self, w_item)
-            msg = "not enough items in file"
-            raise OperationError(space.w_EOFError, space.wrap(msg))
-        array_fromstring__Array_ANY(space, self, w_item)
-
-    def array_tofile__Array_ANY(space, self, w_f):
-        if not isinstance(w_f, W_File):
-            msg = "arg1 must be open file"
-            raise OperationError(space.w_TypeError, space.wrap(msg))
-        w_s = array_tostring__Array(space, self)
-        space.call_method(w_f, 'write', w_s)
-
-    if mytype.typecode == 'u':
-
-        def array_fromunicode__Array_Unicode(space, self, w_ustr):
-            # XXX the following probable bug is not emulated:
-            # CPython accepts a non-unicode string or a buffer, and then
-            # behaves just like fromstring(), except that it strangely truncate
-            # string arguments at multiples of the unicode byte size.
-            # Let's only accept unicode arguments for now.
-            self.fromsequence(w_ustr)
-
-        def array_tounicode__Array(space, self):
-            return space.wrap(rffi.wcharpsize2unicode(self.buffer, self.len))
-    else:
-
-        def array_fromunicode__Array_Unicode(space, self, w_ustr):
-            msg = "fromunicode() may only be called on type 'u' arrays"
-            raise OperationError(space.w_ValueError, space.wrap(msg))
-
-        def array_tounicode__Array(space, self):
-            msg = "tounicode() may only be called on type 'u' arrays"
-            raise OperationError(space.w_ValueError, space.wrap(msg))
-
-    # Compare methods
-    @specialize.arg(3)
-    def _cmp_impl(space, self, other, space_fn):
-        # XXX this is a giant slow hack
-        w_lst1 = array_tolist__Array(space, self)
-        w_lst2 = space.call_method(other, 'tolist')
-        return space_fn(w_lst1, w_lst2)
-
-    def eq__Array_ArrayBase(space, self, other):
-        return _cmp_impl(space, self, other, space.eq)
-
-    def ne__Array_ArrayBase(space, self, other):
-        return _cmp_impl(space, self, other, space.ne)
-
-    def lt__Array_ArrayBase(space, self, other):
-        return _cmp_impl(space, self, other, space.lt)
-
-    def le__Array_ArrayBase(space, self, other):
-        return _cmp_impl(space, self, other, space.le)
-
-    def gt__Array_ArrayBase(space, self, other):
-        return _cmp_impl(space, self, other, space.gt)
-
-    def ge__Array_ArrayBase(space, self, other):
-        return _cmp_impl(space, self, other, space.ge)
-
-    # Misc methods
-
-    def buffer__Array(space, self):
-        return space.wrap(ArrayBuffer(self))
-
-    def array_buffer_info__Array(space, self):
-        w_ptr = space.wrap(rffi.cast(lltype.Unsigned, self.buffer))
-        w_len = space.wrap(self.len)
-        return space.newtuple([w_ptr, w_len])
-
-    def array_reduce__Array(space, self):
-        if self.len > 0:
-            w_s = array_tostring__Array(space, self)
-            args = [space.wrap(mytype.typecode), w_s]
-        else:
-            args = [space.wrap(mytype.typecode)]
-        try:
-            dct = space.getattr(self, space.wrap('__dict__'))
-        except OperationError:
-            dct = space.w_None
-        return space.newtuple([space.type(self), space.newtuple(args), dct])
-
-    def array_copy__Array(space, self):
-        w_a = mytype.w_class(self.space)
-        w_a.setlen(self.len, overallocate=False)
-        rffi.c_memcpy(
-            rffi.cast(rffi.VOIDP, w_a.buffer),
-            rffi.cast(rffi.VOIDP, self.buffer),
-            self.len * mytype.bytes
-        )
-        return w_a
-
-    def array_byteswap__Array(space, self):
-        if mytype.bytes not in [1, 2, 4, 8]:
-            msg = "byteswap not supported for this array"
-            raise OperationError(space.w_RuntimeError, space.wrap(msg))
-        if self.len == 0:
-            return
-        bytes = self._charbuf_start()
-        tmp = [bytes[0]] * mytype.bytes
-        for start in range(0, self.len * mytype.bytes, mytype.bytes):
-            stop = start + mytype.bytes - 1
-            for i in range(mytype.bytes):
-                tmp[i] = bytes[start + i]
-            for i in range(mytype.bytes):
-                bytes[stop - i] = tmp[i]
-        self._charbuf_stop()
-
-    def repr__Array(space, self):
-        if self.len == 0:
-            return space.wrap("array('%s')" % self.typecode)
-        elif self.typecode == "c":
-            r = space.repr(array_tostring__Array(space, self))
-            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
-            return space.wrap(s)
-        elif self.typecode == "u":
-            r = space.repr(array_tounicode__Array(space, self))
-            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
-            return space.wrap(s)
-        else:
-            r = space.repr(array_tolist__Array(space, self))
-            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
-            return space.wrap(s)
-
     mytype.w_class = W_Array
-
-    # Annotator seems to mess up if the names are not unique
+    W_Array.constructor = W_Array
     name = 'ArrayType' + mytype.typecode
     W_Array.__name__ = 'W_' + name
-    import re
-    for n, f in locals().items():
-        new, n = re.subn('_Array_', '_%s_' % name, n)
-        if n > 0:
-            f.__name__ = new
-
-    from pypy.objspace.std.sliceobject import W_SliceObject
-    from pypy.objspace.std.listobject import W_ListObject
-    from pypy.objspace.std.unicodeobject import W_UnicodeObject
-    register_all(locals(), globals())
-
 
 for mytype in types.values():
     make_array(mytype)
-
-register_all(locals(), globals())
+del mytype

pypy/module/array/test/test_array.py

 
 class BaseArrayTests:
 
-    
+
     def test_ctor(self):
         assert len(self.array('c')) == 0
         assert len(self.array('i')) == 0
         assert self.array('c', ('h', 'i')).tostring() == 'hi'
         a = self.array('i', [0, 0, 0])
         assert a.tostring() == '\x00' * 3 * a.itemsize
-
         s = self.array('i', [1, 2, 3]).tostring()
         assert '\x00' in s
         assert '\x01' in s
                 return 0
         class incomparable(object):
             pass
-        
+
         for v1, v2, tt in (([1, 2, 3], [1, 3, 2], 'bhilBHIL'),
                          ('abc', 'acb', 'c'),
                          (unicode('abc'), unicode('acb'), 'u')):
                 assert (a >= c) is False
                 assert (c >= a) is True
 
+        a = self.array('i', [-1, 0, 1, 42, 0x7f])
+        assert not a == 2*a
+        assert a != 2*a
+        assert a < 2*a
+        assert a <= 2*a
+        assert not a > 2*a
+        assert not a >= 2*a
+
+
     def test_reduce(self):
         import pickle
         a = self.array('i', [1, 2, 3])
         raises(TypeError, "a * 'hi'")
         raises(TypeError, "'hi' * a")
         raises(TypeError, "a *= 'hi'")
-        
+
         class mulable(object):
             def __mul__(self, other):
                 return "mul"
 
             def __rmul__(self, other):
                 return "rmul"
-        
+
         assert mulable() * self.array('i') == 'mul'
         assert self.array('i') * mulable() == 'rmul'
 
 
             def __getitem__(self, i):
                 return array.__getitem__(self, self._index(i))
-            
+
             def __setitem__(self, i, val):
                 return array.__setitem__(self, self._index(i), val)
 
 
         assert img[3, 25] == 3 * 9
 
-                
+
     def test_override_from(self):
         class mya(self.array):
             def fromlist(self, lst):
     def test_subclass_del(self):
         import array, gc, weakref
         l = []
-        
+
         class A(array.array):
             pass
 

pypy/module/array/test/test_ztranslation.py

+
+from pypy.objspace.fake.checkmodule import checkmodule
+
+def test_checkmodule():
+    checkmodule('array')
+

pypy/module/cpyext/api.py

 def make_wrapper(space, callable):
     "NOT_RPYTHON"
     names = callable.api_func.argnames
-    argtypes_enum_ui = unrolling_iterable(enumerate(zip(callable.api_func.argtypes,
-        [name.startswith("w_") for name in names])))
+    argtypes = callable.api_func.argtypes
+    is_wrapped_list = [name.startswith("w_") for name in names]
     fatal_value = callable.api_func.restype._defl()
 
-    @specialize.ll()
-    def wrapper(*args):
+    lines = []
+    for i, (argtype, is_wrapped) in enumerate(zip(argtypes, is_wrapped_list)):
+        if is_PyObject(argtype) and is_wrapped:
+            new_lines = [
+                'if %(arg)s:',
+                '    %(arg)s = from_ref(space, rffi.cast(PyObject, %(arg)s))',
+                'else:',
+                '    %(arg)s = None',
+            ]
+            for j in range(len(new_lines)):
+                new_lines[j] = new_lines[j] % {'arg': 'arg%d' % i}
+            lines += new_lines
+    middle = '\n            '.join(lines)
+    arg_spec = ", ".join(["arg%d" % i for i in range(len(argtypes))])
+
+    source = py.code.Source("""
+    def wrapper(%(args)s):
         from pypy.module.cpyext.pyobject import make_ref, from_ref
         from pypy.module.cpyext.pyobject import Reference
         retval = fatal_value
         try:
             if not we_are_translated() and DEBUG_WRAPPER:
                 print >>sys.stderr, callable,
-            assert len(args) == len(callable.api_func.argtypes)
-            for i, (typ, is_wrapped) in argtypes_enum_ui:
-                arg = args[i]
-                if is_PyObject(typ) and is_wrapped:
-                    if arg:
-                        arg_conv = from_ref(space, rffi.cast(PyObject, arg))
-                    else:
-                        arg_conv = None
-                else:
-                    arg_conv = arg
-                boxed_args += (arg_conv, )
             state = space.fromcache(State)
+            %(middle)s
             try:
-                result = callable(space, *boxed_args)
+                result = callable(space, %(args)s)
                 if not we_are_translated() and DEBUG_WRAPPER:
                     print >>sys.stderr, " DONE"
             except OperationError, e:
             if failed:
                 error_value = callable.api_func.error_value
                 if error_value is CANNOT_FAIL:
-                    raise SystemError("The function '%s' was not supposed to fail"
-                                      % (callable.__name__,))
+                    raise SystemError("The function '%%s' was not supposed to fail"
+                                      %% (callable.__name__,))
                 retval = error_value
 
             elif is_PyObject(callable.api_func.restype):
                 print str(e)
                 pypy_debug_catch_fatal_exception()
         return retval
+    """ % {"middle": middle, "args": arg_spec})
+    d = {}
+    d.update(locals())
+    d.update(globals())
+    exec source.compile() in d
+    wrapper = d['wrapper']
     callable._always_inline_ = 'try'
     wrapper.__name__ = "wrapper for %r" % (callable, )
     return wrapper
         export_struct(name, struct)
 
     for name, func in FUNCTIONS.iteritems():
-        deco = entrypoint("cpyext", func.argtypes, name, relax=True)
+        deco = entrypoint("cpyext", func.argtypes, name)
         deco(func.get_wrapper(space))
 
     setup_init_functions(eci, translating=True)

pypy/module/micronumpy/arrayimpl/concrete.py

File contents unchanged.

pypy/module/micronumpy/arrayimpl/sort.py

File contents unchanged.

pypy/module/micronumpy/compile.py

 from pypy.module.micronumpy.interp_arrayops import where
 from pypy.module.micronumpy import interp_ufuncs
 from rpython.rlib.objectmodel import specialize, instantiate
+from rpython.rlib.nonconst import NonConstant
 
 
 class BogusBytecode(Exception):
 TWO_ARG_FUNCTIONS = ["dot", 'take']
 THREE_ARG_FUNCTIONS = ['where']
 
+class W_TypeObject(W_Root):
+    def __init__(self, name):
+        self.name = name
+
 class FakeSpace(object):
     w_ValueError = "ValueError"
     w_TypeError = "TypeError"
     w_NotImplementedError = "NotImplementedError"
     w_None = None
 
-    w_bool = "bool"
-    w_int = "int"
-    w_float = "float"
-    w_list = "list"
-    w_long = "long"
-    w_tuple = 'tuple'
-    w_slice = "slice"
-    w_str = "str"
-    w_unicode = "unicode"
-    w_complex = "complex"
-    w_dict = "dict"
+    w_bool = W_TypeObject("bool")
+    w_int = W_TypeObject("int")
+    w_float = W_TypeObject("float")
+    w_list = W_TypeObject("list")
+    w_long = W_TypeObject("long")
+    w_tuple = W_TypeObject('tuple')
+    w_slice = W_TypeObject("slice")
+    w_str = W_TypeObject("str")
+    w_unicode = W_TypeObject("unicode")
+    w_complex = W_TypeObject("complex")
+    w_dict = W_TypeObject("dict")
 
     def __init__(self):
         """NOT_RPYTHON"""
     def issequence_w(self, w_obj):
         return isinstance(w_obj, ListObject) or isinstance(w_obj, W_NDimArray)
 
+    def len(self, w_obj):
+        assert isinstance(w_obj, ListObject)
+        return self.wrap(len(w_obj.items))
+
+    def getattr(self, w_obj, w_attr):
+        return StringObject(NonConstant('foo'))
+
     def isinstance_w(self, w_obj, w_tp):
         return w_obj.tp == w_tp
 

pypy/module/micronumpy/interp_dtype.py

File contents unchanged.

pypy/module/micronumpy/test/test_dtypes.py

File contents unchanged.

pypy/module/micronumpy/test/test_numarray.py

File contents unchanged.

pypy/module/micronumpy/types.py

File contents unchanged.

pypy/module/sys/system.py

 """Information about the current system."""
 from pypy.interpreter import gateway
-from rpython.rlib import rfloat, rbigint
+from rpython.rlib import rbigint, rfloat
 from rpython.rtyper.lltypesystem import rffi
 
 
     return space.call_function(w_float_info, space.newtuple(info_w))
 
 def get_long_info(space):
-    #assert rbigint.SHIFT == 31
     bits_per_digit = rbigint.SHIFT
     sizeof_digit = rffi.sizeof(rbigint.STORE_TYPE)
     info_w = [
     return space.call_function(w_long_info, space.newtuple(info_w))
 
 def get_float_repr_style(space):
-    if rfloat.USE_SHORT_FLOAT_REPR:
-        return space.wrap("short")
-    else:
-        return space.wrap("legacy")
+    return space.wrap("short" if rfloat.USE_SHORT_FLOAT_REPR else "legacy")

pypy/objspace/fake/checkmodule.py

 def checkmodule(*modnames):
     config = get_pypy_config(translating=True)
     space = FakeObjSpace(config)
+    space.setup()
     seeobj_w = []
     for modname in modnames:
         mod = __import__('pypy.module.%s' % modname, None, None, ['__doc__'])

pypy/objspace/fake/objspace.py

         from rpython.rlib.rbigint import rbigint
         return rbigint.fromint(NonConstant(42))
 
+class W_MyListObj(W_MyObject):
+    def append(self, w_other):
+        pass
+
 class W_MyType(W_MyObject):
     def __init__(self):
         self.mro_w = [w_some_obj(), w_some_obj()]
         self._seen_extras = []
         ObjSpace.__init__(self, config=config)
 
+    def _freeze_(self):
+        return True
+
     def float_w(self, w_obj):
         is_root(w_obj)
         return NonConstant(42.5)
     def newlist(self, list_w):
         for w_x in list_w:
             is_root(w_x)
-        return w_some_obj()
+        return W_MyListObj()
 
     def newslice(self, w_start, w_end, w_step):
         is_root(w_start)
         t.buildrtyper().specialize()
         t.checkgraphs()
 
+    def setup(space):
+        for name in (ObjSpace.ConstantTable +
+                     ObjSpace.ExceptionTable +
+                     ['int', 'str', 'float', 'long', 'tuple', 'list',
+                      'dict', 'unicode', 'complex', 'slice', 'bool',
+                      'basestring', 'object', 'bytearray']):
+            setattr(space, 'w_' + name, w_some_obj())
+        space.w_type = w_some_type()
+        #
+        for (name, _, arity, _) in ObjSpace.MethodTable:
+            if name == 'type':
+                continue
+            args = ['w_%d' % i for i in range(arity)]
+            params = args[:]
+            d = {'is_root': is_root,
+                 'w_some_obj': w_some_obj}
+            if name in ('get',):
+                params[-1] += '=None'
+            exec compile2("""\
+                def meth(%s):
+                    %s
+                    return w_some_obj()
+            """ % (', '.join(params),
+                   '; '.join(['is_root(%s)' % arg for arg in args]))) in d
+            meth = func_with_new_name(d['meth'], name)
+            setattr(space, name, meth)
+        #
+        for name in ObjSpace.IrregularOpTable:
+            assert hasattr(space, name)    # missing?
 
-def setup():
-    for name in (ObjSpace.ConstantTable +
-                 ObjSpace.ExceptionTable +
-                 ['int', 'str', 'float', 'long', 'tuple', 'list',
-                  'dict', 'unicode', 'complex', 'slice', 'bool',
-                  'basestring', 'object', 'bytearray']):
-        setattr(FakeObjSpace, 'w_' + name, w_some_obj())
-    FakeObjSpace.w_type = w_some_type()
-    #
-    for (name, _, arity, _) in ObjSpace.MethodTable:
-        if name == 'type':
-            continue
-        args = ['w_%d' % i for i in range(arity)]
-        params = args[:]
-        d = {'is_root': is_root,
-             'w_some_obj': w_some_obj}
-        if name in ('get',):
-            params[-1] += '=None'
-        exec compile2("""\
-            def meth(self, %s):
-                %s
-                return w_some_obj()
-        """ % (', '.join(params),
-               '; '.join(['is_root(%s)' % arg for arg in args]))) in d
-        meth = func_with_new_name(d['meth'], name)
-        setattr(FakeObjSpace, name, meth)
-    #
-    for name in ObjSpace.IrregularOpTable:
-        assert hasattr(FakeObjSpace, name)    # missing?
-
-setup()
 
 # ____________________________________________________________
 

pypy/objspace/std/dictmultiobject.py

 import py, sys
 from pypy.objspace.std.model import registerimplementation, W_Object
 from pypy.objspace.std.register_all import register_all
-from pypy.objspace.std.settype import set_typedef as settypedef
-from pypy.objspace.std.frozensettype import frozenset_typedef as frozensettypedef
+from pypy.objspace.std.setobject import set_typedef as settypedef
+from pypy.objspace.std.setobject import frozenset_typedef as frozensettypedef
 from pypy.interpreter.error import OperationError, operationerrfmt
 from pypy.interpreter.signature import Signature
 

pypy/objspace/std/frozensettype.py

-from pypy.interpreter import gateway
-from pypy.interpreter.error import OperationError
-from pypy.objspace.std.register_all import register_all
-from pypy.objspace.std.stdtypedef import StdTypeDef, SMM
-
-
-frozenset_copy                  = SMM('copy', 1,
-                                      doc='Return a shallow copy of a set.')
-frozenset_difference            = SMM('difference', 1, varargs_w=True,
-                                      doc='Return a new set with elements in'
-                                          ' the set that are not in the others.')
-frozenset_intersection          = SMM('intersection', 1, varargs_w=True,
-                                      doc='Return a new set with elements common'
-                                          ' to the set and all others.')
-frozenset_issubset              = SMM('issubset', 2,
-                                      doc='Report whether another set contains'
-                                          ' this set.')
-frozenset_issuperset            = SMM('issuperset', 2,
-                                      doc='Report whether this set contains'
-                                          ' another set.')
-frozenset_symmetric_difference  = SMM('symmetric_difference', 2,
-                                      doc='Return the symmetric difference of'
-                                          ' two sets as a new set.\n\n(i.e.'
-                                          ' all elements that are in exactly'
-                                          ' one of the sets.)')
-frozenset_union                 = SMM('union', 1, varargs_w=True,
-                                      doc='Return a new set with elements'
-                                          ' from the set and all others.')
-frozenset_reduce                = SMM('__reduce__',1,
-                                      doc='Return state information for'
-                                          ' pickling.')
-# 2.6 methods
-frozenset_isdisjoint            = SMM('isdisjoint', 2,
-                                      doc='Return True if two sets have a'
-                                          ' null intersection.')
-
-register_all(vars(), globals())
-
-def descr__frozenset__new__(space, w_frozensettype, w_iterable=None):
-    from pypy.objspace.std.setobject import W_FrozensetObject
-    if (space.is_w(w_frozensettype, space.w_frozenset) and
-        w_iterable is not None and type(w_iterable) is W_FrozensetObject):
-        return w_iterable
-    w_obj = space.allocate_instance(W_FrozensetObject, w_frozensettype)
-    W_FrozensetObject.__init__(w_obj, space, w_iterable)
-    return w_obj
-
-frozenset_typedef = StdTypeDef("frozenset",
-    __doc__ = """frozenset(iterable) --> frozenset object
-
-Build an immutable unordered collection.""",
-    __new__ = gateway.interp2app(descr__frozenset__new__),
-    )
-
-frozenset_typedef.registermethods(globals())

pypy/objspace/std/model.py

             from pypy.objspace.std.inttype    import int_typedef
             from pypy.objspace.std.floattype  import float_typedef
             from pypy.objspace.std.complextype  import complex_typedef
-            from pypy.objspace.std.settype import set_typedef
-            from pypy.objspace.std.frozensettype import frozenset_typedef
             from pypy.objspace.std.tupletype  import tuple_typedef
             from pypy.objspace.std.listobject   import list_typedef
             from pypy.objspace.std.dicttype   import dict_typedef
         from pypy.objspace.std import intobject
         from pypy.objspace.std import floatobject
         from pypy.objspace.std import complexobject
-        from pypy.objspace.std import setobject
         from pypy.objspace.std import tupleobject
         from pypy.objspace.std import listobject
         from pypy.objspace.std import dictmultiobject
+        from pypy.objspace.std import setobject
         from pypy.objspace.std import stringobject
         from pypy.objspace.std import bytearrayobject
         from pypy.objspace.std import typeobject
         import pypy.objspace.std.default # register a few catch-all multimethods
 
         import pypy.objspace.std.marshal_impl # install marshal multimethods
-        if config.objspace.usemodules.array:
-            import pypy.module.array
+
+        # not-multimethod based types
+
+        self.pythontypes.append(setobject.W_SetObject.typedef)
+        self.pythontypes.append(setobject.W_FrozensetObject.typedef)
 
         # the set of implementation types
         self.typeorder = {
             longobject.W_LongObject: [],
             noneobject.W_NoneObject: [],
             complexobject.W_ComplexObject: [],
-            setobject.W_BaseSetObject: [],
-            setobject.W_SetObject: [],
-            setobject.W_FrozensetObject: [],
-            setobject.W_SetIterObject: [],
             iterobject.W_SeqIterObject: [],
             iterobject.W_FastListIterObject: [],
             iterobject.W_FastTupleIterObject: [],
             (complexobject.W_ComplexObject,
                     complexobject.delegate_Float2Complex),
             ]
-        self.typeorder[setobject.W_SetObject] += [
-            (setobject.W_BaseSetObject, None)
-            ]
-        self.typeorder[setobject.W_FrozensetObject] += [
-            (setobject.W_BaseSetObject, None)
-            ]
+
         self.typeorder[stringobject.W_StringObject] += [
             (unicodeobject.W_UnicodeObject, unicodeobject.delegate_String2Unicode),
             ]
             s += ' instance of %s' % self.w__class__
         return '<%s>' % s
 
-    def unwrap(w_self, space):
-        raise UnwrapError, 'cannot unwrap %r' % (w_self,)
+    def unwrap(self, space):
+        raise UnwrapError('cannot unwrap %r' % self)
+
 
 class UnwrapError(Exception):
     pass
         mm.dispatch_tree = merge(self.dispatch_tree, other.dispatch_tree)
         return mm
 
-NOT_MULTIMETHODS = dict.fromkeys(
+NOT_MULTIMETHODS = set(
     ['delattr', 'delete', 'get', 'id', 'inplace_div', 'inplace_floordiv',
      'inplace_lshift', 'inplace_mod', 'inplace_pow', 'inplace_rshift',
      'inplace_truediv', 'is_', 'set', 'setattr', 'type', 'userdel',

pypy/objspace/std/setobject.py

-from pypy.objspace.std.model import registerimplementation, W_Object
-from pypy.objspace.std.register_all import register_all
+from pypy.interpreter import gateway
 from pypy.interpreter.error import OperationError
-from pypy.interpreter import gateway
-from pypy.objspace.std.settype import set_typedef as settypedef
-from pypy.objspace.std.frozensettype import frozenset_typedef as frozensettypedef
 from pypy.interpreter.signature import Signature
-from pypy.interpreter.generator import GeneratorIterator
-from pypy.objspace.std.listobject import W_ListObject
+from pypy.interpreter.baseobjspace import W_Root
 from pypy.objspace.std.intobject import W_IntObject
+from pypy.objspace.std.stdtypedef import StdTypeDef
 from pypy.objspace.std.stringobject import W_StringObject
 from pypy.objspace.std.unicodeobject import W_UnicodeObject
 
 from rpython.rlib.rarithmetic import intmask, r_uint
 from rpython.rlib import rerased, jit
 
+
 UNROLL_CUTOFF = 5
 
-class W_BaseSetObject(W_Object):
+