Commits

Justin Peel committed d6d4d23 Merge

merge in default

  • Participants
  • Parent commits 5f924fc, 7eb1a79
  • Branches unsigned-dtypes

Comments (0)

Files changed (25)

File pypy/annotation/test/test_annrpython.py

         s = a.build_types(f, [])
         assert isinstance(s, annmodel.SomeList)
         assert not s.listdef.listitem.resized
+        assert not s.listdef.listitem.immutable
+        assert s.listdef.listitem.mutated
 
     def test_delslice(self):
         def f():

File pypy/annotation/unaryop.py

         check_negative_slice(s_start, s_stop)
         if not isinstance(s_iterable, SomeList):
             raise Exception("list[start:stop] = x: x must be a list")
+        lst.listdef.mutate()
         lst.listdef.agree(s_iterable.listdef)
         # note that setslice is not allowed to resize a list in RPython
 

File pypy/jit/metainterp/optimizeopt/test/test_util.py

                             EffectInfo.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE,
                             can_invalidate=True))
     arraycopydescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
-             EffectInfo([], [], [], [], oopspecindex=EffectInfo.OS_ARRAYCOPY))
+             EffectInfo([], [arraydescr], [], [arraydescr],
+                        oopspecindex=EffectInfo.OS_ARRAYCOPY))
 
     for _name, _os in [
         ('strconcatdescr',               'OS_STR_CONCAT'),

File pypy/jit/metainterp/test/test_ajit.py

         assert res == main(1, 10)
         self.check_loops(call=0)
 
+    def test_setarrayitem_followed_by_arraycopy(self):
+        myjitdriver = JitDriver(greens = [], reds = ['n', 'sa', 'x', 'y'])
+        def f(n):
+            sa = 0
+            x = [1,2,n]
+            y = [1,2,3]
+            while n > 0:
+                myjitdriver.jit_merge_point(sa=sa, n=n, x=x, y=y)
+                y[0] = n
+                x[0:3] = y
+                sa += x[0]
+                n -= 1
+            return sa
+        res = self.meta_interp(f, [16])
+        assert res == f(16)
+        
+
 
 class TestLLtype(BaseLLtypeTests, LLJitMixin):
     def test_tagged(self):

File pypy/module/micronumpy/__init__.py

         ("arccos", "arccos"),
         ("arcsin", "arcsin"),
         ("arctan", "arctan"),
+        ("arcsinh", "arcsinh"),
         ("copysign", "copysign"),
         ("cos", "cos"),
         ("divide", "divide"),
     appleveldefs = {
         'average': 'app_numpy.average',
         'mean': 'app_numpy.mean',
+        'inf': 'app_numpy.inf',
     }

File pypy/module/micronumpy/app_numpy.py

 import numpy
 
+
+inf = float("inf")
+
 def average(a):
     # This implements a weighted average, for now we don't implement the
     # weighting, just the average part!
 def mean(a):
     if not hasattr(a, "mean"):
         a = numpy.array(a)
-    return a.mean()
+    return a.mean()

File pypy/module/micronumpy/interp_dtype.py

     @unaryop
     def arctan(self, v):
         return math.atan(v)
+    @unaryop
+    def arcsinh(self, v):
+        return math.asinh(v)
 
 class IntegerArithmeticDtype(ArithmeticTypeMixin):
     _mixin_ = True

File pypy/module/micronumpy/interp_ufuncs.py

             ("arcsin", "arcsin", 1, {"promote_to_float": True}),
             ("arccos", "arccos", 1, {"promote_to_float": True}),
             ("arctan", "arctan", 1, {"promote_to_float": True}),
+            ("arcsinh", "arcsinh", 1, {"promote_to_float": True}),
         ]:
             self.add_ufunc(space, *ufunc_def)
 

File pypy/module/micronumpy/test/test_module.py

     def test_average(self):
         from numpy import array, average
         assert average(range(10)) == 4.5
-        assert average(array(range(10))) == 4.5
+        assert average(array(range(10))) == 4.5
+
+    def test_inf(self):
+        from numpy import inf
+        assert type(inf) is float
+        assert inf == float("inf")

File pypy/module/micronumpy/test/test_ufuncs.py

         b = arctan(a)
         assert math.isnan(b[0])
 
