Commits

Hakan Ardo committed d41644a Merge

merge release-2.0-beta-1

Comments (0)

Files changed (378)

 b48df0bf4e75b81d98f19ce89d4a7dc3e1dab5e5 benchmarked
 d8ac7d23d3ec5f9a0fa1264972f74a010dbfd07f release-1.6
 ff4af8f318821f7f5ca998613a60fca09aa137da release-1.7
+7e4f0faa3d515b313f035a9eead56655bdb5e768 release-2.0-beta1
-License for files in the pypy/ directory 
-==================================================
+License
+=======
 
 Except when otherwise stated (look for LICENSE files in directories or
 information at the beginning of each file) all software and
-documentation in the 'pypy' directories is licensed as follows: 
+documentation in the 'pypy', 'ctype_configure', 'dotviewer', 'demo',
+and 'lib_pypy' directories is licensed as follows: 
 
     The MIT License
 

lib-python/2.7/distutils/command/build_ext.py

         shared extension.  On most platforms, this is just 'ext.libraries';
         on Windows and OS/2, we add the Python library (eg. python20.dll).
         """
+        # For PyPy, we must not add any such Python library, on any platform
+        if "__pypy__" in sys.builtin_module_names:
+            return ext.libraries
         # The python library is always needed on Windows.
         if sys.platform == "win32":
             template = "python%d%d"

lib-python/conftest.py

 from pypy.interpreter.main import run_string, run_file
 
 # the following adds command line options as a side effect! 
-from pypy.conftest import gettestobjspace, option as pypy_option 
+from pypy.conftest import option as pypy_option 
 
 from pypy.tool.pytest import appsupport 
 from pypy.tool.pytest.confpath import pypydir, testdir, testresultdir

lib_pypy/_sqlite3.py

                 self.statement.reset()
                 raise self.connection._get_exception(ret)
 
+            if self.statement.kind == DML:
+                self.statement.reset()
+
             if self.statement.kind == DQL and ret == SQLITE_ROW:
                 self.statement._build_row_cast_map()
                 self.statement._readahead(self)
                 self.statement.item = None
                 self.statement.exhausted = True
 
-            if self.statement.kind == DML:
-                self.statement.reset()
-
             self.rowcount = -1
             if self.statement.kind == DML:
                 self.rowcount = sqlite.sqlite3_changes(self.connection.db)

lib_pypy/itertools.py

-# Note that PyPy contains also a built-in module 'itertools' which will
-# hide this one if compiled in.
-
-"""Functional tools for creating and using iterators.
-
-Infinite iterators:
-count([n]) --> n, n+1, n+2, ...
-cycle(p) --> p0, p1, ... plast, p0, p1, ...
-repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times
-
-Iterators terminating on the shortest input sequence:
-izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... 
-ifilter(pred, seq) --> elements of seq where pred(elem) is True
-ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False
-islice(seq, [start,] stop [, step]) --> elements from
-       seq[start:stop:step]
-imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ...
-starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...
-tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n
-chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... 
-takewhile(pred, seq) --> seq[0], seq[1], until pred fails
-dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails
-groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v)
-"""
-
-__all__ = ['chain', 'count', 'cycle', 'dropwhile', 'groupby', 'ifilter',
-           'ifilterfalse', 'imap', 'islice', 'izip', 'repeat', 'starmap',
-           'takewhile', 'tee', 'compress', 'product']
-
-try: from __pypy__ import builtinify
-except ImportError: builtinify = lambda f: f
-
-
-class chain(object):
-    """Make an iterator that returns elements from the first iterable
-    until it is exhausted, then proceeds to the next iterable, until
-    all of the iterables are exhausted. Used for treating consecutive
-    sequences as a single sequence.
-
-    Equivalent to :
-
-    def chain(*iterables):
-        for it in iterables:
-            for element in it:
-                yield element
-    """
-    def __init__(self, *iterables):
-        self._iterables_iter = iter(map(iter, iterables))
-        # little trick for the first chain.next() call
-        self._cur_iterable_iter = iter([])
-
-    def __iter__(self):
-        return self
-    
-    def next(self):
-        while True:
-            try:
-                return self._cur_iterable_iter.next()
-            except StopIteration:
-                self._cur_iterable_iter = self._iterables_iter.next()
-            except AttributeError:
-                # CPython raises a TypeError when next() is not defined
-                raise TypeError('%s has no next() method' % \
-                                (self._cur_iterable_iter))
-
-
-class compress(object):
-    def __init__(self, data, selectors):
-        self.data = iter(data)
-        self.selectors = iter(selectors)
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        while True:
-            next_item = self.data.next()
-            next_selector = self.selectors.next()
-            if bool(next_selector):
-                return next_item
-
-
-class count(object):
-    """Make an iterator that returns consecutive integers starting
-    with n.  If not specified n defaults to zero. Does not currently
-    support python long integers. Often used as an argument to imap()
-    to generate consecutive data points.  Also, used with izip() to
-    add sequence numbers.
-
-    Equivalent to :
-
-    def count(n=0):
-        if not isinstance(n, int):
-            raise TypeError("%s is not a regular integer" % n)
-        while True:
-            yield n
-            n += 1
-    """
-    def __init__(self, n=0):
-        if not isinstance(n, int):
-            raise TypeError('%s is not a regular integer' % n)
-        self.times = n-1
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        self.times += 1
-        return self.times
-
-    def __repr__(self):
-        return 'count(%d)' % (self.times + 1)
-
-
-            
-class cycle(object):
-    """Make an iterator returning elements from the iterable and
-    saving a copy of each. When the iterable is exhausted, return
-    elements from the saved copy. Repeats indefinitely.
-
-    Equivalent to :
-
-    def cycle(iterable):
-        saved = []
-        for element in iterable:
-            yield element
-            saved.append(element)
-        while saved:
-            for element in saved:
-                yield element    
-    """
-    def __init__(self, iterable):
-        self._cur_iter = iter(iterable)
-        self._saved = []
-        self._must_save = True
-        
-    def __iter__(self):
-        return self
-
-    def next(self):
-        # XXX Could probably be improved
-        try:
-            next_elt = self._cur_iter.next()
-            if self._must_save:
-                self._saved.append(next_elt)
-        except StopIteration:
-            self._cur_iter = iter(self._saved)
-            next_elt = self._cur_iter.next()
-            self._must_save = False
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % \
-                            (self._cur_iter))
-        return next_elt
-            
-        
-class dropwhile(object):
-    """Make an iterator that drops elements from the iterable as long
-    as the predicate is true; afterwards, returns every
-    element. Note, the iterator does not produce any output until the
-    predicate is true, so it may have a lengthy start-up time.
-
-    Equivalent to :
-
-    def dropwhile(predicate, iterable):
-        iterable = iter(iterable)
-        for x in iterable:
-            if not predicate(x):
-                yield x
-                break
-        for x in iterable:
-            yield x
-    """
-    def __init__(self, predicate, iterable):
-        self._predicate = predicate
-        self._iter = iter(iterable)
-        self._dropped = False
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        try:
-            value = self._iter.next()
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % \
-                            (self._iter))
-        if self._dropped:
-            return value
-        while self._predicate(value):
-            value = self._iter.next()
-        self._dropped = True
-        return value
-
-class groupby(object):
-    """Make an iterator that returns consecutive keys and groups from the
-    iterable. The key is a function computing a key value for each
-    element. If not specified or is None, key defaults to an identity
-    function and returns the element unchanged. Generally, the
-    iterable needs to already be sorted on the same key function.
-
-    The returned group is itself an iterator that shares the
-    underlying iterable with groupby(). Because the source is shared,
-    when the groupby object is advanced, the previous group is no
-    longer visible. So, if that data is needed later, it should be
-    stored as a list:
-
-       groups = []
-       uniquekeys = []
-       for k, g in groupby(data, keyfunc):
-           groups.append(list(g))      # Store group iterator as a list
-           uniquekeys.append(k)
-    """    
-    def __init__(self, iterable, key=None):
-        if key is None:
-            key = lambda x: x
-        self.keyfunc = key
-        self.it = iter(iterable)
-        self.tgtkey = self.currkey = self.currvalue = xrange(0)
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        while self.currkey == self.tgtkey:
-            try:
-                self.currvalue = self.it.next() # Exit on StopIteration
-            except AttributeError:
-                # CPython raises a TypeError when next() is not defined
-                raise TypeError('%s has no next() method' % \
-                                (self.it))            
-            self.currkey = self.keyfunc(self.currvalue)
-        self.tgtkey = self.currkey
-        return (self.currkey, self._grouper(self.tgtkey))
-
-    def _grouper(self, tgtkey):
-        while self.currkey == tgtkey:
-            yield self.currvalue
-            self.currvalue = self.it.next() # Exit on StopIteration
-            self.currkey = self.keyfunc(self.currvalue)
-
-
-
-class _ifilter_base(object):
-    """base class for ifilter and ifilterflase"""
-    def __init__(self, predicate, iterable):
-        # Make sure iterable *IS* iterable
-        self._iter = iter(iterable)
-        if predicate is None:
-            self._predicate = bool
-        else:
-            self._predicate = predicate
-
-    def __iter__(self):
-        return self
-    
-class ifilter(_ifilter_base):
-    """Make an iterator that filters elements from iterable returning
-    only those for which the predicate is True.  If predicate is
-    None, return the items that are true.
-
-    Equivalent to :
-
-    def ifilter:
-        if predicate is None:
-            predicate = bool
-        for x in iterable:
-            if predicate(x):
-                yield x
-    """
-    def next(self):
-        try:
-            next_elt = self._iter.next()
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % \
-                            (self._iter))
-        while True:
-            if self._predicate(next_elt):
-                return next_elt
-            next_elt = self._iter.next()
-
-class ifilterfalse(_ifilter_base):
-    """Make an iterator that filters elements from iterable returning
-    only those for which the predicate is False.  If predicate is
-    None, return the items that are false.
-
-    Equivalent to :
-    
-    def ifilterfalse(predicate, iterable):
-        if predicate is None:
-            predicate = bool
-        for x in iterable:
-            if not predicate(x):
-                yield x
-    """
-    def next(self):
-        try:
-            next_elt = self._iter.next()
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % \
-                            (self._iter))
-        while True:
-            if not self._predicate(next_elt):
-                return next_elt
-            next_elt = self._iter.next()
-             
-
-
-
-class imap(object):
-    """Make an iterator that computes the function using arguments
-    from each of the iterables. If function is set to None, then
-    imap() returns the arguments as a tuple. Like map() but stops
-    when the shortest iterable is exhausted instead of filling in
-    None for shorter iterables. The reason for the difference is that
-    infinite iterator arguments are typically an error for map()
-    (because the output is fully evaluated) but represent a common
-    and useful way of supplying arguments to imap().
-
-    Equivalent to :
-
-    def imap(function, *iterables):
-        iterables = map(iter, iterables)
-        while True:
-            args = [i.next() for i in iterables]
-            if function is None:
-                yield tuple(args)
-            else:
-                yield function(*args)
-    
-    """
-    def __init__(self, function, iterable, *other_iterables):
-        self._func = function
-        self._iters = map(iter, (iterable, ) + other_iterables)
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        try:
-            args = [it.next() for it in self._iters]
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % \
-                            (it))
-        if self._func is None:
-            return tuple(args)
-        else:
-            return self._func(*args)
-
-
-
-class islice(object):
-    """Make an iterator that returns selected elements from the
-    iterable.  If start is non-zero, then elements from the iterable
-    are skipped until start is reached. Afterward, elements are
-    returned consecutively unless step is set higher than one which
-    results in items being skipped. If stop is None, then iteration
-    continues until the iterator is exhausted, if at all; otherwise,
-    it stops at the specified position. Unlike regular slicing,
-    islice() does not support negative values for start, stop, or
-    step. Can be used to extract related fields from data where the
-    internal structure has been flattened (for example, a multi-line
-    report may list a name field on every third line).
-    """ 
-    def __init__(self, iterable, *args):
-        s = slice(*args)
-        self.start, self.stop, self.step = s.start or 0, s.stop, s.step
-        if not isinstance(self.start, (int, long)):
-           raise ValueError("Start argument must be an integer")
-        if self.stop is not None and not isinstance(self.stop, (int,long)):
-           raise ValueError("Stop argument must be an integer or None")
-        if self.step is None:
-            self.step = 1
-        if self.start<0 or (self.stop is not None and self.stop<0
-           ) or self.step<=0:
-            raise ValueError, "indices for islice() must be positive"
-        self.it = iter(iterable)
-        self.donext = None
-        self.cnt = 0
-
-    def __iter__(self):
-        return self
-
-    def next(self): 
-        if self.donext is None:
-            try:
-                self.donext = self.it.next
-            except AttributeError:
-                raise TypeError
-        nextindex = self.start
-        if self.stop is not None and nextindex >= self.stop:
-            raise StopIteration
-        while self.cnt <= nextindex:
-            nextitem = self.donext()
-            self.cnt += 1
-        self.start += self.step 
-        return nextitem
-
-class izip(object):
-    """Make an iterator that aggregates elements from each of the
-    iterables.  Like zip() except that it returns an iterator instead
-    of a list. Used for lock-step iteration over several iterables at
-    a time.
-
-    Equivalent to :
-
-    def izip(*iterables):
-        iterables = map(iter, iterables)
-        while iterables:
-            result = [i.next() for i in iterables]
-            yield tuple(result)
-    """
-    def __init__(self, *iterables):
-        self._iterators = map(iter, iterables)
-        self._result = [None] * len(self._iterators)
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        if not self._iterators:
-            raise StopIteration()
-        try:
-            return tuple([i.next() for i in self._iterators])
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % (i))
-
-
-class product(object):
-
-    def __init__(self, *args, **kw):
-        if len(kw) > 1:
-            raise TypeError("product() takes at most 1 argument (%d given)" %
-                             len(kw))
-        self.repeat = kw.get('repeat', 1)
-        self.gears = [x for x in args] * self.repeat
-        self.num_gears = len(self.gears)
-        # initialization of indicies to loop over
-        self.indicies = [(0, len(self.gears[x]))
-                         for x in range(0, self.num_gears)]
-        self.cont = True
-
-    def roll_gears(self):
-        # Starting from the end of the gear indicies work to the front
-        # incrementing the gear until the limit is reached. When the limit
-        # is reached carry operation to the next gear
-        should_carry = True
-        for n in range(0, self.num_gears):
-            nth_gear = self.num_gears - n - 1
-            if should_carry:
-                count, lim = self.indicies[nth_gear]
-                count += 1
-                if count == lim and nth_gear == 0:
-                    self.cont = False
-                if count == lim:
-                    should_carry = True
-                    count = 0
-                else:
-                    should_carry = False
-                self.indicies[nth_gear] = (count, lim)
-            else:
-                break
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        if not self.cont:
-            raise StopIteration
-        l = []
-        for x in range(0, self.num_gears):
-            index, limit = self.indicies[x]
-            l.append(self.gears[x][index])
-        self.roll_gears()
-        return tuple(l)
-
-
-class repeat(object):
-    """Make an iterator that returns object over and over again.
-    Runs indefinitely unless the times argument is specified.  Used
-    as argument to imap() for invariant parameters to the called
-    function. Also used with izip() to create an invariant part of a
-    tuple record.
-
-    Equivalent to :
-
-    def repeat(object, times=None):
-        if times is None:
-            while True:
-                yield object
-        else:
-            for i in xrange(times):
-                yield object
-    """
-    def __init__(self, obj, times=None):
-        self._obj = obj
-        if times is not None:
-            xrange(times) # Raise a TypeError
-            if times < 0:
-                times = 0
-        self._times = times
-        
-    def __iter__(self):
-        return self
-
-    def next(self):
-        # next() *need* to decrement self._times when consumed
-        if self._times is not None:
-            if self._times <= 0: 
-                raise StopIteration()
-            self._times -= 1
-        return self._obj
-
-    def __repr__(self):
-        if self._times is not None:
-            return 'repeat(%r, %r)' % (self._obj, self._times)
-        else:
-            return 'repeat(%r)' % (self._obj,)
-
-    def __len__(self):
-        if self._times == -1 or self._times is None:
-            raise TypeError("len() of uniszed object")
-        return self._times
-    
-
-class starmap(object):
-    """Make an iterator that computes the function using arguments
-    tuples obtained from the iterable. Used instead of imap() when
-    argument parameters are already grouped in tuples from a single
-    iterable (the data has been ``pre-zipped''). The difference
-    between imap() and starmap() parallels the distinction between
-    function(a,b) and function(*c).
-
-    Equivalent to :
-
-    def starmap(function, iterable):
-        iterable = iter(iterable)
-        while True:
-            yield function(*iterable.next())    
-    """
-    def __init__(self, function, iterable):
-        self._func = function
-        self._iter = iter(iterable)
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        # CPython raises a TypeError when the iterator doesn't return a tuple
-        try:
-            t = self._iter.next()
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % self._iter)
-        if not isinstance(t, tuple):
-            raise TypeError("iterator must return a tuple")
-        return self._func(*t)
-
-
-
-class takewhile(object):
-    """Make an iterator that returns elements from the iterable as
-    long as the predicate is true.
-
-    Equivalent to :
-    
-    def takewhile(predicate, iterable):
-        for x in iterable:
-            if predicate(x):
-                yield x
-            else:
-                break
-    """
-    def __init__(self, predicate, iterable):
-        self._predicate = predicate
-        self._iter = iter(iterable)
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        try:
-            value = self._iter.next()
-        except AttributeError:
-            # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % \
-                            (self._iter))
-        if not self._predicate(value):
-            raise StopIteration()
-        return value
-
-    
-class TeeData(object):
-    """Holds cached values for TeeObjects"""
-    def __init__(self, iterator):
-        self.data = []
-        self._iter = iterator
-
-    def __getitem__(self, i):
-        # iterates until 'i' if not done yet
-        while i>= len(self.data):
-            try:
-                self.data.append( self._iter.next() )
-            except AttributeError:
-                # CPython raises a TypeError when next() is not defined
-                raise TypeError('%s has no next() method' % self._iter)
-        return self.data[i]
-
-
-class TeeObject(object):
-    """Iterables / Iterators as returned by the tee() function"""
-    def __init__(self, iterable=None, tee_data=None):
-        if tee_data:
-            self.tee_data = tee_data
-            self.pos = 0
-        # <=> Copy constructor
-        elif isinstance(iterable, TeeObject):
-            self.tee_data = iterable.tee_data
-            self.pos = iterable.pos
-        else:
-            self.tee_data = TeeData(iter(iterable))
-            self.pos = 0
-            
-    def next(self):
-        data = self.tee_data[self.pos]
-        self.pos += 1
-        return data
-    
-    def __iter__(self):
-        return self
-
-
-@builtinify
-def tee(iterable, n=2):
-    """Return n independent iterators from a single iterable.
-    Note : once tee() has made a split, the original iterable
-    should not be used anywhere else; otherwise, the iterable could get
-    advanced without the tee objects being informed.
-    
-    Note : this member of the toolkit may require significant auxiliary
-    storage (depending on how much temporary data needs to be stored).
-    In general, if one iterator is going to use most or all of the
-    data before the other iterator, it is faster to use list() instead
-    of tee()
-    
-    Equivalent to :
-    
-    def tee(iterable, n=2):
-        def gen(next, data={}, cnt=[0]):
-            for i in count():
-                if i == cnt[0]:
-                    item = data[i] = next()
-                    cnt[0] += 1
-                else:
-                    item = data.pop(i)
-                yield item
-        it = iter(iterable)
-        return tuple([gen(it.next) for i in range(n)])
-    """
-    if isinstance(iterable, TeeObject):
-        # a,b = tee(range(10)) ; c,d = tee(a) ; self.assert_(a is c)
-        return tuple([iterable] +
-        [TeeObject(tee_data=iterable.tee_data) for i in xrange(n-1)])
-    tee_data = TeeData(iter(iterable))
-    return tuple([TeeObject(tee_data=tee_data) for i in xrange(n)])

lib_pypy/numpypy/core/numeric.py

 
-from _numpypy import array, ndarray, int_, float_, bool_ #, complex_# , longlong
+from _numpypy import array, ndarray, int_, float_, bool_, flexible #, complex_# , longlong
 from _numpypy import concatenate
 from .fromnumeric import any
 import math
             typename = "'%s'" % typename
 
         lf = ''
-        if 0: # or issubclass(arr.dtype.type, flexible):
+        if issubclass(arr.dtype.type, flexible):
             if arr.dtype.names:
                 typename = "%s" % str(arr.dtype)
             else:

lib_pypy/pypy_test/test_itertools.py

-from py.test import raises
-from lib_pypy import itertools
-
-class TestItertools(object):
-
-    def test_compress(self):
-        it = itertools.compress(['a', 'b', 'c'], [0, 1, 0])
-
-        assert list(it) == ['b']
-
-    def test_compress_diff_len(self):
-        it = itertools.compress(['a'], [])
-        raises(StopIteration, it.next)
-
-    def test_product(self):
-        l = [1, 2]
-        m = ['a', 'b']
-
-        prodlist = itertools.product(l, m)
-        assert list(prodlist) == [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
-
-    def test_product_repeat(self):
-        l = [1, 2]
-        m = ['a', 'b']
-
-        prodlist = itertools.product(l, m, repeat=2)
-        ans = [(1, 'a', 1, 'a'), (1, 'a', 1, 'b'), (1, 'a', 2, 'a'),
-               (1, 'a', 2, 'b'), (1, 'b', 1, 'a'), (1, 'b', 1, 'b'),
-               (1, 'b', 2, 'a'), (1, 'b', 2, 'b'), (2, 'a', 1, 'a'),
-               (2, 'a', 1, 'b'), (2, 'a', 2, 'a'), (2, 'a', 2, 'b'),
-               (2, 'b', 1, 'a'), (2, 'b', 1, 'b'), (2, 'b', 2, 'a'),
-               (2, 'b', 2, 'b')]
-        assert list(prodlist) == ans
-
-    def test_product_diff_sizes(self):
-        l = [1, 2]
-        m = ['a']
-
-        prodlist = itertools.product(l, m)
-        assert list(prodlist) == [(1, 'a'), (2, 'a')]
-
-        l = [1]
-        m = ['a', 'b']
-        prodlist = itertools.product(l, m)
-        assert list(prodlist) == [(1, 'a'), (1, 'b')]
-
-    def test_product_toomany_args(self):
-        l = [1, 2]
-        m = ['a']
-        raises(TypeError, itertools.product, l, m, repeat=1, foo=2)

lib_pypy/pyrepl/readline.py

         try:
             return unicode(line, ENCODING)
         except UnicodeDecodeError:   # bah, silently fall back...
-            return unicode(line, 'utf-8')
+            return unicode(line, 'utf-8', 'replace')
 
     def get_history_length(self):
         return self.saved_history_length

lib_pypy/pyrepl/unix_console.py

             if iscode:
                 self.__tputs(text)
             else:
-                os.write(self.output_fd, text.encode(self.encoding))
+                os.write(self.output_fd, text.encode(self.encoding, 'replace'))
         del self.__buffer[:]
 
     def __tputs(self, fmt, prog=delayprog):

py/_code/source.py

File contents unchanged.

pypy/annotation/annrpython.py

                         if cell.is_constant():
                             newcell.const = cell.const
                         cell = newcell
-                        cell.knowntypedata = renamed_knowntypedata
+                        cell.set_knowntypedata(renamed_knowntypedata)
 
                     cells.append(cell)
 

pypy/annotation/binaryop.py

 
 # XXX unify this with ObjSpace.MethodTable
 BINARY_OPERATIONS = set(['add', 'sub', 'mul', 'div', 'mod',
-                         'truediv', 'floordiv', 'divmod', 'pow',
+                         'truediv', 'floordiv', 'divmod',
                          'and_', 'or_', 'xor',
                          'lshift', 'rshift',
                          'getitem', 'setitem', 'delitem',
                          'getitem_idx', 'getitem_key', 'getitem_idx_key',
                          'inplace_add', 'inplace_sub', 'inplace_mul',
                          'inplace_truediv', 'inplace_floordiv', 'inplace_div',
-                         'inplace_mod', 'inplace_pow',
+                         'inplace_mod',
                          'inplace_lshift', 'inplace_rshift',
                          'inplace_and', 'inplace_or', 'inplace_xor',
                          'lt', 'le', 'eq', 'ne', 'gt', 'ge', 'is_', 'cmp',
                          'coerce',
                          ]
                         +[opname+'_ovf' for opname in
-                          """add sub mul floordiv div mod pow lshift
+                          """add sub mul floordiv div mod lshift
                            """.split()
                           ])
 
     def inplace_floordiv((obj1, obj2)): return pair(obj1, obj2).floordiv()
     def inplace_div((obj1, obj2)):      return pair(obj1, obj2).div()
     def inplace_mod((obj1, obj2)):      return pair(obj1, obj2).mod()
