[pypy-commit] pypy py3k: merge default, and adapt/kill the py3k SMM additions

pjenvey noreply at buildbot.pypy.org
Tue May 14 21:29:41 CEST 2013


Author: Philip Jenvey <pjenvey at underboss.org>
Branch: py3k
Changeset: r64102:e1281f255e98
Date: 2013-05-14 12:28 -0700
http://bitbucket.org/pypy/pypy/changeset/e1281f255e98/

Log:	merge default, and adapt/kill the py3k SMM additions

diff too long, truncating to 2000 out of 2139 lines

diff --git a/pypy/goal/targetpypystandalone.py b/pypy/goal/targetpypystandalone.py
--- a/pypy/goal/targetpypystandalone.py
+++ b/pypy/goal/targetpypystandalone.py
@@ -83,24 +83,40 @@
     # should be used as sparsely as possible, just to register callbacks
 
     from rpython.rlib.entrypoint import entrypoint
-    from rpython.rtyper.lltypesystem import rffi
+    from rpython.rtyper.lltypesystem import rffi, lltype
 
-    @entrypoint('main', [rffi.CCHARP], c_name='pypy_setup_home')
-    def pypy_setup_home(ll_home):
+    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
         if ll_home:
             home = rffi.charp2str(ll_home)
         else:
             home = pypydir
-        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__'),
                                     space.wrap('__import__'))
             space.call_function(import_, space.wrap('site'))
             return 0
-        except OperationError:
+        except OperationError, e:
+            if verbose:
+                debug("OperationError:")
+                debug(" operror-type: " + e.w_type.getname(space))
+                debug(" operror-value: " + space.str_w(space.str(e.get_w_value(space))))
             return 1
 
     @entrypoint('main', [rffi.CCHARP], c_name='pypy_execute_source')
diff --git a/pypy/interpreter/test/test_targetpypy.py b/pypy/interpreter/test/test_targetpypy.py
--- a/pypy/interpreter/test/test_targetpypy.py
+++ b/pypy/interpreter/test/test_targetpypy.py
@@ -24,5 +24,5 @@
     # did not crash - the same globals
     pypy_setup_home = d['pypy_setup_home']
     lls = rffi.str2charp(__file__)
-    pypy_setup_home(lls)
+    pypy_setup_home(lls, 1)
     lltype.free(lls, flavor='raw')
diff --git a/pypy/module/__pypy__/interp_magic.py b/pypy/module/__pypy__/interp_magic.py
--- a/pypy/module/__pypy__/interp_magic.py
+++ b/pypy/module/__pypy__/interp_magic.py
@@ -1,4 +1,3 @@
-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
@@ -63,7 +62,7 @@
     func.getcode().hidden_applevel = True
     return w_func
 
- at unwrap_spec(ObjSpace, W_Root, str)
+ at unwrap_spec(meth=str)
 def lookup_special(space, w_obj, meth):
     """Lookup up a special method on an object."""
     w_descr = space.lookup(w_obj, meth)
diff --git a/pypy/module/array/__init__.py b/pypy/module/array/__init__.py
--- a/pypy/module/array/__init__.py
+++ b/pypy/module/array/__init__.py
@@ -1,12 +1,5 @@
 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',
diff --git a/pypy/module/array/interp_array.py b/pypy/module/array/interp_array.py
--- a/pypy/module/array/interp_array.py
+++ b/pypy/module/array/interp_array.py
@@ -2,17 +2,13 @@
 
 from pypy.interpreter.buffer import RWBuffer
 from pypy.interpreter.error import OperationError
-from pypy.interpreter.gateway import interp2app, unwrap_spec
+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.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
 
 
@@ -42,9 +38,10 @@
                     if isinstance(w_initializer, W_ArrayBase):
                         a.extend(w_initializer, True)
                     else:
-                        a.fromstring(space.bufferstr_w(w_initializer))
+                        a.descr_fromstring(space,
+                                           space.bufferstr_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
@@ -55,33 +52,6 @@
     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_tobytes = SMM('tobytes', 1)
-array_fromstring = SMM('fromstring', 2)
-array_frombytes = SMM('frombytes', 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_ex = SMM('__reduce_ex__', 2)
-array_copy = SMM('__copy__', 1)
-array_byteswap = SMM('byteswap', 1)
-
-
 def descr_itemsize(space, self):
     return space.wrap(self.itemsize)
 
@@ -89,28 +59,512 @@
 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_False
+        return space.w_True
+    if arr1.len > arr2.len:
+        return space.w_False
+    return space.w_True
 
-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() -> bytes
+
+        Convert the array to an array of machine values and return the
+        bytes representation.
+
+        This method is deprecated. Use tobytes instead.
+        """
+        msg = "tostring() is deprecated. Use tobytes() instead."
+        space.warn(space.wrap(msg), space.w_DeprecationWarning)
+        return self.descr_tobytes(space)
+
+    def descr_tobytes(self, space):
+        """tobytes() -> bytes
+
+        Convert the array to an array of machine values and return the
+        bytes representation.
+        """
+        cbuf = self._charbuf_start()
+        s = rffi.charpsize2str(cbuf, self.len * self.itemsize)
+        self._charbuf_stop()
+        return self.space.wrapbytes(s)
+
+    @unwrap_spec(s='bufferstr_or_u')
+    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).
+
+        This method is deprecated. Use frombytes instead.
+        """
+        msg = "fromstring() is deprecated. Use frombytes() instead."
+        space.warn(space.wrap(msg), self.space.w_DeprecationWarning)
+        self.descr_frombytes(space, s)
+
+    @unwrap_spec(s='bufferstr')
+    def descr_frombytes(self, space, s):
+        """frombytes(bytestring)
+
+        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(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.bytes_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_frombytes(space, item)
+            msg = "not enough items in file"
+            raise OperationError(space.w_EOFError, space.wrap(msg))
+        self.descr_fromstring(space, item)
+
+    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_tobytes(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])
+
+    @unwrap_spec(protocol=int)
+    def descr_reduce_ex(self, space, protocol):
+        """Return state information for pickling."""
+        try:
+            w_dict = space.getattr(self, space.wrap('__dict__'))
+        except OperationError:
+            w_dict = space.w_None
+        from pypy.module.array import reconstructor
+        mformat_code = reconstructor.typecode_to_mformat_code(self.typecode)
+        if protocol < 3 or mformat_code == reconstructor.UNKNOWN_FORMAT:
+            # Convert the array to a list if we got something weird
+            # (e.g., non-IEEE floats), or we are pickling the array
+            # using a Python 2.x compatible protocol.
+            #
+            # It is necessary to use a list representation for Python
+            # 2.x compatible pickle protocol, since Python 2's str
+            # objects are unpickled as unicode by Python 3. Thus it is
+            # impossible to make arrays unpicklable by Python 3 by
+            # using their memory representation, unless we resort to
+            # ugly hacks such as coercing unicode objects to bytes in
+            # array_reconstructor.
+            w_list = self.descr_tolist(space)
+            return space.newtuple([
+                    space.type(self),
+                    space.newtuple([space.wrap(self.typecode), w_list]),
+                    w_dict])
+
+        w_bytes = self.descr_tobytes(space)
+        w_array_reconstructor = space.fromcache(State).w_array_reconstructor
+        return space.newtuple([
+                w_array_reconstructor,
+                space.newtuple([space.type(self),
+                                space.wrap(self.typecode),
+                                space.wrap(mformat_code),
+                                w_bytes]),
+                w_dict])
+
+    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_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_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_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_iter(self, space):
+        return space.wrap(ArrayIterator(self))
+
+    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 == "u":
+            r = space.repr(self.descr_tounicode(space))
+            s = u"array('u', %s)" % space.unicode_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),
+    __setitem__ = interp2app(W_ArrayBase.descr_setitem),
+    __delitem__ = interp2app(W_ArrayBase.descr_delitem),
+
+    __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),
+    __iter__ = interp2app(W_ArrayBase.descr_iter),
+    __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),
+    tobytes = interp2app(W_ArrayBase.descr_tobytes),
+    frombytes = interp2app(W_ArrayBase.descr_frombytes),
+
+    buffer_info = interp2app(W_ArrayBase.descr_buffer_info),
+    __copy__ = interp2app(W_ArrayBase.descr_copy),
+    __reduce_ex__ = interp2app(W_ArrayBase.descr_reduce_ex),
+    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
@@ -202,14 +656,10 @@
         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):
@@ -316,26 +766,6 @@
                 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):
@@ -359,6 +789,9 @@
         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)
 
@@ -370,157 +803,180 @@
                 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 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_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_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_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 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 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(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_extend__Array_ANY(space, self, w_iterable):
-        self.extend(w_iterable)
+        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
 
-    # 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)
+        # 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')
 
-    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))
+        # Add and mul methods
 
-    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_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_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_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_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 descr_mul(self, space, w_repeat):
+            return _mul_helper(space, self, w_repeat, False)
 
-    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)
-
-    # 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:
@@ -559,218 +1015,17 @@
                 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_frombytes__Array_ANY(space, self, w_s):
-        self.fromstring(space.bufferstr_w(w_s))
-
-    def array_fromstring__Array_ANY(space, self, w_s):
-        msg = "fromstring() is deprecated. Use frombytes() instead."
-        space.warn(space.wrap(msg), self.space.w_DeprecationWarning)
-        self.fromstring(space.str_w(w_s))
-
-    def array_tobytes__Array(space, self):
-        cbuf = self._charbuf_start()
-        s = rffi.charpsize2str(cbuf, self.len * mytype.bytes)
-        self._charbuf_stop()
-        return self.space.wrapbytes(s)
-
-    def array_tostring__Array(space, self):
-        msg = "tostring() is deprecated. Use tobytes() instead."
-        space.warn(space.wrap(msg), space.w_DeprecationWarning)
-        return array_tobytes__Array(space, self)
-
-    def array_fromfile__Array_ANY_ANY(space, self, w_f, w_n):
-        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.bytes_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.wrapbytes(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):
-        w_s = array_tobytes__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 iter__Array(space, self):
-        return space.wrap(ArrayIterator(self))
-
-    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_ex__Array_ANY(space, self, w_protocol):
-        protocol = space.int_w(w_protocol)
-        try:
-            w_dict = space.getattr(self, space.wrap('__dict__'))
-        except OperationError:
-            w_dict = space.w_None
-        from pypy.module.array import reconstructor
-        mformat_code = reconstructor.typecode_to_mformat_code(mytype.typecode)
-        if protocol < 3 or mformat_code == reconstructor.UNKNOWN_FORMAT:
-            # Convert the array to a list if we got something weird
-            # (e.g., non-IEEE floats), or we are pickling the array
-            # using a Python 2.x compatible protocol.
-            #
-            # It is necessary to use a list representation for Python
-            # 2.x compatible pickle protocol, since Python 2's str
-            # objects are unpickled as unicode by Python 3. Thus it is
-            # impossible to make arrays unpicklable by Python 3 by
-            # using their memory representation, unless we resort to
-            # ugly hacks such as coercing unicode objects to bytes in
-            # array_reconstructor.
-            w_list = array_tolist__Array(space, self)
-            return space.newtuple([
-                    space.type(self),
-                    space.newtuple([space.wrap(mytype.typecode), w_list]),
-                    w_dict])
-            
-        w_bytes = array_tobytes__Array(space, self)
-        w_array_reconstructor = space.fromcache(State).w_array_reconstructor
-        return space.newtuple([
-                w_array_reconstructor,
-                space.newtuple([space.type(self),
-                                space.wrap(mytype.typecode),
-                                space.wrap(mformat_code),
-                                w_bytes]),
-                w_dict])
-
-    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 == "u":
-            r = space.repr(array_tounicode__Array(space, self))
-            s = u"array('u', %s)" % space.unicode_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)
-
+del mytype
 
 class State:
     def __init__(self, space):
         w_module = space.getbuiltinmodule('array')
         self.w_array_reconstructor = space.getattr(
             w_module, space.wrap("_array_reconstructor"))
-
diff --git a/pypy/module/array/test/test_array.py b/pypy/module/array/test/test_array.py
--- a/pypy/module/array/test/test_array.py
+++ b/pypy/module/array/test/test_array.py
@@ -19,7 +19,7 @@
 
 class BaseArrayTests:
 
-    
+
     def test_ctor(self):
         assert len(self.array('i')) == 0
 
@@ -373,7 +373,6 @@
 
         a = self.array('i', [0, 0, 0])
         assert a.tobytes() == b'\x00' * 3 * a.itemsize
-
         s = self.array('i', [1, 2, 3]).tobytes()
         assert 0x00 in s
         assert 0x01 in s
@@ -484,7 +483,7 @@
                 return True
         class incomparable(object):
             pass
-        
+
         for v1, v2, tt in (([1, 2, 3], [1, 3, 2], 'bhilBHIL'),
                          ('abc', 'acb', 'u')):
             for t in tt:
@@ -634,14 +633,14 @@
         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'
 
@@ -753,7 +752,7 @@
 
             def __getitem__(self, i):
                 return array.__getitem__(self, self._index(i))
-            
+
             def __setitem__(self, i, val):
                 return array.__setitem__(self, self._index(i), val)
 
@@ -767,7 +766,7 @@
 
         assert img[3, 25] == 3 * 9
 
-                
+
     def test_override_from(self):
         class mya(self.array):
             def fromlist(self, lst):
@@ -836,7 +835,7 @@
     def test_subclass_del(self):
         import array, gc, weakref
         l = []
-        
+
         class A(array.array):
             pass
 
diff --git a/pypy/module/array/test/test_ztranslation.py b/pypy/module/array/test/test_ztranslation.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/array/test/test_ztranslation.py
@@ -0,0 +1,6 @@
+
+from pypy.objspace.fake.checkmodule import checkmodule
+
+def test_checkmodule():
+    checkmodule('array')
+
diff --git a/pypy/module/cpyext/api.py b/pypy/module/cpyext/api.py
--- a/pypy/module/cpyext/api.py
+++ b/pypy/module/cpyext/api.py
@@ -545,12 +545,27 @@
 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
@@ -558,20 +573,10 @@
         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:
@@ -593,8 +598,8 @@
             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):
@@ -622,6 +627,12 @@
                 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
@@ -1016,7 +1027,7 @@
         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)
diff --git a/pypy/objspace/std/model.py b/pypy/objspace/std/model.py
--- a/pypy/objspace/std/model.py
+++ b/pypy/objspace/std/model.py
@@ -79,8 +79,6 @@
         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
 
         # the set of implementation types
         self.typeorder = {
diff --git a/rpython/annotator/description.py b/rpython/annotator/description.py
--- a/rpython/annotator/description.py
+++ b/rpython/annotator/description.py
@@ -215,9 +215,8 @@
         if len(self._cache) != 1:
             raise NoStandardGraph(self)
         [graph] = self._cache.values()
-        relax_sig_check = getattr(self.pyobj, "relax_sig_check", False)
         if (graph.signature != self.signature or
-            graph.defaults  != self.defaults) and not relax_sig_check:
+            graph.defaults  != self.defaults):
             raise NoStandardGraph(self)
         return graph
 
diff --git a/rpython/annotator/test/test_annrpython.py b/rpython/annotator/test/test_annrpython.py
--- a/rpython/annotator/test/test_annrpython.py
+++ b/rpython/annotator/test/test_annrpython.py
@@ -3542,16 +3542,6 @@
         s = a.build_types(f, [int])
         assert s.knowntype is int
 
-    def test_relax(self):
-        def f(*args):
-            return args[0] + args[1]
-        f.relax_sig_check = True
-        def g(x):
-            return f(x, x - x)
-        a = self.RPythonAnnotator()
-        s = a.build_types(g, [int])
-        assert a.bookkeeper.getdesc(f).getuniquegraph()
-
     def test_cannot_raise_ll_exception(self):
         from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
         #
diff --git a/rpython/jit/metainterp/blackhole.py b/rpython/jit/metainterp/blackhole.py
--- a/rpython/jit/metainterp/blackhole.py
+++ b/rpython/jit/metainterp/blackhole.py
@@ -1,7 +1,8 @@
 from rpython.jit.codewriter import heaptracker, longlong
 from rpython.jit.codewriter.jitcode import JitCode, SwitchDictDescr
 from rpython.jit.metainterp.compile import ResumeAtPositionDescr
-from rpython.jit.metainterp.jitexc import JitException, get_llexception, reraise
+from rpython.jit.metainterp.jitexc import get_llexception, reraise
+from rpython.jit.metainterp import jitexc
 from rpython.rlib import longlong2float
 from rpython.rlib.debug import ll_assert, make_sure_not_resized
 from rpython.rlib.objectmodel import we_are_translated
@@ -25,7 +26,7 @@
 LONGLONG_TYPECODE = 'i' if longlong.is_64_bit else 'f'
 
 
-class LeaveFrame(JitException):
+class LeaveFrame(jitexc.JitException):
     pass
 
 class MissingValue(object):
@@ -306,7 +307,7 @@
                 self.dispatch_loop(self, self.jitcode.code, self.position)
             except LeaveFrame:
                 break
-            except JitException:
+            except jitexc.JitException:
                 raise     # go through
             except Exception, e:
                 lle = get_llexception(self.cpu, e)
@@ -902,8 +903,7 @@
     @arguments("self", "i", "I", "R", "F", "I", "R", "F")
     def bhimpl_jit_merge_point(self, jdindex, *args):
         if self.nextblackholeinterp is None:    # we are the last level
-            CRN = self.builder.metainterp_sd.ContinueRunningNormally
-            raise CRN(*args)
+            raise jitexc.ContinueRunningNormally(*args)
             # Note that the case above is an optimization: the case
             # below would work too.  But it keeps unnecessary stuff on
             # the stack; the solution above first gets rid of the blackhole
@@ -1400,7 +1400,7 @@
             # we now proceed to interpret the bytecode in this frame
             self.run()
         #
-        except JitException, e:
+        except jitexc.JitException, e:
             raise     # go through
         except Exception, e:
             # if we get an exception, return it to the caller frame
@@ -1495,20 +1495,20 @@
         sd = self.builder.metainterp_sd
         kind = self._return_type
         if kind == 'v':
-            raise sd.DoneWithThisFrameVoid()
+            raise jitexc.DoneWithThisFrameVoid()
         elif kind == 'i':
-            raise sd.DoneWithThisFrameInt(self.get_tmpreg_i())
+            raise jitexc.DoneWithThisFrameInt(self.get_tmpreg_i())
         elif kind == 'r':
-            raise sd.DoneWithThisFrameRef(self.cpu, self.get_tmpreg_r())
+            raise jitexc.DoneWithThisFrameRef(self.cpu, self.get_tmpreg_r())
         elif kind == 'f':
-            raise sd.DoneWithThisFrameFloat(self.get_tmpreg_f())
+            raise jitexc.DoneWithThisFrameFloat(self.get_tmpreg_f())
         else:
             assert False
 
     def _exit_frame_with_exception(self, e):
         sd = self.builder.metainterp_sd
         e = lltype.cast_opaque_ptr(llmemory.GCREF, e)
-        raise sd.ExitFrameWithExceptionRef(self.cpu, e)
+        raise jitexc.ExitFrameWithExceptionRef(self.cpu, e)
 
     def _handle_jitexception_in_portal(self, e):
         # This case is really rare, but can occur if
@@ -1558,23 +1558,23 @@
     while True:
         try:
             current_exc = blackholeinterp._resume_mainloop(current_exc)
-        except JitException, e:
+        except jitexc.JitException as e:
             blackholeinterp, current_exc = _handle_jitexception(
                 blackholeinterp, e)
         blackholeinterp.builder.release_interp(blackholeinterp)
         blackholeinterp = blackholeinterp.nextblackholeinterp
 
-def _handle_jitexception(blackholeinterp, jitexc):
+def _handle_jitexception(blackholeinterp, exc):
     # See comments in _handle_jitexception_in_portal().
     while not blackholeinterp.jitcode.is_portal:
         blackholeinterp.builder.release_interp(blackholeinterp)
         blackholeinterp = blackholeinterp.nextblackholeinterp
     if blackholeinterp.nextblackholeinterp is None:
         blackholeinterp.builder.release_interp(blackholeinterp)
-        raise jitexc     # bottommost entry: go through
+        raise exc     # bottommost entry: go through
     # We have reached a recursive portal level.
     try:
-        blackholeinterp._handle_jitexception_in_portal(jitexc)
+        blackholeinterp._handle_jitexception_in_portal(exc)
     except Exception, e:
         # It raised a general exception (it should not be a JitException here).
         lle = get_llexception(blackholeinterp.cpu, e)
diff --git a/rpython/jit/metainterp/compile.py b/rpython/jit/metainterp/compile.py
--- a/rpython/jit/metainterp/compile.py
+++ b/rpython/jit/metainterp/compile.py
@@ -12,7 +12,7 @@
 from rpython.jit.metainterp.history import TreeLoop, Box, JitCellToken, TargetToken
 from rpython.jit.metainterp.history import AbstractFailDescr, BoxInt
 from rpython.jit.metainterp.history import BoxPtr, BoxFloat, ConstInt
-from rpython.jit.metainterp import history, resume
+from rpython.jit.metainterp import history, resume, jitexc
 from rpython.jit.metainterp.optimize import InvalidLoop
 from rpython.jit.metainterp.inliner import Inliner
 from rpython.jit.metainterp.resume import NUMBERING, PENDINGFIELDSP, ResumeDataDirectReader
@@ -415,32 +415,32 @@
 class DoneWithThisFrameDescrVoid(_DoneWithThisFrameDescr):
     def handle_fail(self, deadframe, metainterp_sd, jitdriver_sd):
         assert jitdriver_sd.result_type == history.VOID
-        raise metainterp_sd.DoneWithThisFrameVoid()
+        raise jitexc.DoneWithThisFrameVoid()
 
 class DoneWithThisFrameDescrInt(_DoneWithThisFrameDescr):
     def handle_fail(self, deadframe, metainterp_sd, jitdriver_sd):
         assert jitdriver_sd.result_type == history.INT
         result = metainterp_sd.cpu.get_int_value(deadframe, 0)
-        raise metainterp_sd.DoneWithThisFrameInt(result)
+        raise jitexc.DoneWithThisFrameInt(result)
 
 class DoneWithThisFrameDescrRef(_DoneWithThisFrameDescr):
     def handle_fail(self, deadframe, metainterp_sd, jitdriver_sd):
         assert jitdriver_sd.result_type == history.REF
         cpu = metainterp_sd.cpu
         result = cpu.get_ref_value(deadframe, 0)
-        raise metainterp_sd.DoneWithThisFrameRef(cpu, result)
+        raise jitexc.DoneWithThisFrameRef(cpu, result)
 
 class DoneWithThisFrameDescrFloat(_DoneWithThisFrameDescr):
     def handle_fail(self, deadframe, metainterp_sd, jitdriver_sd):
         assert jitdriver_sd.result_type == history.FLOAT
         result = metainterp_sd.cpu.get_float_value(deadframe, 0)
-        raise metainterp_sd.DoneWithThisFrameFloat(result)
+        raise jitexc.DoneWithThisFrameFloat(result)
 
 class ExitFrameWithExceptionDescrRef(_DoneWithThisFrameDescr):
     def handle_fail(self, deadframe, metainterp_sd, jitdriver_sd):
         cpu = metainterp_sd.cpu
         value = cpu.get_ref_value(deadframe, 0)
-        raise metainterp_sd.ExitFrameWithExceptionRef(cpu, value)
+        raise jitexc.ExitFrameWithExceptionRef(cpu, value)
 
 
 class TerminatingLoopToken(JitCellToken): # FIXME: kill?
@@ -865,7 +865,7 @@
         if not exception:
             exception = cast_instance_to_gcref(memory_error)
         assert exception, "PropagateExceptionDescr: no exception??"
-        raise metainterp_sd.ExitFrameWithExceptionRef(cpu, exception)
+        raise jitexc.ExitFrameWithExceptionRef(cpu, exception)
 
 def compile_tmp_callback(cpu, jitdriver_sd, greenboxes, redargtypes,
                          memory_manager=None):
diff --git a/rpython/jit/metainterp/jitexc.py b/rpython/jit/metainterp/jitexc.py
--- a/rpython/jit/metainterp/jitexc.py
+++ b/rpython/jit/metainterp/jitexc.py
@@ -1,8 +1,9 @@
 from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
-from rpython.rtyper.lltypesystem import rclass
+from rpython.rtyper.lltypesystem import lltype, rclass
 from rpython.rtyper.llinterp import LLException
 from rpython.rlib.objectmodel import we_are_translated
+from rpython.jit.codewriter import longlong
 
 
 class JitException(Exception):
@@ -12,6 +13,54 @@
     """
     _go_through_llinterp_uncaught_ = True     # ugh
 
+class DoneWithThisFrameVoid(JitException):
+    def __str__(self):
+        return 'DoneWithThisFrameVoid()'
+
+class DoneWithThisFrameInt(JitException):
+    def __init__(self, result):
+        assert lltype.typeOf(result) is lltype.Signed
+        self.result = result
+    def __str__(self):
+        return 'DoneWithThisFrameInt(%s)' % (self.result,)
+
+class DoneWithThisFrameRef(JitException):
+    def __init__(self, cpu, result):
+        assert lltype.typeOf(result) == cpu.ts.BASETYPE
+        self.result = result
+    def __str__(self):
+        return 'DoneWithThisFrameRef(%s)' % (self.result,)
+
+class DoneWithThisFrameFloat(JitException):
+    def __init__(self, result):
+        assert lltype.typeOf(result) is longlong.FLOATSTORAGE
+        self.result = result
+    def __str__(self):
+        return 'DoneWithThisFrameFloat(%s)' % (self.result,)
+
+class ExitFrameWithExceptionRef(JitException):
+    def __init__(self, cpu, value):
+        assert lltype.typeOf(value) == cpu.ts.BASETYPE
+        self.value = value
+    def __str__(self):
+        return 'ExitFrameWithExceptionRef(%s)' % (self.value,)
+
+class ContinueRunningNormally(JitException):
+    def __init__(self, gi, gr, gf, ri, rr, rf):
+        # the six arguments are: lists of green ints, greens refs,
+        # green floats, red ints, red refs, and red floats.
+        self.green_int = gi
+        self.green_ref = gr
+        self.green_float = gf
+        self.red_int = ri
+        self.red_ref = rr
+        self.red_float = rf
+    def __str__(self):
+        return 'ContinueRunningNormally(%s, %s, %s, %s, %s, %s)' % (
+            self.green_int, self.green_ref, self.green_float,
+            self.red_int, self.red_ref, self.red_float)
+
+
 def _get_standard_error(rtyper, Class):
     exdata = rtyper.getexceptiondata()
     clsdef = rtyper.annotator.bookkeeper.getuniqueclassdef(Class)
diff --git a/rpython/jit/metainterp/pyjitpl.py b/rpython/jit/metainterp/pyjitpl.py
--- a/rpython/jit/metainterp/pyjitpl.py
+++ b/rpython/jit/metainterp/pyjitpl.py
@@ -5,11 +5,10 @@
 from rpython.jit.codewriter import heaptracker
 from rpython.jit.codewriter.effectinfo import EffectInfo
 from rpython.jit.codewriter.jitcode import JitCode, SwitchDictDescr
-from rpython.jit.metainterp import history, compile, resume, executor
+from rpython.jit.metainterp import history, compile, resume, executor, jitexc
 from rpython.jit.metainterp.heapcache import HeapCache
 from rpython.jit.metainterp.history import (Const, ConstInt, ConstPtr,
     ConstFloat, Box, TargetToken)
-from rpython.jit.metainterp.jitexc import JitException, get_llexception
 from rpython.jit.metainterp.jitprof import EmptyProfiler
 from rpython.jit.metainterp.logger import Logger
 from rpython.jit.metainterp.optimizeopt.util import args_dict_box
@@ -1705,13 +1704,13 @@
             result_type = self.jitdriver_sd.result_type
             if result_type == history.VOID:
                 assert resultbox is None
-                raise sd.DoneWithThisFrameVoid()
+                raise jitexc.DoneWithThisFrameVoid()
             elif result_type == history.INT:
-                raise sd.DoneWithThisFrameInt(resultbox.getint())
+                raise jitexc.DoneWithThisFrameInt(resultbox.getint())
             elif result_type == history.REF:
-                raise sd.DoneWithThisFrameRef(self.cpu, resultbox.getref_base())
+                raise jitexc.DoneWithThisFrameRef(self.cpu, resultbox.getref_base())
             elif result_type == history.FLOAT:
-                raise sd.DoneWithThisFrameFloat(resultbox.getfloatstorage())
+                raise jitexc.DoneWithThisFrameFloat(resultbox.getfloatstorage())
             else:
                 assert False
 
@@ -1734,7 +1733,7 @@
             self.compile_exit_frame_with_exception(excvaluebox)
         except SwitchToBlackhole, stb:
             self.aborted_tracing(stb.reason)
-        raise self.staticdata.ExitFrameWithExceptionRef(self.cpu, excvaluebox.getref_base())
+        raise jitexc.ExitFrameWithExceptionRef(self.cpu, excvaluebox.getref_base())
 
     def check_recursion_invariant(self):
         portal_call_depth = -1
@@ -1842,9 +1841,9 @@
             op.name = self.framestack[-1].jitcode.name
 
     def execute_raised(self, exception, constant=False):
-        if isinstance(exception, JitException):
-            raise JitException, exception      # go through
-        llexception = get_llexception(self.cpu, exception)
+        if isinstance(exception, jitexc.JitException):
+            raise jitexc.JitException, exception      # go through
+        llexception = jitexc.get_llexception(self.cpu, exception)
         self.execute_ll_raised(llexception, constant)
 
     def execute_ll_raised(self, llexception, constant=False):
@@ -2089,7 +2088,7 @@
             gi, gr, gf = self._unpack_boxes(live_arg_boxes, 0, num_green_args)
             ri, rr, rf = self._unpack_boxes(live_arg_boxes, num_green_args,
                                             len(live_arg_boxes))
-            CRN = self.staticdata.ContinueRunningNormally
+            CRN = jitexc.ContinueRunningNormally
             raise CRN(gi, gr, gf, ri, rr, rf)
         else:
             # However, in order to keep the existing tests working
@@ -2671,11 +2670,11 @@
 
 # ____________________________________________________________
 
-class ChangeFrame(JitException):
+class ChangeFrame(jitexc.JitException):
     """Raised after we mutated metainterp.framestack, in order to force
     it to reload the current top-of-stack frame that gets interpreted."""
 
-class SwitchToBlackhole(JitException):
+class SwitchToBlackhole(jitexc.JitException):
     def __init__(self, reason, raising_exception=False):
         self.reason = reason
         self.raising_exception = raising_exception
diff --git a/rpython/jit/metainterp/test/support.py b/rpython/jit/metainterp/test/support.py
--- a/rpython/jit/metainterp/test/support.py
+++ b/rpython/jit/metainterp/test/support.py
@@ -6,7 +6,7 @@
 from rpython.jit.metainterp.warmspot import ll_meta_interp, get_stats
 from rpython.jit.metainterp.warmstate import unspecialize_value
 from rpython.jit.metainterp.optimizeopt import ALL_OPTS_DICT
-from rpython.jit.metainterp import pyjitpl, history
+from rpython.jit.metainterp import pyjitpl, history, jitexc
 from rpython.jit.codewriter.policy import JitPolicy
 from rpython.jit.codewriter import codewriter, longlong
 from rpython.rlib.rfloat import isnan
@@ -118,30 +118,19 @@
     return blackholeinterp._final_result_anytype()
 
 def _run_with_pyjitpl(testself, args):
-
-    class DoneWithThisFrame(Exception):
-        pass
-
-    class DoneWithThisFrameRef(DoneWithThisFrame):
-        def __init__(self, cpu, *args):
-            DoneWithThisFrame.__init__(self, *args)
-
     cw = testself.cw
     opt = history.Options(listops=True)
     metainterp_sd = pyjitpl.MetaInterpStaticData(cw.cpu, opt)
     metainterp_sd.finish_setup(cw)
     [jitdriver_sd] = metainterp_sd.jitdrivers_sd
     metainterp = pyjitpl.MetaInterp(metainterp_sd, jitdriver_sd)
-    metainterp_sd.DoneWithThisFrameInt = DoneWithThisFrame
-    metainterp_sd.DoneWithThisFrameRef = DoneWithThisFrameRef
-    metainterp_sd.DoneWithThisFrameFloat = DoneWithThisFrame
     testself.metainterp = metainterp
     try:
         metainterp.compile_and_run_once(jitdriver_sd, *args)
-    except DoneWithThisFrame, e:
-        #if option.view:
-        #    metainterp.stats.view()
-        return e.args[0]
+    except (jitexc.DoneWithThisFrameInt,
+            jitexc.DoneWithThisFrameRef,
+            jitexc.DoneWithThisFrameFloat) as e:
+        return e.result
     else:
         raise Exception("FAILED")
 
diff --git a/rpython/jit/metainterp/test/test_blackhole.py b/rpython/jit/metainterp/test/test_blackhole.py
--- a/rpython/jit/metainterp/test/test_blackhole.py
+++ b/rpython/jit/metainterp/test/test_blackhole.py
@@ -4,7 +4,7 @@
 from rpython.jit.metainterp.blackhole import BlackholeInterpBuilder
 from rpython.jit.metainterp.blackhole import BlackholeInterpreter
 from rpython.jit.metainterp.blackhole import convert_and_run_from_pyjitpl
-from rpython.jit.metainterp import history, pyjitpl
+from rpython.jit.metainterp import history, pyjitpl, jitexc
 from rpython.jit.codewriter.assembler import JitCode
 from rpython.rtyper.lltypesystem import lltype, llmemory
 from rpython.rtyper.llinterp import LLException
@@ -119,6 +119,7 @@
                       "\x01\x02",          # int_return/i
                       [],
                       num_regs_i=3, num_regs_r=0, num_regs_f=0)
+        jitcode.is_portal = True
         pc = 1
         registers_i = [history.BoxInt(40), history.ConstInt(2), None]
     class MyMetaInterp:
@@ -129,8 +130,6 @@
                 def start_blackhole(): pass
                 @staticmethod
                 def end_blackhole(): pass
-            class DoneWithThisFrameInt(Exception):
-                pass
         last_exc_value_box = None
         framestack = [MyMIFrame()]
     MyMetaInterp.staticdata.blackholeinterpbuilder = getblackholeinterp(
@@ -138,9 +137,9 @@
     MyMetaInterp.staticdata.blackholeinterpbuilder.metainterp_sd = \
         MyMetaInterp.staticdata
     #
-    d = py.test.raises(MyMetaInterp.staticdata.DoneWithThisFrameInt,
+    d = py.test.raises(jitexc.DoneWithThisFrameInt,
                        convert_and_run_from_pyjitpl, MyMetaInterp())
-    assert d.value.args == (42,)
+    assert d.value.result == 42
 
 
 class TestBlackhole(LLJitMixin):
diff --git a/rpython/jit/metainterp/test/test_warmspot.py b/rpython/jit/metainterp/test/test_warmspot.py
--- a/rpython/jit/metainterp/test/test_warmspot.py
+++ b/rpython/jit/metainterp/test/test_warmspot.py
@@ -1,4 +1,5 @@
 import py
+from rpython.jit.metainterp import jitexc
 from rpython.jit.metainterp.warmspot import get_stats
 from rpython.rlib.jit import JitDriver, set_param, unroll_safe, jit_callback
 from rpython.jit.backend.llgraph import runner
@@ -583,14 +584,14 @@
                 no = self.no
                 assert deadframe._no == no
                 if no == 0:
-                    raise metainterp_sd.warmrunnerdesc.DoneWithThisFrameInt(3)
+                    raise jitexc.DoneWithThisFrameInt(3)
                 if no == 1:
-                    raise metainterp_sd.warmrunnerdesc.ContinueRunningNormally(
+                    raise jitexc.ContinueRunningNormally(
                         [0], [], [], [1], [], [])
                 if no == 3:
                     exc = lltype.malloc(OBJECT)
                     exc.typeptr = exc_vtable
-                    raise metainterp_sd.warmrunnerdesc.ExitFrameWithExceptionRef(
+                    raise jitexc.ExitFrameWithExceptionRef(
                         metainterp_sd.cpu,
                         lltype.cast_opaque_ptr(llmemory.GCREF, exc))
                 assert 0
diff --git a/rpython/jit/metainterp/warmspot.py b/rpython/jit/metainterp/warmspot.py
--- a/rpython/jit/metainterp/warmspot.py
+++ b/rpython/jit/metainterp/warmspot.py
@@ -16,10 +16,9 @@
 from rpython.translator.backendopt import removenoops
 from rpython.translator.unsimplify import call_final_function
 
-from rpython.jit.metainterp import history, pyjitpl, gc, memmgr
+from rpython.jit.metainterp import history, pyjitpl, gc, memmgr, jitexc
 from rpython.jit.metainterp.pyjitpl import MetaInterpStaticData
 from rpython.jit.metainterp.jitprof import Profiler, EmptyProfiler
-from rpython.jit.metainterp.jitexc import JitException
 from rpython.jit.metainterp.jitdriver import JitDriverStaticData
 from rpython.jit.codewriter import support, codewriter, longlong
 from rpython.jit.codewriter.policy import JitPolicy
@@ -172,9 +171,6 @@
     stats.maybe_view()
     stats.check_consistency()
 
-class ContinueRunningNormallyBase(JitException):
-    pass
-
 # ____________________________________________________________
 
 class WarmRunnerDesc(object):
@@ -210,7 +206,6 @@
         #
         self.hooks = policy.jithookiface
         self.make_virtualizable_infos()
-        self.make_exception_classes()
         self.make_driverhook_graphs()
         self.make_enter_functions()
         self.rewrite_jit_merge_points(policy)
@@ -466,70 +461,6 @@
                 vinfos[VTYPEPTR] = VirtualizableInfo(self, VTYPEPTR)
             jd.virtualizable_info = vinfos[VTYPEPTR]
 
-    def make_exception_classes(self):
-
-        class DoneWithThisFrameVoid(JitException):
-            def __str__(self):
-                return 'DoneWithThisFrameVoid()'
-
-        class DoneWithThisFrameInt(JitException):
-            def __init__(self, result):
-                assert lltype.typeOf(result) is lltype.Signed
-                self.result = result
-            def __str__(self):
-                return 'DoneWithThisFrameInt(%s)' % (self.result,)
-
-        class DoneWithThisFrameRef(JitException):
-            def __init__(self, cpu, result):
-                assert lltype.typeOf(result) == cpu.ts.BASETYPE
-                self.result = result
-            def __str__(self):
-                return 'DoneWithThisFrameRef(%s)' % (self.result,)
-
-        class DoneWithThisFrameFloat(JitException):
-            def __init__(self, result):
-                assert lltype.typeOf(result) is longlong.FLOATSTORAGE
-                self.result = result
-            def __str__(self):
-                return 'DoneWithThisFrameFloat(%s)' % (self.result,)
-
-        class ExitFrameWithExceptionRef(JitException):
-            def __init__(self, cpu, value):
-                assert lltype.typeOf(value) == cpu.ts.BASETYPE
-                self.value = value
-            def __str__(self):
-                return 'ExitFrameWithExceptionRef(%s)' % (self.value,)
-
-        class ContinueRunningNormally(ContinueRunningNormallyBase):
-            def __init__(self, gi, gr, gf, ri, rr, rf):
-                # the six arguments are: lists of green ints, greens refs,
-                # green floats, red ints, red refs, and red floats.
-                self.green_int = gi
-                self.green_ref = gr
-                self.green_float = gf
-                self.red_int = ri
-                self.red_ref = rr
-                self.red_float = rf
-            def __str__(self):
-                return 'ContinueRunningNormally(%s, %s, %s, %s, %s, %s)' % (
-                    self.green_int, self.green_ref, self.green_float,
-                    self.red_int, self.red_ref, self.red_float)
-


More information about the pypy-commit mailing list