+    def test_arcsinh(self):
+        import math
+        from numpy import arcsinh, inf
+
+        for v in [inf, -inf, 1.0, math.e]:
+            assert math.asinh(v) == arcsinh(v)
+        assert math.isnan(arcsinh(float("nan")))
+
     def test_reduce_errors(self):
         from numpy import sin, add
 

File pypy/objspace/descroperation.py

             msg = "'%s' has no length" % (name,)
             raise OperationError(space.w_TypeError, space.wrap(msg))
         w_res = space.get_and_call_function(w_descr, w_obj)
-        space._check_len_result(w_res)
-        return w_res
+        return space.wrap(space._check_len_result(w_res))
 
     def _check_len_result(space, w_obj):
         # Will complain if result is too big.
-        result = space.int_w(w_obj)
+        result = space.int_w(space.int(w_obj))
         if result < 0:
             raise OperationError(space.w_ValueError,
                                  space.wrap("__len__() should return >= 0"))
+        return result
 
     def iter(space, w_obj):
         w_descr = space.lookup(w_obj, '__iter__')

File pypy/objspace/std/intobject.py

 from pypy.interpreter.error import OperationError
 from pypy.objspace.std import newformat
+from pypy.objspace.std.inttype import wrapint
 from pypy.objspace.std.model import registerimplementation, W_Object
-from pypy.objspace.std.register_all import register_all
 from pypy.objspace.std.multimethod import FailedToImplementArgs
 from pypy.objspace.std.noneobject import W_NoneObject
+from pypy.objspace.std.register_all import register_all
+from pypy.rlib import jit
 from pypy.rlib.rarithmetic import ovfcheck, ovfcheck_lshift, LONG_BIT, r_uint
 from pypy.rlib.rbigint import rbigint