-    def inplace_pow((obj1, obj2)):      return pair(obj1, obj2).pow(s_None)
     def inplace_lshift((obj1, obj2)):   return pair(obj1, obj2).lshift()
     def inplace_rshift((obj1, obj2)):   return pair(obj1, obj2).rshift()
     def inplace_and((obj1, obj2)):      return pair(obj1, obj2).and_()
         # XXX HACK HACK HACK
         bk = getbookkeeper()
         if bk is not None: # for testing
-            knowntypedata = r.knowntypedata = {}
+            knowntypedata = {}
             fn, block, i = bk.position_key
 
             annotator = bk.annotator
 
             bind(obj2, obj1, 0)
             bind(obj1, obj2, 1)
+            r.set_knowntypedata(knowntypedata)
 
         return r
 
             return SomeInteger(nonneg=int1.nonneg, knowntype=int1.knowntype)
     rshift.can_only_throw = []
 
-    def pow((int1, int2), obj3):
-        knowntype = rarithmetic.compute_restype(int1.knowntype, int2.knowntype)
-        return SomeInteger(nonneg = int1.nonneg,
-                           knowntype=knowntype)
-    pow.can_only_throw = [ZeroDivisionError]
-    pow_ovf = _clone(pow, [ZeroDivisionError, OverflowError])
-
-    def inplace_pow((int1, int2)):
-        knowntype = rarithmetic.compute_restype(int1.knowntype, int2.knowntype)
-        return SomeInteger(nonneg = int1.nonneg,
-                           knowntype=knowntype)
-    inplace_pow.can_only_throw = [ZeroDivisionError]
-
     def _compare_helper((int1, int2), opname, operation):
         r = SomeBool()
         if int1.is_immutable_constant() and int2.is_immutable_constant():
             case = opname in ('gt', 'ge', 'eq')
             add_knowntypedata(knowntypedata, case, [op.args[0]],
                               SomeInteger(nonneg=True, knowntype=tointtype(int1)))
-        if knowntypedata:
-            r.knowntypedata = knowntypedata
+        r.set_knowntypedata(knowntypedata)
         # a special case for 'x < 0' or 'x >= 0',
         # where 0 is a flow graph Constant
         # (in this case we are sure that it cannot become a r_uint later)
         if hasattr(boo1, 'knowntypedata') and \
            hasattr(boo2, 'knowntypedata'):
             ktd = merge_knowntypedata(boo1.knowntypedata, boo2.knowntypedata)
-            if ktd:
-                s.knowntypedata = ktd
+            s.set_knowntypedata(ktd)
         return s 
 
     def and_((boo1, boo2)):
     div.can_only_throw = []
     truediv = div
 
-    def pow((flt1, flt2), obj3):
-        raise NotImplementedError("float power not supported, use math.pow")
-
     # repeat these in order to copy the 'can_only_throw' attribute
     inplace_div = div
     inplace_truediv = truediv

pypy/annotation/bookkeeper.py

 from pypy.annotation.dictdef import DictDef
 from pypy.annotation import description
 from pypy.annotation.signature import annotationoftype
-from pypy.interpreter.argument import ArgumentsForTranslation
+from pypy.objspace.flow.argument import ArgumentsForTranslation
 from pypy.rlib.objectmodel import r_dict, Symbolic
 from pypy.tool.algo.unionfind import UnionFind
 from pypy.rpython.lltypesystem import lltype, llmemory
 
     def consider_list_delitem(self, idx):
         return self.indexrepr(idx)