-from pypy.objspace.std.inttype import wrapint
 
 """
 In order to have the same behavior running
     _immutable_fields_ = ['intval']
 
     from pypy.objspace.std.inttype import int_typedef as typedef
-    
+
     def __init__(w_self, intval):
         w_self.intval = intval
 
     x = float(w_int1.intval)
     y = float(w_int2.intval)
     if y == 0.0:
-        raise FailedToImplementArgs(space.w_ZeroDivisionError, space.wrap("float division"))    
+        raise FailedToImplementArgs(space.w_ZeroDivisionError, space.wrap("float division"))
     return space.wrap(x / y)
 
 def mod__Int_Int(space, w_int1, w_int2):
 
 
 # helper for pow()
-def _impl_int_int_pow(space, iv, iw, iz=0):
+@jit.look_inside_iff(lambda space, iv, iw, iz: jit.isconstant(iw) and jit.isconstant(iz))
+def _impl_int_int_pow(space, iv, iw, iz):
     if iw < 0:
         if iz != 0:
             raise OperationError(space.w_TypeError,
     except OverflowError:
         raise FailedToImplementArgs(space.w_OverflowError,
                                 space.wrap("integer exponentiation"))
-    return wrapint(space, ix)
+    return ix
 
 def pow__Int_Int_Int(space, w_int1, w_int2, w_int3):
     x = w_int1.intval
     if z == 0:
         raise OperationError(space.w_ValueError,
                              space.wrap("pow() 3rd argument cannot be 0"))
-    return _impl_int_int_pow(space, x, y, z)
+    return space.wrap(_impl_int_int_pow(space, x, y, z))
 
 def pow__Int_Int_None(space, w_int1, w_int2, w_int3):
     x = w_int1.intval
     y = w_int2.intval
-    return _impl_int_int_pow(space, x, y)
+    return space.wrap(_impl_int_int_pow(space, x, y, 0))
 
 def neg__Int(space, w_int1):
     a = w_int1.intval

File pypy/objspace/std/listobject.py

     if len(items)== 0:
         raise OperationError(space.w_IndexError,
                              space.wrap("pop from empty list"))
-    idx = space.int_w(w_idx)
+    if space.isinstance_w(w_idx, space.w_float):
+        raise OperationError(space.w_TypeError,
+            space.wrap("integer argument expected, got float")
+        )
+    idx = space.int_w(space.int(w_idx))
     try:
         return items.pop(idx)
     except IndexError:

File pypy/objspace/std/rangeobject.py

 
 class W_RangeListObject(W_Object):
     typedef = listtype.list_typedef
-    
+
     def __init__(w_self, start, step, length):
         assert step != 0
         w_self.start = start
         if not length:
             w_self.w_list = space.newlist([])
             return w_self.w_list
-        
+
         arr = [None] * length  # this is to avoid using append.
 
         i = start
     if length == 0:
         raise OperationError(space.w_IndexError,
                              space.wrap("pop from empty list"))
-    idx = space.int_w(w_idx)
+    if space.isinstance_w(w_idx, space.w_float):
+        raise OperationError(space.w_TypeError,
+            space.wrap("integer argument expected, got float")
+        )
+    idx = space.int_w(space.int(w_idx))
     if idx == 0:
         result = w_rangelist.start
         w_rangelist.start += w_rangelist.step

File pypy/objspace/std/ropeunicodeobject.py

 
 def eq__RopeUnicode_Rope(space, w_runi, w_rope):
     from pypy.objspace.std.unicodeobject import _unicode_string_comparison
-    return _unicode_string_comparison(space, w_runi, w_rope, 
+    return _unicode_string_comparison(space, w_runi, w_rope,
                     False,  unicode_from_string)
 
 def ne__RopeUnicode_RopeUnicode(space, w_str1, w_str2):
 
 def ne__RopeUnicode_Rope(space, w_runi, w_rope):
     from pypy.objspace.std.unicodeobject import _unicode_string_comparison
-    return _unicode_string_comparison(space, w_runi, w_rope, 
+    return _unicode_string_comparison(space, w_runi, w_rope,
                     True, unicode_from_string)
 
 def gt__RopeUnicode_RopeUnicode(space, w_str1, w_str2):
     if (len(l_w) == 1 and
         space.is_w(space.type(l_w[0]), space.w_unicode)):
         return l_w[0]
-    
+
     values_list = []
     for i in range(len(l_w)):
         w_item = l_w[i]
 
 
 def make_generic(funcname):
-    def func(space, w_self): 
+    def func(space, w_self):
         node = w_self._node
         if node.length() == 0:
             return space.w_False
         return w_self.create_if_subclassed()
     resultnode = rope.concatenate(rope.multiply(fillchar, padding), self)
     return W_RopeUnicodeObject(resultnode)
-    
+
 def unicode_zfill__RopeUnicode_ANY(space, w_self, w_width):
     self = w_self._node
     length = self.length()
     except OverflowError:
         raise OperationError(space.w_OverflowError,
                              space.wrap("string too long"))
-    
+
 
 def unicode_encode__RopeUnicode_ANY_ANY(space, w_unistr,
                                         w_encoding=None,
         try:
             w_newval = space.getitem(w_table, space.wrap(char))
         except OperationError, e:
-            if e.match(space, space.w_KeyError):
+            if e.match(space, space.w_LookupError):
                 result.append(crope)
             else:
                 raise
     hexdigits = "0123456789abcdef"
     node = w_unicode._node
     size = node.length()
-    
+
     singlequote = doublequote = False
     iter = rope.ItemIterator(node)
     for i in range(size):
                                   ])
                     j += 2
                     continue
-                
+
         if code >= 0x100:
             result.extend(['\\', "u",
                            hexdigits[(code >> 12) & 0xf],
             continue
         if code < ord(' ') or code >= 0x7f:
             result.extend(['\\', "x",
-                           hexdigits[(code >> 4) & 0xf], 
+                           hexdigits[(code >> 4) & 0xf],
                            hexdigits[(code >> 0) & 0xf],
                           ])
             j += 1
 
 def next__RopeUnicodeIter(space, w_ropeiter):
     if w_ropeiter.node is None:
-        raise OperationError(space.w_StopIteration, space.w_None) 
+        raise OperationError(space.w_StopIteration, space.w_None)
     try:
         unichar = w_ropeiter.item_iter.nextunichar()
         w_item = space.wrap(unichar)
     except StopIteration:
         w_ropeiter.node = None
         w_ropeiter.char_iter = None
-        raise OperationError(space.w_StopIteration, space.w_None) 
-    w_ropeiter.index += 1 
+        raise OperationError(space.w_StopIteration, space.w_None)
+    w_ropeiter.index += 1
     return w_item
 
 # XXX __length_hint__()

File pypy/objspace/std/test/test_listobject.py

         l.pop()
         assert l == range(9)
 
+    def test_pop_custom_int(self):
+        class A(object):
+            def __init__(self, x):
+                self.x = x
+
+            def __int__(self):
+                return self.x
+
+        l = range(10)
+        x = l.pop(A(-1))
+        assert x == 9
+        assert l == range(9)
+        raises(TypeError, range(10).pop, 1.0)
+
     def test_remove(self):
         c = list('hello world')
         c.remove('l')

File pypy/objspace/std/test/test_typeobject.py

         raises(TypeError, type, 'test', 42, {})
         raises(TypeError, type, 'test', (object,), 42)
 
+    def test_call_type_subclass(self):
+        class A(type):
+            pass
+
+        assert A("hello") is str
+
+        # Make sure type(x) doesn't call x.__class__.__init__
+        class T(type):
+            counter = 0
+            def __init__(self, *args):
+                T.counter += 1
+        class C:
+            __metaclass__ = T
+        assert T.counter == 1
+        a = C()
+        assert T.counter == 1
+        assert type(a) is C
+        assert T.counter == 1
+
     def test_bases(self):
         assert int.__bases__ == (object,)
         class X:

File pypy/objspace/std/typeobject.py

         for i in range(len(self.lookup_where)):
             self.lookup_where[i] = None_None
 
-# possible values of compares_by_identity_status 
+# possible values of compares_by_identity_status
 UNKNOWN = 0
 COMPARES_BY_IDENTITY = 1
 OVERRIDES_EQ_CMP_OR_HASH = 2
                 if w_value is not None:
                     return w_value
         return None
-                
+
     @unroll_safe
     def _lookup(w_self, key):
         space = w_self.space
 
 def call__Type(space, w_type, __args__):
     promote(w_type)
-    # special case for type(x)
-    if space.is_w(w_type, space.w_type):
-        try:
-            w_obj, = __args__.fixedunpack(1)
-        except ValueError:
-            pass
-        else:
-            return space.type(w_obj)
     # invoke the __new__ of the type
     if not we_are_jitted():
         # note that the annotator will figure out that w_type.w_bltin_new can
         call_init = space.isinstance_w(w_newobject, w_type)
 
     # maybe invoke the __init__ of the type
-    if call_init:
+    if (call_init and not (space.is_w(w_type, space.w_type) and
+        not __args__.keywords and len(__args__.arguments_w) == 1)):
         w_descr = space.lookup(w_newobject, '__init__')
         w_result = space.get_and_call_args(w_descr, w_newobject, __args__)
         if not space.is_w(w_result, space.w_None):

File pypy/objspace/std/typetype.py

-from pypy.interpreter.error import OperationError, operationerrfmt
 from pypy.interpreter import gateway
 from pypy.interpreter.argument import Arguments
+from pypy.interpreter.error import OperationError, operationerrfmt
 from pypy.interpreter.typedef import (GetSetProperty, descr_get_dict,
                                       weakref_descr)
 from pypy.objspace.std.stdtypedef import StdTypeDef
 
-def descr__new__(space, w_typetype, w_name, w_bases, w_dict):
+
+def descr__new__(space, w_typetype, w_name, w_bases=gateway.NoneNotWrapped,
+    w_dict=gateway.NoneNotWrapped):
+
     "This is used to create user-defined classes only."
     from pypy.objspace.std.typeobject import W_TypeObject
     # XXX check types
 
     w_typetype = _precheck_for_new(space, w_typetype)
 
+    # special case for type(x)
+    if (space.is_w(space.type(w_typetype), space.w_type) and w_bases is None and
+        w_dict is None):
+        return space.type(w_name)
+    elif w_bases is None or w_dict is None:
+        raise OperationError(space.w_TypeError, space.wrap("type() takes 1 or 3 arguments"))
+
+
     bases_w = space.fixedview(w_bases)
 
     w_winner = w_typetype

File pypy/objspace/test/test_descroperation.py

                 return -1L
         raises(ValueError, len, Y())
 
+    def test_len_custom__int__(self):
+        class X(object):
+            def __init__(self, x):
+                self.x = x
+            def __len__(self):
+                return self.x
+            def __int__(self):
+                return self.x
+
+        l = len(X(3.0))
+        assert l == 3 and type(l) is int
+        l = len(X(X(2)))
+        assert l == 2 and type(l) is int
+
 class AppTestWithBuiltinShortcut(AppTest_Descroperation):
     OPTIONS = {'objspace.std.builtinshortcut': True}

File pypy/rlib/jit.py

 
     This is for advanced usage only.
     """