-    
+
     def consider_str_join(self, s):
         if s.is_constant():
             return repr(s.const)
                 check_no_flags(s_value_or_def.listdef.listitem)
             elif isinstance(s_value_or_def, SomeDict):
                 check_no_flags(s_value_or_def.dictdef.dictkey)
-                check_no_flags(s_value_or_def.dictdef.dictvalue)                
+                check_no_flags(s_value_or_def.dictdef.dictvalue)
             elif isinstance(s_value_or_def, SomeTuple):
                 for s_item in s_value_or_def.items:
                     check_no_flags(s_item)
             elif isinstance(s_value_or_def, ListItem):
                 if s_value_or_def in seen:
                     return
-                seen.add(s_value_or_def)                
+                seen.add(s_value_or_def)
                 check_no_flags(s_value_or_def.s_value)
-            
+
         for clsdef in self.classdefs:
             check_no_flags(clsdef)
 
                 listdef = ListDef(self, s_ImpossibleValue)
                 for e in x:
                     listdef.generalize(self.immutablevalue(e, False))
-                result = SomeList(listdef)    
+                result = SomeList(listdef)
         elif tp is dict or tp is r_dict:
             if need_const:
                 key = Constant(x)
                 try:
                     return self.immutable_cache[key]
                 except KeyError:
-                    result = SomeDict(DictDef(self, 
+                    result = SomeDict(DictDef(self,
                                               s_ImpossibleValue,
                                               s_ImpossibleValue,
                                               is_r_dict = tp is r_dict))
                     result.const_box = key
                     return result
             else:
-                dictdef = DictDef(self, 
+                dictdef = DictDef(self,
                 s_ImpossibleValue,
                 s_ImpossibleValue,
                 is_r_dict = tp is r_dict)
             return True
         else:
             return False
-        
+
     def getfrozen(self, pyobj):
         return description.FrozenDesc(self, pyobj)
 
         key = (x.__class__, x)
         if key in self.seen_mutable:
             return
-        clsdef = self.getuniqueclassdef(x.__class__)        
+        clsdef = self.getuniqueclassdef(x.__class__)
         self.seen_mutable[key] = True
         self.event('mutable', x)
         source = InstanceSource(self, x)
         except KeyError:
             access_sets = map[attrname] = UnionFind(description.ClassAttrFamily)
         return access_sets
-    
+
     def pbc_getattr(self, pbc, s_attr):
         assert s_attr.is_constant()
         attr = s_attr.const
         first = descs[0]
         if len(descs) == 1:
             return first.s_read_attribute(attr)
-        
+
         change = first.mergeattrfamilies(descs[1:], attr)
         attrfamily = first.getattrfamily(attr)
 
     def ondegenerated(self, what, s_value, where=None, called_from_graph=None):
         self.annotator.ondegenerated(what, s_value, where=where,
                                      called_from_graph=called_from_graph)
-        
+
     def whereami(self):
         return self.annotator.whereami(self.position_key)
 

pypy/annotation/builtin.py

             variables = [op.args[1]]
         for variable in variables:
             assert bk.annotator.binding(variable) == s_obj
-        r.knowntypedata = {}
-        
+        knowntypedata = {}
         if not hasattr(typ, '_freeze_') and isinstance(s_type, SomePBC):
-            add_knowntypedata(r.knowntypedata, True, variables, bk.valueoftype(typ))
+            add_knowntypedata(knowntypedata, True, variables, bk.valueoftype(typ))
+        r.set_knowntypedata(knowntypedata)
     return r
 
 # note that this one either needs to be constant, or we will create SomeObject
 
 def robjmodel_hlinvoke(s_repr, s_llcallable, *args_s):
     from pypy.rpython import rmodel
-    assert s_repr.is_constant() and isinstance(s_repr.const, rmodel.Repr),"hlinvoke expects a constant repr as first argument"
-    r_func, nimplicitarg  = s_repr.const.get_r_implfunc()
+    from pypy.rpython.error import TyperError
 
-    nbargs = len(args_s) + nimplicitarg 
+    assert s_repr.is_constant() and isinstance(s_repr.const, rmodel.Repr), "hlinvoke expects a constant repr as first argument"
+    r_func, nimplicitarg = s_repr.const.get_r_implfunc()
+
+    nbargs = len(args_s) + nimplicitarg
     s_sigs = r_func.get_s_signatures((nbargs, (), False, False))
     if len(s_sigs) != 1:
         raise TyperError("cannot hlinvoke callable %r with not uniform"
 
     return lltype_to_annotation(rresult.lowleveltype)
 
+
 def robjmodel_keepalive_until_here(*args_s):
     return immutablevalue(None)
 
     BUILTIN_ANALYZERS[unicodedata.decimal] = unicodedata_decimal # xxx
 
 # object - just ignore object.__init__
-BUILTIN_ANALYZERS[object.__init__] = object_init
+if hasattr(object.__init__, 'im_func'):
+    BUILTIN_ANALYZERS[object.__init__.im_func] = object_init
+else:
+    BUILTIN_ANALYZERS[object.__init__] = object_init    
 
 # import
 BUILTIN_ANALYZERS[__import__] = import_func

pypy/annotation/description.py

 import types, py
 from pypy.objspace.flow.model import Constant, FunctionGraph
-from pypy.interpreter.pycode import cpython_code_signature
-from pypy.interpreter.argument import rawshape
-from pypy.interpreter.argument import ArgErr
+from pypy.objspace.flow.bytecode import cpython_code_signature
+from pypy.objspace.flow.argument import rawshape, ArgErr
 from pypy.tool.sourcetools import valid_identifier
 from pypy.tool.pairtype import extendabletype
 
             name = pyobj.func_name
         if signature is None:
             if hasattr(pyobj, '_generator_next_method_of_'):
-                from pypy.interpreter.argument import Signature
+                from pypy.objspace.flow.argument import Signature
                 signature = Signature(['entry'])     # haaaaaack
                 defaults = ()
             else:
         try:
             inputcells = args.match_signature(signature, defs_s)
         except ArgErr, e:
-            raise TypeError("signature mismatch: %s() %s" % 
+            raise TypeError("signature mismatch: %s() %s" %
                             (self.name, e.getmsg()))
         return inputcells
 

pypy/annotation/model.py

     unsigned = False
     def __init__(self):
         pass
+    def set_knowntypedata(self, knowntypedata):
+        assert not hasattr(self, 'knowntypedata')
+        if knowntypedata:
+            self.knowntypedata = knowntypedata
 
 class SomeStringOrUnicode(SomeObject):
     immutable = True
                 desc, = descriptions
                 if desc.pyobj is not None:
                     self.const = desc.pyobj
+            elif len(descriptions) > 1:
+                from pypy.annotation.description import ClassDesc
+                if self.getKind() is ClassDesc:
+                    # a PBC of several classes: enforce them all to be
+                    # built, without support for specialization.  See
+                    # rpython/test/test_rpbc.test_pbc_of_classes_not_all_used
+                    for desc in descriptions:
+                        desc.getuniqueclassdef()
 
     def any_description(self):
         return iter(self.descriptions).next()
     return r
 
 def not_const(s_obj):
-    if s_obj.is_constant():
+    if s_obj.is_constant() and not isinstance(s_obj, SomePBC):
         new_s_obj = SomeObject.__new__(s_obj.__class__)
         dic = new_s_obj.__dict__ = s_obj.__dict__.copy()
         if 'const' in dic:

pypy/annotation/specialize.py

 from pypy.objspace.flow.model import Block, Link, Variable, SpaceOperation
 from pypy.objspace.flow.model import Constant, checkgraph
 from pypy.annotation import model as annmodel
-from pypy.interpreter.argument import Signature
+from pypy.objspace.flow.argument import Signature
 
 def flatten_star_args(funcdesc, args_s):
     argnames, vararg, kwarg = funcdesc.signature

pypy/annotation/test/test_annrpython.py

 from pypy.rlib.rarithmetic import r_uint, base_int, r_longlong, r_ulonglong
 from pypy.rlib.rarithmetic import r_singlefloat
 from pypy.rlib import objectmodel
-from pypy.objspace.flow.objspace import FlowObjSpace
+from pypy.objspace.flow.objspace import FlowObjSpace, FlowingError
 
 from pypy.translator.test import snippet
 
         assert a.binding(et) == t
         assert isinstance(a.binding(ev), annmodel.SomeInstance) and a.binding(ev).classdef == a.bookkeeper.getuniqueclassdef(Exception)
 
-    def test_pow(self):
-        def f(n):
-            n **= 2
-            return 2 ** n
-        a = self.RPythonAnnotator()
-        s = a.build_types(f, [int])
-        # result should be an integer
-        assert s.knowntype == int
-
     def test_inplace_div(self):
         def f(n):
             n /= 2
             x **= y
             return x ** y
         a = self.RPythonAnnotator()
-        s = a.build_types(f, [int, int])
-        assert isinstance(s, annmodel.SomeInteger)
-        a = self.RPythonAnnotator()
-        py.test.raises(NotImplementedError, a.build_types, f, [float, float])
+        py.test.raises(FlowingError, a.build_types, f, [int, int])
+        a = self.RPythonAnnotator()
+        py.test.raises(FlowingError, a.build_types, f, [float, float])
 
     def test_intcmp_bug(self):
         def g(x, y):
         s = a.build_types(f, [annmodel.SomeInteger()])
         assert isinstance(s, annmodel.SomeBool)
 
+    def test_object_init(self):
+        class A(object):
+            pass
+
+        class B(A):
+            def __init__(self):
+                A.__init__(self)
+
+        def f():
+            B()
+
+        a = self.RPythonAnnotator()
+        a.build_types(f, []) # assert did not explode
+
 def g(n):
     return [0,1,2,n]
 

pypy/annotation/unaryop.py

         s_obj.is_true_behavior(r)
 
         bk = getbookkeeper()
-        knowntypedata = r.knowntypedata = {}
+        knowntypedata = {}
         fn, block, i = bk.position_key
         op = block.operations[i]
         assert op.opname == "is_true" or op.opname == "nonzero"
         if s_obj.can_be_none():
             s_nonnone_obj = s_obj.nonnoneify()
         add_knowntypedata(knowntypedata, True, [arg], s_nonnone_obj)
+        r.set_knowntypedata(knowntypedata)
         return r
-        
 
     def nonzero(obj):
         return obj.is_true()
     config, parser = option.get_standard_options()
     interactiveconfig = Config(cmdline_optiondescr)
     to_optparse(interactiveconfig, parser=parser)
+    def set_family_of_options(option, opt, value, parser):
+        from pypy.config.pypyoption import set_pypy_opt_level
+        set_pypy_opt_level(config, value)
     parser.add_option(
         '--cc', type=str, action="callback",
         callback=set_compiler,
         help="Compiler to use for compiling generated C")
+    parser.add_option(
+        '--opt', type=str, action="callback",
+        callback=set_family_of_options,
+        help="Set the family of options based on -opt=0,1,2,jit...")
     args = option.process_options(parser, argv[1:])
     if interactiveconfig.verbose:
         error.RECORD_INTERPLEVEL_TRACEBACK = True

pypy/config/pypyoption.py

         config.objspace.std.suggest(builtinshortcut=True)
         config.objspace.std.suggest(optimized_list_getitem=True)
         config.objspace.std.suggest(getattributeshortcut=True)
-        config.objspace.std.suggest(newshortcut=True)
+        #config.objspace.std.suggest(newshortcut=True)
         config.objspace.std.suggest(withspecialisedtuple=True)
         config.objspace.std.suggest(withidentitydict=True)
         #if not IS_64_BITS:

pypy/config/test/test_pypyoption.py

 def test_set_pypy_opt_level():
     conf = get_pypy_config()
     set_pypy_opt_level(conf, '2')
-    assert conf.objspace.std.newshortcut
+    assert conf.objspace.std.getattributeshortcut
     conf = get_pypy_config()
     set_pypy_opt_level(conf, '0')
-    assert not conf.objspace.std.newshortcut
+    assert not conf.objspace.std.getattributeshortcut
 
 def test_rweakref_required():
     conf = get_pypy_config()

pypy/config/translationoption.py

                          ("translation.gcrootfinder", DEFL_ROOTFINDER_WITHJIT),
                          ("translation.list_comprehension_operations", True)]),
     ChoiceOption("jit_backend", "choose the backend for the JIT",
-                 ["auto", "x86", "x86-without-sse2", "llvm", 'arm'],
+                 ["auto", "x86", "x86-without-sse2", 'arm'],
                  default="auto", cmdline="--jit-backend"),
     ChoiceOption("jit_profiler", "integrate profiler support into the JIT",
                  ["off", "oprofile"],
-import py, pytest, sys, os, textwrap, types
-from pypy.interpreter.gateway import app2interp_temp
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.function import Method
-from pypy.tool.pytest import appsupport
-from pypy.tool.option import make_config, make_objspace
-from pypy.config.config import ConflictConfigError
-from inspect import isclass, getmro
-from pypy.tool.udir import udir
-from pypy.tool.autopath import pypydir
-from pypy.tool import leakfinder
+import py, pytest, sys, os, textwrap
+from inspect import isclass
 
 # pytest settings
 rsyncdirs = ['.', '../lib-python', '../lib_pypy', '../demo']
 def pytest_report_header():
     return "pytest-%s from %s" %(pytest.__version__, pytest.__file__)
 
+
+def pytest_addhooks(pluginmanager):
+    from pypy.tool.pytest.plugins import LeakFinder
+    pluginmanager.register(LeakFinder())
+
+
 def pytest_configure(config):
     global option
     option = config.option
         pass
 
 def pytest_funcarg__space(request):
+    from pypy.tool.pytest.objspace import gettestobjspace
     spaceconfig = getattr(request.cls, 'spaceconfig', {})
     return gettestobjspace(**spaceconfig)
 
-_SPACECACHE={}
-def gettestobjspace(name=None, **kwds):
-    """ helper for instantiating and caching space's for testing.
-    """
-    try:
-        config = make_config(option, objspace=name, **kwds)
-    except ConflictConfigError, e:
-        # this exception is typically only raised if a module is not available.
-        # in this case the test should be skipped
-        py.test.skip(str(e))
-    key = config.getkey()
-    try:
-        return _SPACECACHE[key]
-    except KeyError:
-        if getattr(option, 'runappdirect', None):
-            if name not in (None, 'std'):
-                myname = getattr(sys, 'pypy_objspaceclass', '')
-                if not myname.lower().startswith(name):
-                    py.test.skip("cannot runappdirect test: "
-                                 "%s objspace required" % (name,))
-            return TinyObjSpace(**kwds)
-        space = maketestobjspace(config)
-        _SPACECACHE[key] = space
-        return space
-
-def maketestobjspace(config=None):
-    if config is None:
-        config = make_config(option)
-    space = make_objspace(config)
-    space.startup() # Initialize all builtin modules
-    space.setitem(space.builtin.w_dict, space.wrap('AssertionError'),
-                  appsupport.build_pytest_assertion(space))
-    space.setitem(space.builtin.w_dict, space.wrap('raises'),
-                  space.wrap(appsupport.app_raises))
-    space.setitem(space.builtin.w_dict, space.wrap('skip'),
-                  space.wrap(appsupport.app_skip))
-    space.raises_w = appsupport.raises_w.__get__(space)
-    space.eq_w = appsupport.eq_w.__get__(space)
-    return space
-
-class TinyObjSpace(object):
-    def __init__(self, **kwds):
-        import sys
-        info = getattr(sys, 'pypy_translation_info', None)
-        for key, value in kwds.iteritems():
-            if key == 'usemodules':
-                if info is not None:
-                    for modname in value:
-                        ok = info.get('objspace.usemodules.%s' % modname,
-                                      False)
-                        if not ok:
-                            py.test.skip("cannot runappdirect test: "
-                                         "module %r required" % (modname,))
-                else:
-                    if '__pypy__' in value:
-                        py.test.skip("no module __pypy__ on top of CPython")
-                continue
-            if info is None:
-                py.test.skip("cannot runappdirect this test on top of CPython")
-            has = info.get(key, None)
-            if has != value:
-                #print sys.pypy_translation_info
-                py.test.skip("cannot runappdirect test: space needs %s = %s, "\
-                    "while pypy-c was built with %s" % (key, value, has))
-
-        for name in ('int', 'long', 'str', 'unicode', 'None'):
-            setattr(self, 'w_' + name, eval(name))
-
-
-    def appexec(self, args, body):
-        body = body.lstrip()
-        assert body.startswith('(')
-        src = py.code.Source("def anonymous" + body)
-        d = {}
-        exec src.compile() in d
-        return d['anonymous'](*args)
-
-    def wrap(self, obj):
-        return obj
-
-    def unpackiterable(self, itr):
-        return list(itr)
-
-    def is_true(self, obj):
-        return bool(obj)
-
-    def str_w(self, w_str):
-        return w_str
-
-    def newdict(self, module=None):
-        return {}
-
-    def newtuple(self, iterable):
-        return tuple(iterable)
-
-    def newlist(self, iterable):
-        return list(iterable)
-
-    def call_function(self, func, *args, **kwds):
-        return func(*args, **kwds)
-
-    def call_method(self, obj, name, *args, **kwds):
-        return getattr(obj, name)(*args, **kwds)
-
-    def getattr(self, obj, name):
-        return getattr(obj, name)
-
-    def setattr(self, obj, name, value):
-        setattr(obj, name, value)
-
-    def getbuiltinmodule(self, name):
-        return __import__(name)
-
-    def delslice(self, obj, *args):
-        obj.__delslice__(*args)
-
-    def is_w(self, obj1, obj2):
-        return obj1 is obj2
-
-def translation_test_so_skip_if_appdirect():
-    if option.runappdirect:
-        py.test.skip("translation test, skipped for appdirect")
-
-
-class OpErrKeyboardInterrupt(KeyboardInterrupt):
-    pass
-
-def check_keyboard_interrupt(e):
-    # we cannot easily convert w_KeyboardInterrupt to KeyboardInterrupt
-    # in general without a space -- here is an approximation
-    try:
-        if e.w_type.name == 'KeyboardInterrupt':
-            tb = sys.exc_info()[2]
-            raise OpErrKeyboardInterrupt, OpErrKeyboardInterrupt(), tb
-    except AttributeError:
-        pass
 
 #
 # Interfacing/Integrating with py.test's collection process
     def makeitem(self, name, obj):
         if isclass(obj) and self.classnamefilter(name):
             if name.startswith('AppTest'):
+                from pypy.tool.pytest.apptest import AppClassCollector
                 return AppClassCollector(name, parent=self)
             elif name.startswith('ExpectTest'):
                 if self.config.option.rundirect:
                     return py.test.collect.Class(name, parent=self)
+                from pypy.tool.pytest.expecttest import ExpectClassCollector
                 return ExpectClassCollector(name, parent=self)
             # XXX todo
             #elif name.startswith('AppExpectTest'):
             #        return AppClassCollector(name, parent=self)
             #    return AppExpectClassCollector(name, parent=self)
             else:
+                from pypy.tool.pytest.inttest import IntClassCollector
                 return IntClassCollector(name, parent=self)
 
         elif hasattr(obj, 'func_code') and self.funcnamefilter(name):
             if name.startswith('app_test_'):
                 assert not obj.func_code.co_flags & 32, \
                     "generator app level functions? you must be joking"
+                from pypy.tool.pytest.apptest import AppTestFunction
                 return AppTestFunction(name, parent=self)
             elif obj.func_code.co_flags & 32: # generator function
                 return pytest.Generator(name, parent=self)
             else:
+                from pypy.tool.pytest.inttest import IntTestFunction
                 return IntTestFunction(name, parent=self)
 
 def skip_on_missing_buildoption(**ropts):
 
 class LazyObjSpaceGetter(object):
     def __get__(self, obj, cls=None):
+        from pypy.tool.pytest.objspace import gettestobjspace
         space = gettestobjspace()
         if cls:
             cls.space = space
         return space
 
 
-class AppError(Exception):
-
-    def __init__(self, excinfo):
-        self.excinfo = excinfo
-
 def pytest_runtest_setup(__multicall__, item):
     if isinstance(item, py.test.collect.Function):
         appclass = item.getparent(PyPyClassCollector)
         if appclass is not None:
+            # Make cls.space and cls.runappdirect available in tests.
             spaceconfig = getattr(appclass.obj, 'spaceconfig', None)
-            if spaceconfig:
+            if spaceconfig is not None:
+                from pypy.tool.pytest.objspace import gettestobjspace
                 appclass.obj.space = gettestobjspace(**spaceconfig)
+            appclass.obj.runappdirect = option.runappdirect
 
     __multicall__.execute()
 
-    if isinstance(item, py.test.collect.Function):
-        if not getattr(item.obj, 'dont_track_allocations', False):
-            leakfinder.start_tracking_allocations()
-
-def pytest_runtest_call(__multicall__, item):
-    __multicall__.execute()
-    item._success = True
-
 def pytest_runtest_teardown(__multicall__, item):
     __multicall__.execute()
 
-    if isinstance(item, py.test.collect.Function):
-        if (not getattr(item.obj, 'dont_track_allocations', False)
-            and leakfinder.TRACK_ALLOCATIONS):
-            item._pypytest_leaks = leakfinder.stop_tracking_allocations(False)
-        else:            # stop_tracking_allocations() already called
-            item._pypytest_leaks = None
-
-        # check for leaks, but only if the test passed so far
-        if getattr(item, '_success', False) and item._pypytest_leaks:
-            raise leakfinder.MallocMismatch(item._pypytest_leaks)