-    # I hate the annotator so much.
-    if NonConstant(False):
-        return True
-    return False
+    return NonConstant(False)
 
 @oopspec("jit.isvirtual(value)")
 @specialize.ll()

File pypy/rlib/rgc.py

 
 from pypy.rlib import jit
 from pypy.rlib.objectmodel import we_are_translated, enforceargs, specialize
+from pypy.rlib.nonconst import NonConstant
 from pypy.rpython.extregistry import ExtRegistryEntry
 from pypy.rpython.lltypesystem import lltype, llmemory
 
     from pypy.rpython.lltypesystem.lloperation import llop
     from pypy.rlib.objectmodel import keepalive_until_here
 
+    # XXX: Hack to ensure that we get a proper effectinfo.write_descrs_arrays
+    if NonConstant(False):
+        dest[dest_start] = source[source_start]
+
     # supports non-overlapping copies only
     if not we_are_translated():
         if source == dest:

File pypy/rlib/test/test_jit.py

 import py
 from pypy.conftest import option
 from pypy.rlib.jit import hint, we_are_jitted, JitDriver, elidable_promote
-from pypy.rlib.jit import JitHintError, oopspec
+from pypy.rlib.jit import JitHintError, oopspec, isconstant
 from pypy.translator.translator import TranslationContext, graphof
 from pypy.rpython.test.tool import BaseRtypingTest, LLRtypeMixin, OORtypeMixin
 from pypy.rpython.lltypesystem import lltype
             t.view()
         # assert did not raise
 
+    def test_isconstant(self):
+        def f(n):
+            assert n >= 0
+            assert isconstant(n) is False
+            l = []
+            l.append(n)
+            return len(l)
+        res = self.interpret(f, [234])
+        assert res == 1
+
 
 class TestJITLLtype(BaseTestJIT, LLRtypeMixin):
     pass

File pypy/rpython/lltypesystem/rlist.py

+from pypy.rlib import rgc, jit
+from pypy.rlib.debug import ll_assert
+from pypy.rlib.objectmodel import enforceargs
+from pypy.rpython.lltypesystem import rstr
+from pypy.rpython.lltypesystem.lltype import (GcForwardReference, Ptr, GcArray,
+     GcStruct, Void, Signed, malloc, typeOf, nullptr, typeMethod)
+from pypy.rpython.rlist import (AbstractBaseListRepr, AbstractListRepr,
+    AbstractFixedSizeListRepr, AbstractListIteratorRepr, ll_setitem_nonneg,
+    ADTIList, ADTIFixedList, dum_nocheck)
+from pypy.rpython.rmodel import Repr, inputconst, externalvsinternal
 from pypy.tool.pairtype import pairtype, pair
-from pypy.rpython.rmodel import Repr, inputconst
-from pypy.rpython.rmodel import externalvsinternal
-from pypy.rpython.rlist import AbstractBaseListRepr, AbstractListRepr, \
-        AbstractFixedSizeListRepr, AbstractListIteratorRepr, \
-        ll_setitem_nonneg, ADTIList, ADTIFixedList
-from pypy.rpython.rlist import dum_nocheck
-from pypy.rpython.lltypesystem.lltype import GcForwardReference, Ptr, GcArray,\
-     GcStruct, Void, Signed, malloc, typeOf, nullptr, typeMethod
-from pypy.rpython.lltypesystem import rstr
-from pypy.rlib.debug import ll_assert
-from pypy.rlib import rgc, jit
+
 
 # ____________________________________________________________
 #
 
 # adapted C code
 
+@enforceargs(None, int)
 def _ll_list_resize_really(l, newsize):
     """
     Ensure l.items has room for at least newsize elements, and set
         rgc.ll_arraycopy(items, newitems, 0, 0, p)
     l.length = newsize
     l.items = newitems
-_ll_list_resize_really._annenforceargs_ = (None, int)
 
 # this common case was factored out of _ll_list_resize
 # to see if inlining it gives some speed-up.

File pypy/translator/c/genc.py

             else:
                 mk.definition('PYPY_MAIN_FUNCTION', "main")
 
-            if sys.platform == 'win32':
+            if (py.path.local.sysfind('python') or
+                py.path.local.sysfind('python.exe')):
+                python = 'python '
+            elif sys.platform == 'win32':
                 python = sys.executable.replace('\\', '/') + ' '
             else:
                 python = sys.executable + ' '