[pypy-commit] pypy merge-2.7.2: hg merge default
amauryfa
noreply at buildbot.pypy.org
Sun Jan 22 20:57:14 CET 2012
Author: Amaury Forgeot d'Arc <amauryfa at gmail.com>
Branch: merge-2.7.2
Changeset: r51663:6e17d519d090
Date: 2012-01-22 20:42 +0100
http://bitbucket.org/pypy/pypy/changeset/6e17d519d090/
Log: hg merge default
diff --git a/.hgignore b/.hgignore
--- a/.hgignore
+++ b/.hgignore
@@ -2,6 +2,9 @@
*.py[co]
*~
.*.swp
+.idea
+.project
+.pydevproject
syntax: regexp
^testresult$
diff --git a/lib_pypy/datetime.py b/lib_pypy/datetime.py
--- a/lib_pypy/datetime.py
+++ b/lib_pypy/datetime.py
@@ -1519,12 +1519,17 @@
@classmethod
def utcfromtimestamp(cls, t):
"Construct a UTC datetime from a POSIX timestamp (like time.time())."
- if 1 - (t % 1.0) < 0.0000005:
- t = float(int(t)) + 1
- if t < 0:
- t -= 1
+ t, frac = divmod(t, 1.0)
+ us = round(frac * 1e6)
+
+ # If timestamp is less than one microsecond smaller than a
+ # full second, us can be rounded up to 1000000. In this case,
+ # roll over to seconds, otherwise, ValueError is raised
+ # by the constructor.
+ if us == 1000000:
+ t += 1
+ us = 0
y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
- us = int((t % 1.0) * 1000000)
ss = min(ss, 59) # clamp out leap seconds if the platform has them
return cls(y, m, d, hh, mm, ss, us)
diff --git a/lib_pypy/numpypy/__init__.py b/lib_pypy/numpypy/__init__.py
--- a/lib_pypy/numpypy/__init__.py
+++ b/lib_pypy/numpypy/__init__.py
@@ -1,2 +1,2 @@
from _numpypy import *
-from .fromnumeric import *
+from .core import *
diff --git a/lib_pypy/numpypy/core/__init__.py b/lib_pypy/numpypy/core/__init__.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/numpypy/core/__init__.py
@@ -0,0 +1,1 @@
+from .fromnumeric import *
diff --git a/lib_pypy/numpypy/fromnumeric.py b/lib_pypy/numpypy/core/fromnumeric.py
rename from lib_pypy/numpypy/fromnumeric.py
rename to lib_pypy/numpypy/core/fromnumeric.py
--- a/lib_pypy/numpypy/fromnumeric.py
+++ b/lib_pypy/numpypy/core/fromnumeric.py
@@ -85,7 +85,7 @@
array([4, 3, 6])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
# not deprecated --- copy if necessary, view otherwise
@@ -149,6 +149,7 @@
[5, 6]])
"""
+ assert order == 'C'
if not hasattr(a, 'reshape'):
a = numpypy.array(a)
return a.reshape(newshape)
@@ -273,7 +274,7 @@
[-1, -2, -3, -4, -5]]])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def repeat(a, repeats, axis=None):
@@ -315,7 +316,7 @@
[3, 4]])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def put(a, ind, v, mode='raise'):
@@ -366,7 +367,7 @@
array([ 0, 1, 2, 3, -5])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def swapaxes(a, axis1, axis2):
@@ -410,7 +411,7 @@
[3, 7]]])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def transpose(a, axes=None):
@@ -451,8 +452,11 @@
(2, 1, 3)
"""
- raise NotImplemented('Waiting on interp level method')
-
+ if axes is not None:
+ raise NotImplementedError('No "axes" arg yet.')
+ if not hasattr(a, 'T'):
+ a = numpypy.array(a)
+ return a.T
def sort(a, axis=-1, kind='quicksort', order=None):
"""
@@ -553,7 +557,7 @@
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def argsort(a, axis=-1, kind='quicksort', order=None):
@@ -634,7 +638,7 @@
array([0, 1])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def argmax(a, axis=None):
@@ -687,6 +691,7 @@
1
"""
+ assert axis is None
if not hasattr(a, 'argmax'):
a = numpypy.array(a)
return a.argmax()
@@ -702,6 +707,7 @@
documentation.
"""
+ assert axis is None
if not hasattr(a, 'argmin'):
a = numpypy.array(a)
return a.argmin()
@@ -753,7 +759,7 @@
array([0, 5, 1, 2])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def resize(a, new_shape):
@@ -794,7 +800,7 @@
[0, 1, 2, 3]])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def squeeze(a):
@@ -821,7 +827,7 @@
(3,)
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def diagonal(a, offset=0, axis1=0, axis2=1):
@@ -905,7 +911,7 @@
[5, 7]])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
@@ -964,7 +970,7 @@
(2, 3)
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def ravel(a, order='C'):
"""
@@ -1048,7 +1054,7 @@
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def nonzero(a):
@@ -1124,7 +1130,7 @@
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def shape(a):
@@ -1229,7 +1235,7 @@
array([2])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def clip(a, a_min, a_max, out=None):
@@ -1282,7 +1288,7 @@
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def sum(a, axis=None, dtype=None, out=None):
@@ -1351,9 +1357,11 @@
-128
"""
+ assert dtype is None
+ assert out is None
if not hasattr(a, "sum"):
a = numpypy.array(a)
- return a.sum()
+ return a.sum(axis=axis)
def product (a, axis=None, dtype=None, out=None):
@@ -1365,7 +1373,7 @@
prod : equivalent function; see for details.
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def sometrue(a, axis=None, out=None):
@@ -1379,6 +1387,8 @@
any : equivalent function
"""
+ assert axis is None
+ assert out is None
if not hasattr(a, 'any'):
a = numpypy.array(a)
return a.any()
@@ -1393,6 +1403,8 @@
numpy.all : Equivalent function; see for details.
"""
+ assert axis is None
+ assert out is None
if not hasattr(a, 'all'):
a = numpypy.array(a)
return a.all()
@@ -1461,6 +1473,8 @@
(191614240, 191614240)
"""
+ assert axis is None
+ assert out is None
if not hasattr(a, 'any'):
a = numpypy.array(a)
return a.any()
@@ -1523,6 +1537,8 @@
(28293632, 28293632, array([ True], dtype=bool))
"""
+ assert axis is None
+ assert out is None
if not hasattr(a, 'all'):
a = numpypy.array(a)
return a.all()
@@ -1590,7 +1606,7 @@
[ 4, 9, 15]])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def cumproduct(a, axis=None, dtype=None, out=None):
@@ -1603,7 +1619,7 @@
cumprod : equivalent function; see for details.
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def ptp(a, axis=None, out=None):
@@ -1644,7 +1660,7 @@
array([1, 1])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def amax(a, axis=None, out=None):
@@ -1702,6 +1718,8 @@
4.0
"""
+ assert axis is None
+ assert out is None
if not hasattr(a, "max"):
a = numpypy.array(a)
return a.max()
@@ -1763,6 +1781,8 @@
"""
# amin() is equivalent to min()
+ assert axis is None
+ assert out is None
if not hasattr(a, 'min'):
a = numpypy.array(a)
return a.min()
@@ -1873,7 +1893,7 @@
True
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def cumprod(a, axis=None, dtype=None, out=None):
@@ -1936,7 +1956,7 @@
[ 4, 20, 120]])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def ndim(a):
@@ -2054,7 +2074,7 @@
2
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def around(a, decimals=0, out=None):
@@ -2123,7 +2143,7 @@
array([ 0, 0, 0, 10])
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def round_(a, decimals=0, out=None):
@@ -2137,7 +2157,7 @@
around : equivalent function
"""
- raise NotImplemented('Waiting on interp level method')
+ raise NotImplementedError('Waiting on interp level method')
def mean(a, axis=None, dtype=None, out=None):
@@ -2211,9 +2231,11 @@
0.55000000074505806
"""
+ assert dtype is None
+ assert out is None
if not hasattr(a, "mean"):
a = numpypy.array(a)
- return a.mean()
+ return a.mean(axis=axis)
def std(a, axis=None, dtype=None, out=None, ddof=0):
@@ -2302,6 +2324,10 @@
0.44999999925552653
"""
+ assert axis is None
+ assert dtype is None
+ assert out is None
+ assert ddof == 0
if not hasattr(a, "std"):
a = numpypy.array(a)
return a.std()
@@ -2395,6 +2421,10 @@
0.20250000000000001
"""
+ assert axis is None
+ assert dtype is None
+ assert out is None
+ assert ddof == 0
if not hasattr(a, "var"):
a = numpypy.array(a)
return a.var()
diff --git a/pypy/config/pypyoption.py b/pypy/config/pypyoption.py
--- a/pypy/config/pypyoption.py
+++ b/pypy/config/pypyoption.py
@@ -340,7 +340,7 @@
requires=[("objspace.std.builtinshortcut", True)]),
BoolOption("withidentitydict",
"track types that override __hash__, __eq__ or __cmp__ and use a special dict strategy for those which do not",
- default=True),
+ default=False),
]),
])
@@ -370,6 +370,7 @@
config.objspace.std.suggest(getattributeshortcut=True)
config.objspace.std.suggest(newshortcut=True)
config.objspace.std.suggest(withspecialisedtuple=True)
+ config.objspace.std.suggest(withidentitydict=True)
#if not IS_64_BITS:
# config.objspace.std.suggest(withsmalllong=True)
diff --git a/pypy/doc/translation.rst b/pypy/doc/translation.rst
--- a/pypy/doc/translation.rst
+++ b/pypy/doc/translation.rst
@@ -155,7 +155,7 @@
function. The two input variables are the exception class
and the exception value, respectively. (No other block will
actually link to the exceptblock if the function does not
- explicitely raise exceptions.)
+ explicitly raise exceptions.)
``Block``
@@ -325,7 +325,7 @@
Mutable objects need special treatment during annotation, because
the annotation of contained values needs to be possibly updated to account
for mutation operations, and consequently the annotation information
-reflown through the relevant parts of the flow the graphs.
+reflown through the relevant parts of the flow graphs.
* ``SomeList`` stands for a list of homogeneous type (i.e. all the
elements of the list are represented by a single common ``SomeXxx``
@@ -503,8 +503,8 @@
Since RPython is a garbage collected language there is a lot of heap memory
allocation going on all the time, which would either not occur at all in a more
-traditional explicitely managed language or results in an object which dies at
-a time known in advance and can thus be explicitely deallocated. For example a
+traditional explicitly managed language or results in an object which dies at
+a time known in advance and can thus be explicitly deallocated. For example a
loop of the following form::
for i in range(n):
@@ -696,7 +696,7 @@
So far it is the second most mature high level backend after GenCLI:
it still can't translate the full Standard Interpreter, but after the
-Leysin sprint we were able to compile and run the rpytstone and
+Leysin sprint we were able to compile and run the rpystone and
richards benchmarks.
GenJVM is almost entirely the work of Niko Matsakis, who worked on it
diff --git a/pypy/jit/backend/test/runner_test.py b/pypy/jit/backend/test/runner_test.py
--- a/pypy/jit/backend/test/runner_test.py
+++ b/pypy/jit/backend/test/runner_test.py
@@ -551,6 +551,28 @@
res = self.execute_operation(rop.CALL, [funcbox] + map(BoxInt, args), 'int', descr=calldescr)
assert res.value == func(*args)
+ def test_call_box_func(self):
+ def a(a1, a2):
+ return a1 + a2
+ def b(b1, b2):
+ return b1 * b2
+
+ arg1 = 40
+ arg2 = 2
+ for f in [a, b]:
+ TP = lltype.Signed
+ FPTR = self.Ptr(self.FuncType([TP, TP], TP))
+ func_ptr = llhelper(FPTR, f)
+ FUNC = deref(FPTR)
+ funcconst = self.get_funcbox(self.cpu, func_ptr)
+ funcbox = funcconst.clonebox()
+ calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
+ EffectInfo.MOST_GENERAL)
+ res = self.execute_operation(rop.CALL,
+ [funcbox, BoxInt(arg1), BoxInt(arg2)],
+ 'int', descr=calldescr)
+ assert res.getint() == f(arg1, arg2)
+
def test_call_stack_alignment(self):
# test stack alignment issues, notably for Mac OS/X.
# also test the ordering of the arguments.
@@ -1872,6 +1894,7 @@
values.append(descr)
values.append(self.cpu.get_latest_value_int(0))
values.append(self.cpu.get_latest_value_int(1))
+ values.append(token)
FUNC = self.FuncType([lltype.Signed, lltype.Signed], lltype.Void)
func_ptr = llhelper(lltype.Ptr(FUNC), maybe_force)
@@ -1902,7 +1925,8 @@
assert fail.identifier == 1
assert self.cpu.get_latest_value_int(0) == 1
assert self.cpu.get_latest_value_int(1) == 10
- assert values == [faildescr, 1, 10]
+ token = self.cpu.get_latest_force_token()
+ assert values == [faildescr, 1, 10, token]
def test_force_operations_returning_int(self):
values = []
@@ -1911,6 +1935,7 @@
self.cpu.force(token)
values.append(self.cpu.get_latest_value_int(0))
values.append(self.cpu.get_latest_value_int(2))
+ values.append(token)
return 42
FUNC = self.FuncType([lltype.Signed, lltype.Signed], lltype.Signed)
@@ -1944,7 +1969,8 @@
assert self.cpu.get_latest_value_int(0) == 1
assert self.cpu.get_latest_value_int(1) == 42
assert self.cpu.get_latest_value_int(2) == 10
- assert values == [1, 10]
+ token = self.cpu.get_latest_force_token()
+ assert values == [1, 10, token]
def test_force_operations_returning_float(self):
values = []
@@ -1953,6 +1979,7 @@
self.cpu.force(token)
values.append(self.cpu.get_latest_value_int(0))
values.append(self.cpu.get_latest_value_int(2))
+ values.append(token)
return 42.5
FUNC = self.FuncType([lltype.Signed, lltype.Signed], lltype.Float)
@@ -1988,7 +2015,8 @@
x = self.cpu.get_latest_value_float(1)
assert longlong.getrealfloat(x) == 42.5
assert self.cpu.get_latest_value_int(2) == 10
- assert values == [1, 10]
+ token = self.cpu.get_latest_force_token()
+ assert values == [1, 10, token]
def test_call_to_c_function(self):
from pypy.rlib.libffi import CDLL, types, ArgChain, FUNCFLAG_CDECL
diff --git a/pypy/jit/backend/x86/assembler.py b/pypy/jit/backend/x86/assembler.py
--- a/pypy/jit/backend/x86/assembler.py
+++ b/pypy/jit/backend/x86/assembler.py
@@ -1118,6 +1118,12 @@
for src, dst in singlefloats:
self.mc.MOVD(dst, src)
# Finally remap the arguments in the main regs
+ # If x is a register and is in dst_locs, then oups, it needs to
+ # be moved away:
+ if x in dst_locs:
+ src_locs.append(x)
+ dst_locs.append(r10)
+ x = r10
remap_frame_layout(self, src_locs, dst_locs, X86_64_SCRATCH_REG)
self._regalloc.reserve_param(len(pass_on_stack))
@@ -2042,10 +2048,7 @@
size = sizeloc.value
signloc = arglocs[1]
- if isinstance(op.getarg(0), Const):
- x = imm(op.getarg(0).getint())
- else:
- x = arglocs[2]
+ x = arglocs[2] # the function address
if x is eax:
tmp = ecx
else:
diff --git a/pypy/jit/backend/x86/runner.py b/pypy/jit/backend/x86/runner.py
--- a/pypy/jit/backend/x86/runner.py
+++ b/pypy/jit/backend/x86/runner.py
@@ -6,7 +6,7 @@
from pypy.jit.codewriter import longlong
from pypy.jit.metainterp import history, compile
from pypy.jit.backend.x86.assembler import Assembler386
-from pypy.jit.backend.x86.arch import FORCE_INDEX_OFS
+from pypy.jit.backend.x86.arch import FORCE_INDEX_OFS, IS_X86_32
from pypy.jit.backend.x86.profagent import ProfileAgent
from pypy.jit.backend.llsupport.llmodel import AbstractLLCPU
from pypy.jit.backend.x86 import regloc
@@ -142,7 +142,9 @@
cast_ptr_to_int._annspecialcase_ = 'specialize:arglltype(0)'
cast_ptr_to_int = staticmethod(cast_ptr_to_int)
- all_null_registers = lltype.malloc(rffi.LONGP.TO, 24,
+ all_null_registers = lltype.malloc(rffi.LONGP.TO,
+ IS_X86_32 and (16+8) # 16 + 8 regs
+ or (16+16), # 16 + 16 regs
flavor='raw', zero=True,
immortal=True)
diff --git a/pypy/module/_codecs/interp_codecs.py b/pypy/module/_codecs/interp_codecs.py
--- a/pypy/module/_codecs/interp_codecs.py
+++ b/pypy/module/_codecs/interp_codecs.py
@@ -108,6 +108,10 @@
w_result = state.codec_search_cache.get(normalized_encoding, None)
if w_result is not None:
return w_result
+ return _lookup_codec_loop(space, encoding, normalized_encoding)
+
+def _lookup_codec_loop(space, encoding, normalized_encoding):
+ state = space.fromcache(CodecState)
if state.codec_need_encodings:
w_import = space.getattr(space.builtin, space.wrap("__import__"))
# registers new codecs
diff --git a/pypy/module/_codecs/test/test_codecs.py b/pypy/module/_codecs/test/test_codecs.py
--- a/pypy/module/_codecs/test/test_codecs.py
+++ b/pypy/module/_codecs/test/test_codecs.py
@@ -588,10 +588,18 @@
raises(UnicodeDecodeError, '+3ADYAA-'.decode, 'utf-7')
def test_utf_16_encode_decode(self):
- import codecs
+ import codecs, sys
x = u'123abc'
- assert codecs.getencoder('utf-16')(x) == ('\xff\xfe1\x002\x003\x00a\x00b\x00c\x00', 6)
- assert codecs.getdecoder('utf-16')('\xff\xfe1\x002\x003\x00a\x00b\x00c\x00') == (x, 14)
+ if sys.byteorder == 'big':
+ assert codecs.getencoder('utf-16')(x) == (
+ '\xfe\xff\x001\x002\x003\x00a\x00b\x00c', 6)
+ assert codecs.getdecoder('utf-16')(
+ '\xfe\xff\x001\x002\x003\x00a\x00b\x00c') == (x, 14)
+ else:
+ assert codecs.getencoder('utf-16')(x) == (
+ '\xff\xfe1\x002\x003\x00a\x00b\x00c\x00', 6)
+ assert codecs.getdecoder('utf-16')(
+ '\xff\xfe1\x002\x003\x00a\x00b\x00c\x00') == (x, 14)
def test_unicode_escape(self):
assert u'\\'.encode('unicode-escape') == '\\\\'
diff --git a/pypy/module/_codecs/test/test_ztranslation.py b/pypy/module/_codecs/test/test_ztranslation.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/_codecs/test/test_ztranslation.py
@@ -0,0 +1,5 @@
+from pypy.objspace.fake.checkmodule import checkmodule
+
+
+def test__codecs_translates():
+ checkmodule('_codecs')
diff --git a/pypy/module/cpyext/include/patchlevel.h b/pypy/module/cpyext/include/patchlevel.h
--- a/pypy/module/cpyext/include/patchlevel.h
+++ b/pypy/module/cpyext/include/patchlevel.h
@@ -29,7 +29,7 @@
#define PY_VERSION "2.7.1"
/* PyPy version as a string */
-#define PYPY_VERSION "1.7.1"
+#define PYPY_VERSION "1.8.1"
/* Subversion Revision number of this file (not of the repository).
* Empty since Mercurial migration. */
diff --git a/pypy/module/micronumpy/__init__.py b/pypy/module/micronumpy/__init__.py
--- a/pypy/module/micronumpy/__init__.py
+++ b/pypy/module/micronumpy/__init__.py
@@ -70,6 +70,7 @@
("exp", "exp"),
("fabs", "fabs"),
("floor", "floor"),
+ ("ceil", "ceil"),
("greater", "greater"),
("greater_equal", "greater_equal"),
("less", "less"),
@@ -85,12 +86,13 @@
("subtract", "subtract"),
('sqrt', 'sqrt'),
("tan", "tan"),
+ ('bitwise_and', 'bitwise_and'),
+ ('bitwise_or', 'bitwise_or'),
]:
interpleveldefs[exposed] = "interp_ufuncs.get(space).%s" % impl
appleveldefs = {
'average': 'app_numpy.average',
- 'mean': 'app_numpy.mean',
'sum': 'app_numpy.sum',
'min': 'app_numpy.min',
'identity': 'app_numpy.identity',
@@ -99,5 +101,4 @@
'e': 'app_numpy.e',
'pi': 'app_numpy.pi',
'arange': 'app_numpy.arange',
- 'reshape': 'app_numpy.reshape',
}
diff --git a/pypy/module/micronumpy/app_numpy.py b/pypy/module/micronumpy/app_numpy.py
--- a/pypy/module/micronumpy/app_numpy.py
+++ b/pypy/module/micronumpy/app_numpy.py
@@ -11,23 +11,20 @@
def average(a):
# This implements a weighted average, for now we don't implement the
# weighting, just the average part!
- return mean(a)
+ if not hasattr(a, "mean"):
+ a = _numpypy.array(a)
+ return a.mean()
def identity(n, dtype=None):
- a = _numpypy.zeros((n,n), dtype=dtype)
+ a = _numpypy.zeros((n, n), dtype=dtype)
for i in range(n):
a[i][i] = 1
return a
-def mean(a, axis=None):
- if not hasattr(a, "mean"):
- a = _numpypy.array(a)
- return a.mean(axis)
-
def sum(a,axis=None):
'''sum(a, axis=None)
Sum of array elements over a given axis.
-
+
Parameters
----------
a : array_like
@@ -35,7 +32,7 @@
axis : integer, optional
Axis over which the sum is taken. By default `axis` is None,
and all elements are summed.
-
+
Returns
-------
sum_along_axis : ndarray
@@ -43,7 +40,7 @@
axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
is returned. If an output array is specified, a reference to
`out` is returned.
-
+
See Also
--------
ndarray.sum : Equivalent method.
@@ -79,40 +76,3 @@
arr[j] = i
i += step
return arr
-
-
-def reshape(a, shape):
- '''reshape(a, newshape)
- Gives a new shape to an array without changing its data.
-
- Parameters
- ----------
- a : array_like
- Array to be reshaped.
- newshape : int or tuple of ints
- The new shape should be compatible with the original shape. If
- an integer, then the result will be a 1-D array of that length.
- One shape dimension can be -1. In this case, the value is inferred
- from the length of the array and remaining dimensions.
-
- Returns
- -------
- reshaped_array : ndarray
- This will be a new view object if possible; otherwise, it will
- be a copy.
-
-
- See Also
- --------
- ndarray.reshape : Equivalent method.
-
- Notes
- -----
-
- It is not always possible to change the shape of an array without
- copying the data. If you want an error to be raise if the data is copied,
- you should assign the new shape to the shape attribute of the array
-'''
- if not hasattr(a, 'reshape'):
- a = _numpypy.array(a)
- return a.reshape(shape)
diff --git a/pypy/module/micronumpy/interp_dtype.py b/pypy/module/micronumpy/interp_dtype.py
--- a/pypy/module/micronumpy/interp_dtype.py
+++ b/pypy/module/micronumpy/interp_dtype.py
@@ -20,7 +20,7 @@
class W_Dtype(Wrappable):
_immutable_fields_ = ["itemtype", "num", "kind"]
- def __init__(self, itemtype, num, kind, name, char, w_box_type, alternate_constructors=[]):
+ def __init__(self, itemtype, num, kind, name, char, w_box_type, alternate_constructors=[], aliases=[]):
self.itemtype = itemtype
self.num = num
self.kind = kind
@@ -28,6 +28,7 @@
self.char = char
self.w_box_type = w_box_type
self.alternate_constructors = alternate_constructors
+ self.aliases = aliases
def malloc(self, length):
# XXX find out why test_zjit explodes with tracking of allocations
@@ -46,6 +47,10 @@
def getitem(self, storage, i):
return self.itemtype.read(storage, self.itemtype.get_element_size(), i, 0)
+ def getitem_bool(self, storage, i):
+ isize = self.itemtype.get_element_size()
+ return self.itemtype.read_bool(storage, isize, i, 0)
+
def setitem(self, storage, i, box):
self.itemtype.store(storage, self.itemtype.get_element_size(), i, 0, box)
@@ -62,7 +67,7 @@
elif space.isinstance_w(w_dtype, space.w_str):
name = space.str_w(w_dtype)
for dtype in cache.builtin_dtypes:
- if dtype.name == name or dtype.char == name:
+ if dtype.name == name or dtype.char == name or name in dtype.aliases:
return dtype
else:
for dtype in cache.builtin_dtypes:
@@ -84,6 +89,12 @@
def descr_get_shape(self, space):
return space.newtuple([])
+ def is_int_type(self):
+ return self.kind == SIGNEDLTR or self.kind == UNSIGNEDLTR
+
+ def is_bool_type(self):
+ return self.kind == BOOLLTR
+
W_Dtype.typedef = TypeDef("dtype",
__module__ = "numpypy",
__new__ = interp2app(W_Dtype.descr__new__.im_func),
@@ -107,7 +118,7 @@
kind=BOOLLTR,
name="bool",
char="?",
- w_box_type = space.gettypefor(interp_boxes.W_BoolBox),
+ w_box_type=space.gettypefor(interp_boxes.W_BoolBox),
alternate_constructors=[space.w_bool],
)
self.w_int8dtype = W_Dtype(
@@ -116,7 +127,7 @@
kind=SIGNEDLTR,
name="int8",
char="b",
- w_box_type = space.gettypefor(interp_boxes.W_Int8Box)
+ w_box_type=space.gettypefor(interp_boxes.W_Int8Box)
)
self.w_uint8dtype = W_Dtype(
types.UInt8(),
@@ -124,7 +135,7 @@
kind=UNSIGNEDLTR,
name="uint8",
char="B",
- w_box_type = space.gettypefor(interp_boxes.W_UInt8Box),
+ w_box_type=space.gettypefor(interp_boxes.W_UInt8Box),
)
self.w_int16dtype = W_Dtype(
types.Int16(),
@@ -132,7 +143,7 @@
kind=SIGNEDLTR,
name="int16",
char="h",
- w_box_type = space.gettypefor(interp_boxes.W_Int16Box),
+ w_box_type=space.gettypefor(interp_boxes.W_Int16Box),
)
self.w_uint16dtype = W_Dtype(
types.UInt16(),
@@ -140,7 +151,7 @@
kind=UNSIGNEDLTR,
name="uint16",
char="H",
- w_box_type = space.gettypefor(interp_boxes.W_UInt16Box),
+ w_box_type=space.gettypefor(interp_boxes.W_UInt16Box),
)
self.w_int32dtype = W_Dtype(
types.Int32(),
@@ -148,7 +159,7 @@
kind=SIGNEDLTR,
name="int32",
char="i",
- w_box_type = space.gettypefor(interp_boxes.W_Int32Box),
+ w_box_type=space.gettypefor(interp_boxes.W_Int32Box),
)
self.w_uint32dtype = W_Dtype(
types.UInt32(),
@@ -156,7 +167,7 @@
kind=UNSIGNEDLTR,
name="uint32",
char="I",
- w_box_type = space.gettypefor(interp_boxes.W_UInt32Box),
+ w_box_type=space.gettypefor(interp_boxes.W_UInt32Box),
)
if LONG_BIT == 32:
name = "int32"
@@ -168,7 +179,7 @@
kind=SIGNEDLTR,
name=name,
char="l",
- w_box_type = space.gettypefor(interp_boxes.W_LongBox),
+ w_box_type=space.gettypefor(interp_boxes.W_LongBox),
alternate_constructors=[space.w_int],
)
self.w_ulongdtype = W_Dtype(
@@ -177,7 +188,7 @@
kind=UNSIGNEDLTR,
name="u" + name,
char="L",
- w_box_type = space.gettypefor(interp_boxes.W_ULongBox),
+ w_box_type=space.gettypefor(interp_boxes.W_ULongBox),
)
self.w_int64dtype = W_Dtype(
types.Int64(),
@@ -185,7 +196,7 @@
kind=SIGNEDLTR,
name="int64",
char="q",
- w_box_type = space.gettypefor(interp_boxes.W_Int64Box),
+ w_box_type=space.gettypefor(interp_boxes.W_Int64Box),
alternate_constructors=[space.w_long],
)
self.w_uint64dtype = W_Dtype(
@@ -194,7 +205,7 @@
kind=UNSIGNEDLTR,
name="uint64",
char="Q",
- w_box_type = space.gettypefor(interp_boxes.W_UInt64Box),
+ w_box_type=space.gettypefor(interp_boxes.W_UInt64Box),
)
self.w_float32dtype = W_Dtype(
types.Float32(),
@@ -202,7 +213,7 @@
kind=FLOATINGLTR,
name="float32",
char="f",
- w_box_type = space.gettypefor(interp_boxes.W_Float32Box),
+ w_box_type=space.gettypefor(interp_boxes.W_Float32Box),
)
self.w_float64dtype = W_Dtype(
types.Float64(),
@@ -212,6 +223,7 @@
char="d",
w_box_type = space.gettypefor(interp_boxes.W_Float64Box),
alternate_constructors=[space.w_float],
+ aliases=["float"],
)
self.builtin_dtypes = [
diff --git a/pypy/module/micronumpy/interp_iter.py b/pypy/module/micronumpy/interp_iter.py
--- a/pypy/module/micronumpy/interp_iter.py
+++ b/pypy/module/micronumpy/interp_iter.py
@@ -4,6 +4,19 @@
from pypy.module.micronumpy.strides import calculate_broadcast_strides,\
calculate_slice_strides
+# structures to describe slicing
+
+class Chunk(object):
+ def __init__(self, start, stop, step, lgt):
+ self.start = start
+ self.stop = stop
+ self.step = step
+ self.lgt = lgt
+
+ def extend_shape(self, shape):
+ if self.step != 0:
+ shape.append(self.lgt)
+
class BaseTransform(object):
pass
@@ -38,11 +51,18 @@
self.size = size
def next(self, shapelen):
+ return self._next(1)
+
+ def _next(self, ofs):
arr = instantiate(ArrayIterator)
arr.size = self.size
- arr.offset = self.offset + 1
+ arr.offset = self.offset + ofs
return arr
+ def next_no_increase(self, shapelen):
+ # a hack to make JIT believe this is always virtual
+ return self._next(0)
+
def done(self):
return self.offset >= self.size
@@ -157,6 +177,8 @@
offset += self.strides[i]
break
else:
+ if i == self.dim:
+ first_line = True
indices[i] = 0
offset -= self.backstrides[i]
else:
diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py
--- a/pypy/module/micronumpy/interp_numarray.py
+++ b/pypy/module/micronumpy/interp_numarray.py
@@ -2,14 +2,15 @@
from pypy.interpreter.error import OperationError, operationerrfmt
from pypy.interpreter.gateway import interp2app, NoneNotWrapped
from pypy.interpreter.typedef import TypeDef, GetSetProperty
-from pypy.module.micronumpy import interp_ufuncs, interp_dtype, signature
+from pypy.module.micronumpy import interp_ufuncs, interp_dtype, signature,\
+ interp_boxes
from pypy.module.micronumpy.strides import calculate_slice_strides
from pypy.rlib import jit
from pypy.rpython.lltypesystem import lltype, rffi
from pypy.tool.sourcetools import func_with_new_name
from pypy.rlib.rstring import StringBuilder
from pypy.module.micronumpy.interp_iter import ArrayIterator, OneDimIterator,\
- SkipLastAxisIterator
+ SkipLastAxisIterator, Chunk, ViewIterator
numpy_driver = jit.JitDriver(
greens=['shapelen', 'sig'],
@@ -39,7 +40,24 @@
get_printable_location=signature.new_printable_location('slice'),
name='numpy_slice',
)
-
+count_driver = jit.JitDriver(
+ greens=['shapelen'],
+ virtualizables=['frame'],
+ reds=['s', 'frame', 'iter', 'arr'],
+ name='numpy_count'
+)
+filter_driver = jit.JitDriver(
+ greens=['shapelen', 'sig'],
+ virtualizables=['frame'],
+ reds=['concr', 'argi', 'ri', 'frame', 'v', 'res', 'self'],
+ name='numpy_filter',
+)
+filter_set_driver = jit.JitDriver(
+ greens=['shapelen', 'sig'],
+ virtualizables=['frame'],
+ reds=['idx', 'idxi', 'frame', 'arr'],
+ name='numpy_filterset',
+)
def _find_shape_and_elems(space, w_iterable):
shape = [space.len_w(w_iterable)]
@@ -157,9 +175,6 @@
# (meaning that the realignment of elements crosses from one step into another)
# return None so that the caller can raise an exception.
def calc_new_strides(new_shape, old_shape, old_strides):
- # Return the proper strides for new_shape, or None if the mapping crosses
- # stepping boundaries
-
# Assumes that prod(old_shape) == prod(new_shape), len(old_shape) > 1, and
# len(new_shape) > 0
steps = []
@@ -167,6 +182,7 @@
oldI = 0
new_strides = []
if old_strides[0] < old_strides[-1]:
+ #Start at old_shape[0], old_stides[0]
for i in range(len(old_shape)):
steps.append(old_strides[i] / last_step)
last_step *= old_shape[i]
@@ -184,10 +200,11 @@
if n_new_elems_used == n_old_elems_to_use:
oldI += 1
if oldI >= len(old_shape):
- break
+ continue
cur_step = steps[oldI]
n_old_elems_to_use *= old_shape[oldI]
else:
+ #Start at old_shape[-1], old_strides[-1]
for i in range(len(old_shape) - 1, -1, -1):
steps.insert(0, old_strides[i] / last_step)
last_step *= old_shape[i]
@@ -207,7 +224,7 @@
if n_new_elems_used == n_old_elems_to_use:
oldI -= 1
if oldI < -len(old_shape):
- break
+ continue
cur_step = steps[oldI]
n_old_elems_to_use *= old_shape[oldI]
return new_strides
@@ -271,6 +288,9 @@
descr_gt = _binop_impl("greater")
descr_ge = _binop_impl("greater_equal")
+ descr_and = _binop_impl("bitwise_and")
+ descr_or = _binop_impl("bitwise_or")
+
def _binop_right_impl(ufunc_name):
def impl(self, space, w_other):
w_other = scalar_w(space,
@@ -288,11 +308,11 @@
descr_rmod = _binop_right_impl("mod")
def _reduce_ufunc_impl(ufunc_name, promote_to_largest=False):
- def impl(self, space, w_dim=None):
- if space.is_w(w_dim, space.w_None):
- w_dim = space.wrap(-1)
+ def impl(self, space, w_axis=None):
+ if space.is_w(w_axis, space.w_None):
+ w_axis = space.wrap(-1)
return getattr(interp_ufuncs.get(space), ufunc_name).reduce(space,
- self, True, promote_to_largest, w_dim)
+ self, True, promote_to_largest, w_axis)
return func_with_new_name(impl, "reduce_%s_impl" % ufunc_name)
descr_sum = _reduce_ufunc_impl("add")
@@ -410,9 +430,15 @@
def descr_copy(self, space):
return self.copy(space)
+ def descr_flatten(self, space):
+ return self.flatten(space)
+
def copy(self, space):
return self.get_concrete().copy(space)
+ def flatten(self, space):
+ return self.get_concrete().flatten(space)
+
def descr_len(self, space):
if len(self.shape):
return space.wrap(self.shape[0])
@@ -480,11 +506,69 @@
def _prepare_slice_args(self, space, w_idx):
if (space.isinstance_w(w_idx, space.w_int) or
space.isinstance_w(w_idx, space.w_slice)):
- return [space.decode_index4(w_idx, self.shape[0])]
- return [space.decode_index4(w_item, self.shape[i]) for i, w_item in
+ return [Chunk(*space.decode_index4(w_idx, self.shape[0]))]
+ return [Chunk(*space.decode_index4(w_item, self.shape[i])) for i, w_item in
enumerate(space.fixedview(w_idx))]
+ def count_all_true(self, arr):
+ sig = arr.find_sig()
+ frame = sig.create_frame(self)
+ shapelen = len(arr.shape)
+ s = 0
+ iter = None
+ while not frame.done():
+ count_driver.jit_merge_point(arr=arr, frame=frame, iter=iter, s=s,
+ shapelen=shapelen)
+ iter = frame.get_final_iter()
+ s += arr.dtype.getitem_bool(arr.storage, iter.offset)
+ frame.next(shapelen)
+ return s
+
+ def getitem_filter(self, space, arr):
+ concr = arr.get_concrete()
+ size = self.count_all_true(concr)
+ res = W_NDimArray(size, [size], self.find_dtype())
+ ri = ArrayIterator(size)
+ shapelen = len(self.shape)
+ argi = concr.create_iter()
+ sig = self.find_sig()
+ frame = sig.create_frame(self)
+ v = None
+ while not frame.done():
+ filter_driver.jit_merge_point(concr=concr, argi=argi, ri=ri,
+ frame=frame, v=v, res=res, sig=sig,
+ shapelen=shapelen, self=self)
+ if concr.dtype.getitem_bool(concr.storage, argi.offset):
+ v = sig.eval(frame, self)
+ res.setitem(ri.offset, v)
+ ri = ri.next(1)
+ else:
+ ri = ri.next_no_increase(1)
+ argi = argi.next(shapelen)
+ frame.next(shapelen)
+ return res
+
+ def setitem_filter(self, space, idx, val):
+ size = self.count_all_true(idx)
+ arr = SliceArray([size], self.dtype, self, val)
+ sig = arr.find_sig()
+ shapelen = len(self.shape)
+ frame = sig.create_frame(arr)
+ idxi = idx.create_iter()
+ while not frame.done():
+ filter_set_driver.jit_merge_point(idx=idx, idxi=idxi, sig=sig,
+ frame=frame, arr=arr,
+ shapelen=shapelen)
+ if idx.dtype.getitem_bool(idx.storage, idxi.offset):
+ sig.eval(frame, arr)
+ frame.next_from_second(1)
+ frame.next_first(shapelen)
+ idxi = idxi.next(shapelen)
+
def descr_getitem(self, space, w_idx):
+ if (isinstance(w_idx, BaseArray) and w_idx.shape == self.shape and
+ w_idx.find_dtype().is_bool_type()):
+ return self.getitem_filter(space, w_idx)
if self._single_item_result(space, w_idx):
concrete = self.get_concrete()
item = concrete._index_of_single_item(space, w_idx)
@@ -494,6 +578,11 @@
def descr_setitem(self, space, w_idx, w_value):
self.invalidated()
+ if (isinstance(w_idx, BaseArray) and w_idx.shape == self.shape and
+ w_idx.find_dtype().is_bool_type()):
+ return self.get_concrete().setitem_filter(space,
+ w_idx.get_concrete(),
+ convert_to_array(space, w_value))
if self._single_item_result(space, w_idx):
concrete = self.get_concrete()
item = concrete._index_of_single_item(space, w_idx)
@@ -510,9 +599,8 @@
def create_slice(self, chunks):
shape = []
i = -1
- for i, (start_, stop, step, lgt) in enumerate(chunks):
- if step != 0:
- shape.append(lgt)
+ for i, chunk in enumerate(chunks):
+ chunk.extend_shape(shape)
s = i + 1
assert s >= 0
shape += self.shape[s:]
@@ -570,19 +658,19 @@
)
return w_result
- def descr_mean(self, space, w_dim=None):
- if space.is_w(w_dim, space.w_None):
- w_dim = space.wrap(-1)
+ def descr_mean(self, space, w_axis=None):
+ if space.is_w(w_axis, space.w_None):
+ w_axis = space.wrap(-1)
w_denom = space.wrap(self.size)
else:
- dim = space.int_w(w_dim)
+ dim = space.int_w(w_axis)
w_denom = space.wrap(self.shape[dim])
- return space.div(self.descr_sum_promote(space, w_dim), w_denom)
+ return space.div(self.descr_sum_promote(space, w_axis), w_denom)
def descr_var(self, space):
# var = mean((values - mean(values)) ** 2)
w_res = self.descr_sub(space, self.descr_mean(space, space.w_None))
- assert isinstance(w_res, BaseArray)
+ assert isinstance(w_res, BaseArray)
w_res = w_res.descr_pow(space, space.wrap(2))
assert isinstance(w_res, BaseArray)
return w_res.descr_mean(space, space.w_None)
@@ -591,6 +679,10 @@
# std(v) = sqrt(var(v))
return interp_ufuncs.get(space).sqrt.call(space, [self.descr_var(space)])
+ def descr_fill(self, space, w_value):
+ concr = self.get_concrete_or_scalar()
+ concr.fill(space, w_value)
+
def descr_nonzero(self, space):
if self.size > 1:
raise OperationError(space.w_ValueError, space.wrap(
@@ -683,6 +775,14 @@
def copy(self, space):
return Scalar(self.dtype, self.value)
+ def flatten(self, space):
+ array = W_NDimArray(self.size, [self.size], self.dtype)
+ array.setitem(0, self.value)
+ return array
+
+ def fill(self, space, w_value):
+ self.value = self.dtype.coerce(space, w_value)
+
def create_sig(self):
return signature.ScalarSignature(self.dtype)
@@ -718,8 +818,7 @@
frame=frame,
ri=ri,
self=self, result=result)
- result.dtype.setitem(result.storage, ri.offset,
- sig.eval(frame, self))
+ result.setitem(ri.offset, sig.eval(frame, self))
frame.next(shapelen)
ri = ri.next(shapelen)
return result
@@ -789,7 +888,7 @@
Intermediate class for performing binary operations.
"""
_immutable_fields_ = ['left', 'right']
-
+
def __init__(self, ufunc, name, shape, calc_dtype, res_dtype, left, right):
VirtualArray.__init__(self, name, shape, res_dtype)
self.ufunc = ufunc
@@ -826,14 +925,15 @@
self.left.create_sig(), self.right.create_sig())
class SliceArray(Call2):
- def __init__(self, shape, dtype, left, right):
+ def __init__(self, shape, dtype, left, right, no_broadcast=False):
+ self.no_broadcast = no_broadcast
Call2.__init__(self, None, 'sliceloop', shape, dtype, dtype, left,
right)
-
+
def create_sig(self):
lsig = self.left.create_sig()
rsig = self.right.create_sig()
- if self.shape != self.right.shape:
+ if not self.no_broadcast and self.shape != self.right.shape:
return signature.SliceloopBroadcastSignature(self.ufunc,
self.name,
self.calc_dtype,
@@ -848,7 +948,7 @@
when we'll make AxisReduce lazy
"""
_immutable_fields_ = ['left', 'right']
-
+
def __init__(self, ufunc, name, shape, dtype, left, right, dim):
Call2.__init__(self, ufunc, name, shape, dtype, dtype,
left, right)
@@ -920,14 +1020,14 @@
if size < 1:
builder.append('[]')
return
- elif size == 1:
- builder.append(dtype.itemtype.str_format(self.getitem(0)))
- return
if size > 1000:
# Once this goes True it does not go back to False for recursive
# calls
use_ellipsis = True
ndims = len(self.shape)
+ if ndims == 0:
+ builder.append(dtype.itemtype.str_format(self.getitem(0)))
+ return
i = 0
builder.append('[')
if ndims > 1:
@@ -939,7 +1039,7 @@
builder.append('\n' + indent)
else:
builder.append(indent)
- view = self.create_slice([(i, 0, 0, 1)]).get_concrete()
+ view = self.create_slice([Chunk(i, 0, 0, 1)]).get_concrete()
view.to_str(space, comma, builder, indent=indent + ' ',
use_ellipsis=use_ellipsis)
if i < self.shape[0] - 1:
@@ -956,7 +1056,7 @@
builder.append(indent)
# create_slice requires len(chunks) > 1 in order to reduce
# shape
- view = self.create_slice([(i, 0, 0, 1)]).get_concrete()
+ view = self.create_slice([Chunk(i, 0, 0, 1)]).get_concrete()
view.to_str(space, comma, builder, indent=indent + ' ',
use_ellipsis=use_ellipsis)
i += 1
@@ -1062,6 +1162,18 @@
array.setslice(space, self)
return array
+ def flatten(self, space):
+ array = W_NDimArray(self.size, [self.size], self.dtype, self.order)
+ if self.supports_fast_slicing():
+ array._fast_setslice(space, self)
+ else:
+ arr = SliceArray(array.shape, array.dtype, array, self, no_broadcast=True)
+ array._sliceloop(arr)
+ return array
+
+ def fill(self, space, w_value):
+ self.setslice(space, scalar_w(space, self.dtype, w_value))
+
class ViewArray(ConcreteArray):
def create_sig(self):
@@ -1082,6 +1194,10 @@
parent)
self.start = start
+ def create_iter(self):
+ return ViewIterator(self.start, self.strides, self.backstrides,
+ self.shape)
+
def setshape(self, space, new_shape):
if len(self.shape) < 1:
return
@@ -1128,6 +1244,9 @@
self.shape = new_shape
self.calc_strides(new_shape)
+ def create_iter(self):
+ return ArrayIterator(self.size)
+
def create_sig(self):
return signature.ArraySignature(self.dtype)
@@ -1182,6 +1301,7 @@
arr = W_NDimArray(size, shape[:], dtype=dtype, order=order)
shapelen = len(shape)
arr_iter = ArrayIterator(arr.size)
+ # XXX we might want to have a jitdriver here
for i in range(len(elems_w)):
w_elem = elems_w[i]
dtype.setitem(arr.storage, arr_iter.offset,
@@ -1248,6 +1368,9 @@
__gt__ = interp2app(BaseArray.descr_gt),
__ge__ = interp2app(BaseArray.descr_ge),
+ __and__ = interp2app(BaseArray.descr_and),
+ __or__ = interp2app(BaseArray.descr_or),
+
__repr__ = interp2app(BaseArray.descr_repr),
__str__ = interp2app(BaseArray.descr_str),
__array_interface__ = GetSetProperty(BaseArray.descr_array_iface),
@@ -1274,7 +1397,10 @@
var = interp2app(BaseArray.descr_var),
std = interp2app(BaseArray.descr_std),
+ fill = interp2app(BaseArray.descr_fill),
+
copy = interp2app(BaseArray.descr_copy),
+ flatten = interp2app(BaseArray.descr_flatten),
reshape = interp2app(BaseArray.descr_reshape),
tolist = interp2app(BaseArray.descr_tolist),
)
diff --git a/pypy/module/micronumpy/interp_ufuncs.py b/pypy/module/micronumpy/interp_ufuncs.py
--- a/pypy/module/micronumpy/interp_ufuncs.py
+++ b/pypy/module/micronumpy/interp_ufuncs.py
@@ -249,15 +249,16 @@
class W_Ufunc2(W_Ufunc):
- _immutable_fields_ = ["comparison_func", "func", "name"]
+ _immutable_fields_ = ["comparison_func", "func", "name", "int_only"]
argcount = 2
def __init__(self, func, name, promote_to_float=False, promote_bools=False,
- identity=None, comparison_func=False):
+ identity=None, comparison_func=False, int_only=False):
W_Ufunc.__init__(self, name, promote_to_float, promote_bools, identity)
self.func = func
self.comparison_func = comparison_func
+ self.int_only = int_only
def call(self, space, args_w):
from pypy.module.micronumpy.interp_numarray import (Call2,
@@ -268,6 +269,7 @@
w_rhs = convert_to_array(space, w_rhs)
calc_dtype = find_binop_result_dtype(space,
w_lhs.find_dtype(), w_rhs.find_dtype(),
+ int_only=self.int_only,
promote_to_float=self.promote_to_float,
promote_bools=self.promote_bools,
)
@@ -304,10 +306,12 @@
def find_binop_result_dtype(space, dt1, dt2, promote_to_float=False,
- promote_bools=False):
+ promote_bools=False, int_only=False):
# dt1.num should be <= dt2.num
if dt1.num > dt2.num:
dt1, dt2 = dt2, dt1
+ if int_only and (not dt1.is_int_type() or not dt2.is_int_type()):
+ raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
# Some operations promote op(bool, bool) to return int8, rather than bool
if promote_bools and (dt1.kind == dt2.kind == interp_dtype.BOOLLTR):
return interp_dtype.get_dtype_cache(space).w_int8dtype
@@ -425,6 +429,10 @@
("add", "add", 2, {"identity": 0}),
("subtract", "sub", 2),
("multiply", "mul", 2, {"identity": 1}),
+ ("bitwise_and", "bitwise_and", 2, {"identity": 1,
+ 'int_only': True}),
+ ("bitwise_or", "bitwise_or", 2, {"identity": 0,
+ 'int_only': True}),
("divide", "div", 2, {"promote_bools": True}),
("mod", "mod", 2, {"promote_bools": True}),
("power", "pow", 2, {"promote_bools": True}),
@@ -449,6 +457,7 @@
("fabs", "fabs", 1, {"promote_to_float": True}),
("floor", "floor", 1, {"promote_to_float": True}),
+ ("ceil", "ceil", 1, {"promote_to_float": True}),
("exp", "exp", 1, {"promote_to_float": True}),
('sqrt', 'sqrt', 1, {'promote_to_float': True}),
@@ -475,7 +484,7 @@
extra_kwargs["identity"] = identity
func = ufunc_dtype_caller(space, ufunc_name, op_name, argcount,
- comparison_func=extra_kwargs.get("comparison_func", False)
+ comparison_func=extra_kwargs.get("comparison_func", False),
)
if argcount == 1:
ufunc = W_Ufunc1(func, ufunc_name, **extra_kwargs)
diff --git a/pypy/module/micronumpy/signature.py b/pypy/module/micronumpy/signature.py
--- a/pypy/module/micronumpy/signature.py
+++ b/pypy/module/micronumpy/signature.py
@@ -82,6 +82,16 @@
for i in range(len(self.iterators)):
self.iterators[i] = self.iterators[i].next(shapelen)
+ @unroll_safe
+ def next_from_second(self, shapelen):
+ """ Don't increase the first iterator
+ """
+ for i in range(1, len(self.iterators)):
+ self.iterators[i] = self.iterators[i].next(shapelen)
+
+ def next_first(self, shapelen):
+ self.iterators[0] = self.iterators[0].next(shapelen)
+
def get_final_iter(self):
final_iter = promote(self.final_iter)
if final_iter < 0:
diff --git a/pypy/module/micronumpy/strides.py b/pypy/module/micronumpy/strides.py
--- a/pypy/module/micronumpy/strides.py
+++ b/pypy/module/micronumpy/strides.py
@@ -10,12 +10,12 @@
rstart = start
rshape = []
i = -1
- for i, (start_, stop, step, lgt) in enumerate(chunks):
- if step != 0:
- rstrides.append(strides[i] * step)
- rbackstrides.append(strides[i] * (lgt - 1) * step)
- rshape.append(lgt)
- rstart += strides[i] * start_
+ for i, chunk in enumerate(chunks):
+ if chunk.step != 0:
+ rstrides.append(strides[i] * chunk.step)
+ rbackstrides.append(strides[i] * (chunk.lgt - 1) * chunk.step)
+ rshape.append(chunk.lgt)
+ rstart += strides[i] * chunk.start
# add a reminder
s = i + 1
assert s >= 0
diff --git a/pypy/module/micronumpy/test/test_dtypes.py b/pypy/module/micronumpy/test/test_dtypes.py
--- a/pypy/module/micronumpy/test/test_dtypes.py
+++ b/pypy/module/micronumpy/test/test_dtypes.py
@@ -166,14 +166,11 @@
# You can't subclass dtype
raises(TypeError, type, "Foo", (dtype,), {})
- def test_new(self):
- import _numpypy as np
- assert np.int_(4) == 4
- assert np.float_(3.4) == 3.4
+ def test_aliases(self):
+ from _numpypy import dtype
- def test_pow(self):
- from _numpypy import int_
- assert int_(4) ** 2 == 16
+ assert dtype("float") is dtype(float)
+
class AppTestTypes(BaseNumpyAppTest):
def test_abstract_types(self):
@@ -189,6 +186,15 @@
raises(TypeError, numpy.floating, 0)
raises(TypeError, numpy.inexact, 0)
+ def test_new(self):
+ import _numpypy as np
+ assert np.int_(4) == 4
+ assert np.float_(3.4) == 3.4
+
+ def test_pow(self):
+ from _numpypy import int_
+ assert int_(4) ** 2 == 16
+
def test_bool(self):
import _numpypy as numpy
@@ -318,7 +324,7 @@
else:
raises(OverflowError, numpy.int64, 9223372036854775807)
raises(OverflowError, numpy.int64, '9223372036854775807')
-
+
raises(OverflowError, numpy.int64, 9223372036854775808)
raises(OverflowError, numpy.int64, '9223372036854775808')
diff --git a/pypy/module/micronumpy/test/test_module.py b/pypy/module/micronumpy/test/test_module.py
--- a/pypy/module/micronumpy/test/test_module.py
+++ b/pypy/module/micronumpy/test/test_module.py
@@ -2,16 +2,11 @@
class AppTestNumPyModule(BaseNumpyAppTest):
- def test_mean(self):
- from _numpypy import array, mean
- assert mean(array(range(5))) == 2.0
- assert mean(range(5)) == 2.0
-
def test_average(self):
from _numpypy import array, average
assert average(range(10)) == 4.5
assert average(array(range(10))) == 4.5
-
+
def test_sum(self):
from _numpypy import array, sum
assert sum(range(10)) == 45
@@ -21,7 +16,7 @@
from _numpypy import array, min
assert min(range(10)) == 0
assert min(array(range(10))) == 0
-
+
def test_max(self):
from _numpypy import array, max
assert max(range(10)) == 9
diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py
--- a/pypy/module/micronumpy/test/test_numarray.py
+++ b/pypy/module/micronumpy/test/test_numarray.py
@@ -2,6 +2,7 @@
import py
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
from pypy.module.micronumpy.interp_numarray import W_NDimArray, shape_agreement
+from pypy.module.micronumpy.interp_iter import Chunk
from pypy.module.micronumpy import signature
from pypy.interpreter.error import OperationError
from pypy.conftest import gettestobjspace
@@ -37,53 +38,54 @@
def test_create_slice_f(self):
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), 'F')
- s = a.create_slice([(3, 0, 0, 1)])
+ s = a.create_slice([Chunk(3, 0, 0, 1)])
assert s.start == 3
assert s.strides == [10, 50]
assert s.backstrides == [40, 100]
- s = a.create_slice([(1, 9, 2, 4)])
+ s = a.create_slice([Chunk(1, 9, 2, 4)])
assert s.start == 1
assert s.strides == [2, 10, 50]
assert s.backstrides == [6, 40, 100]
- s = a.create_slice([(1, 5, 3, 2), (1, 2, 1, 1), (1, 0, 0, 1)])
+ s = a.create_slice([Chunk(1, 5, 3, 2), Chunk(1, 2, 1, 1), Chunk(1, 0, 0, 1)])
assert s.shape == [2, 1]
assert s.strides == [3, 10]
assert s.backstrides == [3, 0]
- s = a.create_slice([(0, 10, 1, 10), (2, 0, 0, 1)])
+ s = a.create_slice([Chunk(0, 10, 1, 10), Chunk(2, 0, 0, 1)])
assert s.start == 20
assert s.shape == [10, 3]
def test_create_slice_c(self):
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), 'C')
- s = a.create_slice([(3, 0, 0, 1)])
+ s = a.create_slice([Chunk(3, 0, 0, 1)])
assert s.start == 45
assert s.strides == [3, 1]
assert s.backstrides == [12, 2]
- s = a.create_slice([(1, 9, 2, 4)])
+ s = a.create_slice([Chunk(1, 9, 2, 4)])
assert s.start == 15
assert s.strides == [30, 3, 1]
assert s.backstrides == [90, 12, 2]
- s = a.create_slice([(1, 5, 3, 2), (1, 2, 1, 1), (1, 0, 0, 1)])
+ s = a.create_slice([Chunk(1, 5, 3, 2), Chunk(1, 2, 1, 1),
+ Chunk(1, 0, 0, 1)])
assert s.start == 19
assert s.shape == [2, 1]
assert s.strides == [45, 3]
assert s.backstrides == [45, 0]
- s = a.create_slice([(0, 10, 1, 10), (2, 0, 0, 1)])
+ s = a.create_slice([Chunk(0, 10, 1, 10), Chunk(2, 0, 0, 1)])
assert s.start == 6
assert s.shape == [10, 3]
def test_slice_of_slice_f(self):
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), 'F')
- s = a.create_slice([(5, 0, 0, 1)])
+ s = a.create_slice([Chunk(5, 0, 0, 1)])
assert s.start == 5
- s2 = s.create_slice([(3, 0, 0, 1)])
+ s2 = s.create_slice([Chunk(3, 0, 0, 1)])
assert s2.shape == [3]
assert s2.strides == [50]
assert s2.parent is a
assert s2.backstrides == [100]
assert s2.start == 35
- s = a.create_slice([(1, 5, 3, 2)])
- s2 = s.create_slice([(0, 2, 1, 2), (2, 0, 0, 1)])
+ s = a.create_slice([Chunk(1, 5, 3, 2)])
+ s2 = s.create_slice([Chunk(0, 2, 1, 2), Chunk(2, 0, 0, 1)])
assert s2.shape == [2, 3]
assert s2.strides == [3, 50]
assert s2.backstrides == [3, 100]
@@ -91,16 +93,16 @@
def test_slice_of_slice_c(self):
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), order='C')
- s = a.create_slice([(5, 0, 0, 1)])
+ s = a.create_slice([Chunk(5, 0, 0, 1)])
assert s.start == 15 * 5
- s2 = s.create_slice([(3, 0, 0, 1)])
+ s2 = s.create_slice([Chunk(3, 0, 0, 1)])
assert s2.shape == [3]
assert s2.strides == [1]
assert s2.parent is a
assert s2.backstrides == [2]
assert s2.start == 5 * 15 + 3 * 3
- s = a.create_slice([(1, 5, 3, 2)])
- s2 = s.create_slice([(0, 2, 1, 2), (2, 0, 0, 1)])
+ s = a.create_slice([Chunk(1, 5, 3, 2)])
+ s2 = s.create_slice([Chunk(0, 2, 1, 2), Chunk(2, 0, 0, 1)])
assert s2.shape == [2, 3]
assert s2.strides == [45, 1]
assert s2.backstrides == [45, 2]
@@ -108,14 +110,14 @@
def test_negative_step_f(self):
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), 'F')
- s = a.create_slice([(9, -1, -2, 5)])
+ s = a.create_slice([Chunk(9, -1, -2, 5)])
assert s.start == 9
assert s.strides == [-2, 10, 50]
assert s.backstrides == [-8, 40, 100]
def test_negative_step_c(self):
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), order='C')
- s = a.create_slice([(9, -1, -2, 5)])
+ s = a.create_slice([Chunk(9, -1, -2, 5)])
assert s.start == 135
assert s.strides == [-30, 3, 1]
assert s.backstrides == [-120, 12, 2]
@@ -124,7 +126,7 @@
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), 'F')
r = a._index_of_single_item(self.space, self.newtuple(1, 2, 2))
assert r == 1 + 2 * 10 + 2 * 50
- s = a.create_slice([(0, 10, 1, 10), (2, 0, 0, 1)])
+ s = a.create_slice([Chunk(0, 10, 1, 10), Chunk(2, 0, 0, 1)])
r = s._index_of_single_item(self.space, self.newtuple(1, 0))
assert r == a._index_of_single_item(self.space, self.newtuple(1, 2, 0))
r = s._index_of_single_item(self.space, self.newtuple(1, 1))
@@ -134,7 +136,7 @@
a = W_NDimArray(10 * 5 * 3, [10, 5, 3], MockDtype(), 'C')
r = a._index_of_single_item(self.space, self.newtuple(1, 2, 2))
assert r == 1 * 3 * 5 + 2 * 3 + 2
- s = a.create_slice([(0, 10, 1, 10), (2, 0, 0, 1)])
+ s = a.create_slice([Chunk(0, 10, 1, 10), Chunk(2, 0, 0, 1)])
r = s._index_of_single_item(self.space, self.newtuple(1, 0))
assert r == a._index_of_single_item(self.space, self.newtuple(1, 2, 0))
r = s._index_of_single_item(self.space, self.newtuple(1, 1))
@@ -157,6 +159,8 @@
assert calc_new_strides([2, 3, 4], [8, 3], [1, 16]) is None
assert calc_new_strides([24], [2, 4, 3], [48, 6, 1]) is None
assert calc_new_strides([24], [2, 4, 3], [24, 6, 2]) == [2]
+ assert calc_new_strides([105, 1], [3, 5, 7], [35, 7, 1]) == [1, 1]
+ assert calc_new_strides([1, 105], [3, 5, 7], [35, 7, 1]) == [105, 1]
class AppTestNumArray(BaseNumpyAppTest):
@@ -724,15 +728,17 @@
assert d[1] == 12
def test_mean(self):
- from _numpypy import array, mean
+ from _numpypy import array, arange
a = array(range(5))
assert a.mean() == 2.0
assert a[:4].mean() == 1.5
a = array(range(105)).reshape(3, 5, 7)
- b = mean(a, axis=0)
- b[0,0]==35.
+ b = a.mean(axis=0)
+ b[0, 0]==35.
+ assert a.mean(axis=0)[0, 0] == 35
assert (b == array(range(35, 70), dtype=float).reshape(5, 7)).all()
- assert (mean(a, 2) == array(range(0, 15), dtype=float).reshape(3, 5) * 7 + 3).all()
+ assert (a.mean(2) == array(range(0, 15), dtype=float).reshape(3, 5) * 7 + 3).all()
+ assert (arange(10).reshape(5, 2).mean(axis=1) == [0.5, 2.5, 4.5, 6.5, 8.5]).all()
def test_sum(self):
from _numpypy import array
@@ -753,6 +759,7 @@
assert array([]).sum() == 0.0
raises(ValueError, 'array([]).max()')
assert (a.sum(0) == [30, 35, 40]).all()
+ assert (a.sum(axis=0) == [30, 35, 40]).all()
assert (a.sum(1) == [3, 12, 21, 30, 39]).all()
assert (a.max(0) == [12, 13, 14]).all()
assert (a.max(1) == [2, 5, 8, 11, 14]).all()
@@ -765,9 +772,10 @@
assert (a[:, 1, :].sum(1) == [70, 315, 560]).all()
raises (ValueError, 'a[:, 1, :].sum(2)')
assert ((a + a).T.sum(2).T == (a + a).sum(0)).all()
- skip("Those are broken on reshape, fix!")
assert (a.reshape(1,-1).sum(0) == range(105)).all()
assert (a.reshape(1,-1).sum(1) == 5460)
+ assert (array([[1,2],[3,4]]).prod(0) == [3, 8]).all()
+ assert (array([[1,2],[3,4]]).prod(1) == [2, 12]).all()
def test_identity(self):
from _numpypy import identity, array
@@ -1014,11 +1022,15 @@
assert a[0].tolist() == [17.1, 27.2]
def test_var(self):
- from _numpypy import array
+ from _numpypy import array, arange
a = array(range(10))
assert a.var() == 8.25
a = array([5.0])
assert a.var() == 0.0
+ a = arange(10).reshape(5, 2)
+ assert a.var() == 8.25
+ #assert (a.var(0) == [8, 8]).all()
+ #assert (a.var(1) == [.25] * 5).all()
def test_std(self):
from _numpypy import array
@@ -1027,6 +1039,22 @@
a = array([5.0])
assert a.std() == 0.0
+ def test_flatten(self):
+ from _numpypy import array
+
+ a = array([[1, 2, 3], [4, 5, 6]])
+ assert (a.flatten() == [1, 2, 3, 4, 5, 6]).all()
+ a = array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
+ assert (a.flatten() == [1, 2, 3, 4, 5, 6, 7, 8]).all()
+ a = array([1, 2, 3, 4, 5, 6, 7, 8])
+ assert (a[::2].flatten() == [1, 3, 5, 7]).all()
+ a = array([1, 2, 3])
+ assert ((a + a).flatten() == [2, 4, 6]).all()
+ a = array(2)
+ assert (a.flatten() == [2]).all()
+ a = array([[1, 2], [3, 4]])
+ assert (a.T.flatten() == [1, 3, 2, 4]).all()
+
class AppTestMultiDim(BaseNumpyAppTest):
def test_init(self):
@@ -1297,6 +1325,56 @@
assert isinstance(i['data'][0], int)
raises(TypeError, getattr, array(3), '__array_interface__')
+ def test_array_indexing_one_elem(self):
+ skip("not yet")
+ from _numpypy import array, arange
+ raises(IndexError, 'arange(3)[array([3.5])]')
+ a = arange(3)[array([1])]
+ assert a == 1
+ assert a[0] == 1
+ raises(IndexError,'arange(3)[array([15])]')
+ assert arange(3)[array([-3])] == 0
+ raises(IndexError,'arange(3)[array([-15])]')
+ assert arange(3)[array(1)] == 1
+
+ def test_fill(self):
+ from _numpypy import array
+ a = array([1, 2, 3])
+ a.fill(10)
+ assert (a == [10, 10, 10]).all()
+ a.fill(False)
+ assert (a == [0, 0, 0]).all()
+ b = a[:1]
+ b.fill(4)
+ assert (b == [4]).all()
+ assert (a == [4, 0, 0]).all()
+
+ c = b + b
+ c.fill(27)
+ assert (c == [27]).all()
+
+ d = array(10)
+ d.fill(100)
+ assert d == 100
+
+ def test_array_indexing_bool(self):
+ from _numpypy import arange
+ a = arange(10)
+ assert (a[a > 3] == [4, 5, 6, 7, 8, 9]).all()
+ a = arange(10).reshape(5, 2)
+ assert (a[a > 3] == [4, 5, 6, 7, 8, 9]).all()
+ assert (a[a & 1 == 1] == [1, 3, 5, 7, 9]).all()
+
+ def test_array_indexing_bool_setitem(self):
+ from _numpypy import arange, array
+ a = arange(6)
+ a[a > 3] = 15
+ assert (a == [0, 1, 2, 3, 15, 15]).all()
+ a = arange(6).reshape(3, 2)
+ a[a & 1 == 1] = array([8, 9, 10])
+ assert (a == [[0, 8], [2, 9], [4, 10]]).all()
+
+
class AppTestSupport(BaseNumpyAppTest):
def setup_class(cls):
@@ -1436,9 +1514,11 @@
assert repr(a) == "array(0.0)"
a = array(0.2)
assert repr(a) == "array(0.2)"
+ a = array([2])
+ assert repr(a) == "array([2])"
def test_repr_multi(self):
- from _numpypy import arange, zeros
+ from _numpypy import arange, zeros, array
a = zeros((3, 4))
assert repr(a) == '''array([[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
@@ -1461,6 +1541,9 @@
[498, 999],
[499, 1000],
[500, 1001]])'''
+ a = arange(2).reshape((2,1))
+ assert repr(a) == '''array([[0],
+ [1]])'''
def test_repr_slice(self):
from _numpypy import array, zeros
@@ -1545,14 +1628,3 @@
a = arange(0, 0.8, 0.1)
assert len(a) == 8
assert arange(False, True, True).dtype is dtype(int)
-
-
-class AppTestRanges(BaseNumpyAppTest):
- def test_app_reshape(self):
- from _numpypy import arange, array, dtype, reshape
- a = arange(12)
- b = reshape(a, (3, 4))
- assert b.shape == (3, 4)
- a = range(12)
- b = reshape(a, (3, 4))
- assert b.shape == (3, 4)
diff --git a/pypy/module/micronumpy/test/test_ufuncs.py b/pypy/module/micronumpy/test/test_ufuncs.py
--- a/pypy/module/micronumpy/test/test_ufuncs.py
+++ b/pypy/module/micronumpy/test/test_ufuncs.py
@@ -190,14 +190,24 @@
for i in range(3):
assert c[i] == a[i] - b[i]
- def test_floor(self):
- from _numpypy import array, floor
-
- reference = [-2.0, -1.0, 0.0, 1.0, 1.0]
- a = array([-1.4, -1.0, 0.0, 1.0, 1.4])
+ def test_floorceil(self):
+ from _numpypy import array, floor, ceil
+ import math
+ reference = [-2.0, -2.0, -1.0, 0.0, 1.0, 1.0, 0]
+ a = array([-1.4, -1.5, -1.0, 0.0, 1.0, 1.4, 0.5])
b = floor(a)
for i in range(5):
assert b[i] == reference[i]
+ reference = [-1.0, -1.0, -1.0, 0.0, 1.0, 2.0, 1.0]
+ a = array([-1.4, -1.5, -1.0, 0.0, 1.0, 1.4, 0.5])
+ b = ceil(a)
+ assert (reference == b).all()
+ inf = float("inf")
+ data = [1.5, 2.9999, -1.999, inf]
+ results = [math.floor(x) for x in data]
+ assert (floor(data) == results).all()
+ results = [math.ceil(x) for x in data]
+ assert (ceil(data) == results).all()
def test_copysign(self):
from _numpypy import array, copysign
@@ -238,7 +248,7 @@
assert b[i] == math.sin(a[i])
a = sin(array([True, False], dtype=bool))
- assert abs(a[0] - sin(1)) < 1e-7 # a[0] will be less precise
+ assert abs(a[0] - sin(1)) < 1e-7 # a[0] will be less precise
assert a[1] == 0.0
def test_cos(self):
@@ -259,7 +269,6 @@
for i in range(len(a)):
assert b[i] == math.tan(a[i])
-
def test_arcsin(self):
import math
from _numpypy import array, arcsin
@@ -283,7 +292,6 @@
for i in range(len(a)):
assert b[i] == math.acos(a[i])
-
a = array([-10, -1.5, -1.01, 1.01, 1.5, 10, float('nan'), float('inf'), float('-inf')])
b = arccos(a)
for f in b:
@@ -347,11 +355,20 @@
raises(ValueError, maximum.reduce, [])
def test_reduceND(self):
- from numpypy import add, arange
+ from _numpypy import add, arange
a = arange(12).reshape(3, 4)
assert (add.reduce(a, 0) == [12, 15, 18, 21]).all()
assert (add.reduce(a, 1) == [6.0, 22.0, 38.0]).all()
+ def test_bitwise(self):
+ from _numpypy import bitwise_and, bitwise_or, arange, array
+ a = arange(6).reshape(2, 3)
+ assert (a & 1 == [[0, 1, 0], [1, 0, 1]]).all()
+ assert (a & 1 == bitwise_and(a, 1)).all()
+ assert (a | 1 == [[1, 1, 3], [3, 5, 5]]).all()
+ assert (a | 1 == bitwise_or(a, 1)).all()
+ raises(TypeError, 'array([1.0]) & 1')
+
def test_comparisons(self):
import operator
from _numpypy import equal, not_equal, less, less_equal, greater, greater_equal
diff --git a/pypy/module/micronumpy/test/test_zjit.py b/pypy/module/micronumpy/test/test_zjit.py
--- a/pypy/module/micronumpy/test/test_zjit.py
+++ b/pypy/module/micronumpy/test/test_zjit.py
@@ -217,6 +217,7 @@
# This is the sum of the ops for both loops, however if you remove the
# optimization then you end up with 2 float_adds, so we can still be
# sure it was optimized correctly.
+ py.test.skip("too fragile")
self.check_resops({'setinteriorfield_raw': 4, 'getfield_gc': 22,
'getarrayitem_gc': 4, 'getarrayitem_gc_pure': 2,
'getfield_gc_pure': 8,
@@ -349,7 +350,8 @@
self.check_trace_count(1)
self.check_simple_loop({'getinteriorfield_raw': 2, 'float_add': 1,
'setinteriorfield_raw': 1, 'int_add': 2,
- 'int_eq': 1, 'guard_false': 1, 'jump': 1})
+ 'int_eq': 1, 'guard_false': 1, 'jump': 1,
+ 'arraylen_gc': 1})
def define_virtual_slice():
return """
diff --git a/pypy/module/micronumpy/types.py b/pypy/module/micronumpy/types.py
--- a/pypy/module/micronumpy/types.py
+++ b/pypy/module/micronumpy/types.py
@@ -94,6 +94,9 @@
width, storage, i, offset
))
+ def read_bool(self, storage, width, i, offset):
+ raise NotImplementedError
+
def store(self, storage, width, i, offset, box):
value = self.unbox(box)
libffi.array_setitem(clibffi.cast_type_to_ffitype(self.T),
@@ -168,6 +171,7 @@
@simple_binary_op
def min(self, v1, v2):
return min(v1, v2)
+
class Bool(BaseType, Primitive):
T = lltype.Bool
@@ -185,6 +189,11 @@
else:
return self.False
+
+ def read_bool(self, storage, width, i, offset):
+ return libffi.array_getitem(clibffi.cast_type_to_ffitype(self.T),
+ width, storage, i, offset)
+
def coerce_subtype(self, space, w_subtype, w_item):
# Doesn't return subclasses so it can return the constants.
return self._coerce(space, w_item)
@@ -253,6 +262,14 @@
assert v == 0
return 0
+ @simple_binary_op
+ def bitwise_and(self, v1, v2):
+ return v1 & v2
+
+ @simple_binary_op
+ def bitwise_or(self, v1, v2):
+ return v1 | v2
+
class Int8(BaseType, Integer):
T = rffi.SIGNEDCHAR
BoxType = interp_boxes.W_Int8Box
@@ -374,6 +391,10 @@
return math.floor(v)
@simple_unary_op
+ def ceil(self, v):
+ return math.ceil(v)
+
+ @simple_unary_op
def exp(self, v):
try:
return math.exp(v)
@@ -436,4 +457,4 @@
class Float64(BaseType, Float):
T = rffi.DOUBLE
BoxType = interp_boxes.W_Float64Box
- format_code = "d"
\ No newline at end of file
+ format_code = "d"
diff --git a/pypy/module/pypyjit/__init__.py b/pypy/module/pypyjit/__init__.py
--- a/pypy/module/pypyjit/__init__.py
+++ b/pypy/module/pypyjit/__init__.py
@@ -11,6 +11,7 @@
'set_optimize_hook': 'interp_resop.set_optimize_hook',
'set_abort_hook': 'interp_resop.set_abort_hook',
'ResOperation': 'interp_resop.WrappedOp',
+ 'DebugMergePoint': 'interp_resop.DebugMergePoint',
'Box': 'interp_resop.WrappedBox',
}
diff --git a/pypy/module/pypyjit/interp_resop.py b/pypy/module/pypyjit/interp_resop.py
--- a/pypy/module/pypyjit/interp_resop.py
+++ b/pypy/module/pypyjit/interp_resop.py
@@ -1,5 +1,6 @@
-from pypy.interpreter.typedef import TypeDef, GetSetProperty
+from pypy.interpreter.typedef import (TypeDef, GetSetProperty,
+ interp_attrproperty, interp_attrproperty_w)
from pypy.interpreter.baseobjspace import Wrappable
from pypy.interpreter.gateway import unwrap_spec, interp2app, NoneNotWrapped
from pypy.interpreter.pycode import PyCode
@@ -10,6 +11,7 @@
from pypy.jit.metainterp.resoperation import rop, AbstractResOp
from pypy.rlib.nonconst import NonConstant
from pypy.rlib import jit_hooks
+from pypy.module.pypyjit.interp_jit import pypyjitdriver
class Cache(object):
in_recursion = False
@@ -111,13 +113,24 @@
def wrap_oplist(space, logops, operations, ops_offset=None):
l_w = []
+ jitdrivers_sd = logops.metainterp_sd.jitdrivers_sd
for op in operations:
if ops_offset is None:
ofs = -1
else:
ofs = ops_offset.get(op, 0)
- l_w.append(WrappedOp(jit_hooks._cast_to_gcref(op), ofs,
- logops.repr_of_resop(op)))
+ if op.opnum == rop.DEBUG_MERGE_POINT:
+ jd_sd = jitdrivers_sd[op.getarg(0).getint()]
+ greenkey = op.getarglist()[2:]
+ repr = jd_sd.warmstate.get_location_str(greenkey)
+ w_greenkey = wrap_greenkey(space, jd_sd.jitdriver, greenkey, repr)
+ l_w.append(DebugMergePoint(space, jit_hooks._cast_to_gcref(op),
+ logops.repr_of_resop(op),
+ jd_sd.jitdriver.name,
+ w_greenkey))
+ else:
+ l_w.append(WrappedOp(jit_hooks._cast_to_gcref(op), ofs,
+ logops.repr_of_resop(op)))
return l_w
class WrappedBox(Wrappable):
@@ -150,6 +163,15 @@
llres = res.llbox
return WrappedOp(jit_hooks.resop_new(num, args, llres), offset, repr)
+ at unwrap_spec(repr=str, jd_name=str)
+def descr_new_dmp(space, w_tp, w_args, repr, jd_name, w_greenkey):
+ args = [space.interp_w(WrappedBox, w_arg).llbox for w_arg in
+ space.listview(w_args)]
+ num = rop.DEBUG_MERGE_POINT
+ return DebugMergePoint(space,
+ jit_hooks.resop_new(num, args, jit_hooks.emptyval()),
+ repr, jd_name, w_greenkey)
+
class WrappedOp(Wrappable):
""" A class representing a single ResOperation, wrapped nicely
"""
@@ -182,6 +204,25 @@
box = space.interp_w(WrappedBox, w_box)
jit_hooks.resop_setresult(self.op, box.llbox)
+class DebugMergePoint(WrappedOp):
+ def __init__(self, space, op, repr_of_resop, jd_name, w_greenkey):
+ WrappedOp.__init__(self, op, -1, repr_of_resop)
+ self.w_greenkey = w_greenkey
+ self.jd_name = jd_name
+
+ def get_pycode(self, space):
+ if self.jd_name == pypyjitdriver.name:
+ return space.getitem(self.w_greenkey, space.wrap(0))
+ raise OperationError(space.w_AttributeError, space.wrap("This DebugMergePoint doesn't belong to the main Python JitDriver"))
+
+ def get_bytecode_no(self, space):
+ if self.jd_name == pypyjitdriver.name:
+ return space.getitem(self.w_greenkey, space.wrap(1))
+ raise OperationError(space.w_AttributeError, space.wrap("This DebugMergePoint doesn't belong to the main Python JitDriver"))
+
+ def get_jitdriver_name(self, space):
+ return space.wrap(self.jd_name)
+
WrappedOp.typedef = TypeDef(
'ResOperation',
__doc__ = WrappedOp.__doc__,
@@ -195,3 +236,15 @@
WrappedOp.descr_setresult)
)
WrappedOp.acceptable_as_base_class = False
+
+DebugMergePoint.typedef = TypeDef(
+ 'DebugMergePoint', WrappedOp.typedef,
+ __new__ = interp2app(descr_new_dmp),
+ greenkey = interp_attrproperty_w("w_greenkey", cls=DebugMergePoint),
+ pycode = GetSetProperty(DebugMergePoint.get_pycode),
+ bytecode_no = GetSetProperty(DebugMergePoint.get_bytecode_no),
+ jitdriver_name = GetSetProperty(DebugMergePoint.get_jitdriver_name),
+)
+DebugMergePoint.acceptable_as_base_class = False
+
+
diff --git a/pypy/module/pypyjit/policy.py b/pypy/module/pypyjit/policy.py
--- a/pypy/module/pypyjit/policy.py
+++ b/pypy/module/pypyjit/policy.py
@@ -127,7 +127,7 @@
'imp', 'sys', 'array', '_ffi', 'itertools', 'operator',
'posix', '_socket', '_sre', '_lsprof', '_weakref',
'__pypy__', 'cStringIO', '_collections', 'struct',
- 'mmap', 'marshal']:
+ 'mmap', 'marshal', '_codecs']:
if modname == 'pypyjit' and 'interp_resop' in rest:
return False
return True
diff --git a/pypy/module/pypyjit/test/test_jit_hook.py b/pypy/module/pypyjit/test/test_jit_hook.py
--- a/pypy/module/pypyjit/test/test_jit_hook.py
+++ b/pypy/module/pypyjit/test/test_jit_hook.py
@@ -92,6 +92,7 @@
cls.w_on_compile_bridge = space.wrap(interp2app(interp_on_compile_bridge))
cls.w_on_abort = space.wrap(interp2app(interp_on_abort))
cls.w_int_add_num = space.wrap(rop.INT_ADD)
+ cls.w_dmp_num = space.wrap(rop.DEBUG_MERGE_POINT)
cls.w_on_optimize = space.wrap(interp2app(interp_on_optimize))
cls.orig_oplist = oplist
@@ -117,6 +118,10 @@
assert elem[2][2] == False
assert len(elem[3]) == 4
int_add = elem[3][0]
+ dmp = elem[3][1]
+ assert isinstance(dmp, pypyjit.DebugMergePoint)
+ assert dmp.pycode is self.f.func_code
+ assert dmp.greenkey == (self.f.func_code, 0, False)
#assert int_add.name == 'int_add'
assert int_add.num == self.int_add_num
self.on_compile_bridge()
@@ -211,3 +216,18 @@
assert op.getarg(0).getint() == 4
op.result = box
assert op.result.getint() == 1
+
+ def test_creation_dmp(self):
+ from pypyjit import DebugMergePoint, Box
+
+ def f():
+ pass
+
+ op = DebugMergePoint([Box(0)], 'repr', 'pypyjit', (f.func_code, 0, 0))
+ assert op.bytecode_no == 0
+ assert op.pycode is f.func_code
+ assert repr(op) == 'repr'
+ assert op.jitdriver_name == 'pypyjit'
+ assert op.num == self.dmp_num
+ op = DebugMergePoint([Box(0)], 'repr', 'notmain', ('str',))
+ raises(AttributeError, 'op.pycode')
diff --git a/pypy/module/pypyjit/test_pypy_c/test_math.py b/pypy/module/pypyjit/test_pypy_c/test_math.py
--- a/pypy/module/pypyjit/test_pypy_c/test_math.py
+++ b/pypy/module/pypyjit/test_pypy_c/test_math.py
@@ -90,3 +90,19 @@
--TICK--
jump(..., descr=)
""")
+
+ def test_pow_two(self):
+ def main(n):
+ s = 0.123
+ while n > 0:
+ s -= s ** 2 # ID: pow
+ n -= 1
+ return s
+ log = self.run(main, [500])
+ assert abs(log.result - main(500)) < 1e-9
+ loop, = log.loops_by_filename(self.filepath)
+ assert loop.match_by_id("pow", """
+ guard_not_invalidated(descr=...)
+ f38 = float_mul(f30, f30)
+ f39 = float_sub(f30, f38)
+ """)
diff --git a/pypy/module/sys/version.py b/pypy/module/sys/version.py
--- a/pypy/module/sys/version.py
+++ b/pypy/module/sys/version.py
@@ -10,7 +10,7 @@
CPYTHON_VERSION = (2, 7, 1, "final", 42) #XXX # sync patchlevel.h
CPYTHON_API_VERSION = 1013 #XXX # sync with include/modsupport.h
-PYPY_VERSION = (1, 7, 1, "dev", 0) #XXX # sync patchlevel.h
+PYPY_VERSION = (1, 8, 1, "dev", 0) #XXX # sync patchlevel.h
if platform.name == 'msvc':
COMPILER_INFO = 'MSC v.%d 32 bit' % (platform.version * 10 + 600)
diff --git a/lib_pypy/numpypy/test/test_fromnumeric.py b/pypy/module/test_lib_pypy/numpypy/core/test_fromnumeric.py
rename from lib_pypy/numpypy/test/test_fromnumeric.py
rename to pypy/module/test_lib_pypy/numpypy/core/test_fromnumeric.py
--- a/lib_pypy/numpypy/test/test_fromnumeric.py
+++ b/pypy/module/test_lib_pypy/numpypy/core/test_fromnumeric.py
@@ -1,7 +1,7 @@
-
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
-class AppTestFromNumeric(BaseNumpyAppTest):
+
+class AppTestFromNumeric(BaseNumpyAppTest):
def test_argmax(self):
# tests taken from numpy/core/fromnumeric.py docstring
from numpypy import array, arange, argmax
@@ -18,12 +18,12 @@
from numpypy import array, arange, argmin
a = arange(6).reshape((2,3))
assert argmin(a) == 0
- # assert (argmax(a, axis=0) == array([0, 0, 0])).all()
- # assert (argmax(a, axis=1) == array([0, 0])).all()
+ #assert (argmin(a, axis=0) == array([0, 0, 0])).all()
+ #assert (argmin(a, axis=1) == array([0, 0])).all()
b = arange(6)
b[1] = 0
assert argmin(b) == 0
-
+
def test_shape(self):
# tests taken from numpy/core/fromnumeric.py docstring
from numpypy import array, identity, shape
@@ -40,11 +40,11 @@
assert sum([0.5, 1.5])== 2.0
assert sum([[0, 1], [0, 5]]) == 6
# assert sum([0.5, 0.7, 0.2, 1.5], dtype=int32) == 1
- # assert (sum([[0, 1], [0, 5]], axis=0) == array([0, 6])).all()
- # assert (sum([[0, 1], [0, 5]], axis=1) == array([1, 5])).all()
+ assert (sum([[0, 1], [0, 5]], axis=0) == array([0, 6])).all()
+ assert (sum([[0, 1], [0, 5]], axis=1) == array([1, 5])).all()
# If the accumulator is too small, overflow occurs:
# assert ones(128, dtype=int8).sum(dtype=int8) == -128
-
+
def test_amin(self):
# tests taken from numpy/core/fromnumeric.py docstring
from numpypy import array, arange, amin
@@ -86,24 +86,54 @@
assert ndim([[1,2,3],[4,5,6]]) == 2
assert ndim(array([[1,2,3],[4,5,6]])) == 2
assert ndim(1) == 0
-
+
def test_rank(self):
# tests taken from numpy/core/fromnumeric.py docstring
from numpypy import array, rank
assert rank([[1,2,3],[4,5,6]]) == 2
assert rank(array([[1,2,3],[4,5,6]])) == 2
assert rank(1) == 0
-
+
def test_var(self):
from numpypy import array, var
a = array([[1,2],[3,4]])
assert var(a) == 1.25
- # assert (np.var(a,0) == array([ 1., 1.])).all()
- # assert (np.var(a,1) == array([ 0.25, 0.25])).all()
+ #assert (var(a,0) == array([ 1., 1.])).all()
+ #assert (var(a,1) == array([ 0.25, 0.25])).all()
def test_std(self):
from numpypy import array, std
a = array([[1, 2], [3, 4]])
assert std(a) == 1.1180339887498949
- # assert (std(a, axis=0) == array([ 1., 1.])).all()
- # assert (std(a, axis=1) == array([ 0.5, 0.5]).all()
+ #assert (std(a, axis=0) == array([ 1., 1.])).all()
+ #assert (std(a, axis=1) == array([ 0.5, 0.5])).all()
+
+ def test_mean(self):
+ from numpypy import array, mean, arange
+ assert mean(array(range(5))) == 2.0
+ assert mean(range(5)) == 2.0
+ assert (mean(arange(10).reshape(5, 2), axis=0) == [4, 5]).all()
+ assert (mean(arange(10).reshape(5, 2), axis=1) == [0.5, 2.5, 4.5, 6.5, 8.5]).all()
+
+ def test_reshape(self):
+ from numpypy import arange, array, dtype, reshape
+ a = arange(12)
+ b = reshape(a, (3, 4))
+ assert b.shape == (3, 4)
+ a = range(12)
+ b = reshape(a, (3, 4))
+ assert b.shape == (3, 4)
+ a = array(range(105)).reshape(3, 5, 7)
+ assert reshape(a, (1, -1)).shape == (1, 105)
+ assert reshape(a, (1, 1, -1)).shape == (1, 1, 105)
+ assert reshape(a, (-1, 1, 1)).shape == (105, 1, 1)
+
+ def test_transpose(self):
+ from numpypy import arange, array, transpose, ones
+ x = arange(4).reshape((2,2))
+ assert (transpose(x) == array([[0, 2],[1, 3]])).all()
+ # Once axes argument is implemented, add more tests
+ raises(NotImplementedError, "transpose(x, axes=(1, 0, 2))")
+ # x = ones((1, 2, 3))
+ # assert transpose(x, (1, 0, 2)).shape == (2, 1, 3)
+
diff --git a/pypy/module/test_lib_pypy/test_datetime.py b/pypy/module/test_lib_pypy/test_datetime.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/test_lib_pypy/test_datetime.py
@@ -0,0 +1,24 @@
+"""Additional tests for datetime."""
+
+import time
+import datetime
+import os
+
+def test_utcfromtimestamp():
+ """Confirm that utcfromtimestamp and fromtimestamp give consistent results.
+
+ Based on danchr's test script in https://bugs.pypy.org/issue986
+ """
+ try:
+ prev_tz = os.environ.get("TZ")
+ os.environ["TZ"] = "GMT"
+ for unused in xrange(100):
+ now = time.time()
+ delta = (datetime.datetime.utcfromtimestamp(now) -
+ datetime.datetime.fromtimestamp(now))
+ assert delta.days * 86400 + delta.seconds == 0
+ finally:
+ if prev_tz is None:
+ del os.environ["TZ"]
+ else:
+ os.environ["TZ"] = prev_tz
diff --git a/pypy/objspace/std/bytearrayobject.py b/pypy/objspace/std/bytearrayobject.py
--- a/pypy/objspace/std/bytearrayobject.py
+++ b/pypy/objspace/std/bytearrayobject.py
@@ -624,8 +624,8 @@
if step == 1:
assert start >= 0
- assert slicelength >= 0
- del items[start:start+slicelength]
+ if slicelength > 0:
+ del items[start:start+slicelength]
else:
n = len(items)
i = start
@@ -662,10 +662,11 @@
while i >= lim:
items[i] = items[i-delta]
i -= 1
- elif start >= 0:
+ elif delta == 0:
+ pass
+ else:
+ assert start >= 0 # start<0 is only possible with slicelength==0
del items[start:start+delta]
- else:
- assert delta==0 # start<0 is only possible with slicelength==0
elif len2 != slicelength: # No resize for extended slices
raise operationerrfmt(space.w_ValueError, "attempt to "
"assign sequence of size %d to extended slice of size %d",
diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py
--- a/pypy/objspace/std/complexobject.py
+++ b/pypy/objspace/std/complexobject.py
@@ -8,6 +8,7 @@
from pypy.rlib.rbigint import rbigint
from pypy.rlib.rfloat import (
formatd, DTSF_STR_PRECISION, isinf, isnan, copysign)
+from pypy.rlib import jit
import math
@@ -129,10 +130,10 @@
ir = len * math.sin(phase)
return W_ComplexObject(rr, ir)
- def pow_int(self, n):
- if n > 100 or n < -100:
- return self.pow(W_ComplexObject(1.0 * n, 0.0))
- elif n > 0:
+ def pow_small_int(self, n):
+ if n >= 0:
+ if jit.isconstant(n) and n == 2:
+ return self.mul(self)
return self.pow_positive_int(n)
else:
return w_one.div(self.pow_positive_int(-n))
@@ -217,10 +218,10 @@
def pow__Complex_Complex_ANY(space, w_complex, w_exponent, thirdArg):
if not space.is_w(thirdArg, space.w_None):
raise OperationError(space.w_ValueError, space.wrap('complex modulo'))
- int_exponent = int(w_exponent.realval)
try:
- if w_exponent.imagval == 0.0 and w_exponent.realval == int_exponent:
- w_p = w_complex.pow_int(int_exponent)
+ r = w_exponent.realval
+ if w_exponent.imagval == 0.0 and -100.0 <= r <= 100.0 and r == int(r):
+ w_p = w_complex.pow_small_int(int(r))
else:
w_p = w_complex.pow(w_exponent)
except ZeroDivisionError:
diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py
--- a/pypy/objspace/std/floatobject.py
+++ b/pypy/objspace/std/floatobject.py
@@ -451,6 +451,8 @@
y = w_float2.floatval
# Sort out special cases here instead of relying on pow()
+ if y == 2.0: # special case for performance:
+ return W_FloatObject(x * x) # x * x is always correct
if y == 0.0:
# x**0 is 1, even 0**0
return W_FloatObject(1.0)
diff --git a/pypy/objspace/std/listobject.py b/pypy/objspace/std/listobject.py
--- a/pypy/objspace/std/listobject.py
+++ b/pypy/objspace/std/listobject.py
@@ -804,10 +804,11 @@
while i >= lim:
items[i] = items[i-delta]
i -= 1
- elif start >= 0:
+ elif delta == 0:
+ pass
+ else:
+ assert start >= 0 # start<0 is only possible with slicelength==0
del items[start:start+delta]
- else:
- assert delta==0 # start<0 is only possible with slicelength==0
elif len2 != slicelength: # No resize for extended slices
raise operationerrfmt(self.space.w_ValueError, "attempt to "
"assign sequence of size %d to extended slice of size %d",
@@ -851,8 +852,8 @@
if step == 1:
assert start >= 0
- assert slicelength >= 0
- del items[start:start+slicelength]
+ if slicelength > 0:
+ del items[start:start+slicelength]
else:
n = len(items)
i = start
diff --git a/pypy/objspace/std/test/test_bytearrayobject.py b/pypy/objspace/std/test/test_bytearrayobject.py
--- a/pypy/objspace/std/test/test_bytearrayobject.py
+++ b/pypy/objspace/std/test/test_bytearrayobject.py
@@ -1,5 +1,9 @@
+from pypy import conftest
class AppTestBytesArray:
+ def setup_class(cls):
+ cls.w_runappdirect = cls.space.wrap(conftest.option.runappdirect)
+
def test_basics(self):
b = bytearray()
assert type(b) is bytearray
@@ -439,3 +443,15 @@
def test_reduce(self):
assert bytearray('caf\xe9').__reduce__() == (
bytearray, (u'caf\xe9', 'latin-1'), None)
+
+ def test_setitem_slice_performance(self):
+ # because of a complexity bug, this used to take forever on a
+ # translated pypy. On CPython2.6 -A, it takes around 8 seconds.
+ if self.runappdirect:
+ count = 16*1024*1024
+ else:
+ count = 1024
+ b = bytearray(count)
+ for i in range(count):
+ b[i:i+1] = 'y'
+ assert str(b) == 'y' * count
diff --git a/pypy/objspace/std/test/test_complexobject.py b/pypy/objspace/std/test/test_complexobject.py
--- a/pypy/objspace/std/test/test_complexobject.py
+++ b/pypy/objspace/std/test/test_complexobject.py
@@ -71,7 +71,7 @@
assert _powu((0.0,1.0),2) == (-1.0,0.0)
def _powi((r1, i1), n):
- w_res = W_ComplexObject(r1, i1).pow_int(n)
+ w_res = W_ComplexObject(r1, i1).pow_small_int(n)
return w_res.realval, w_res.imagval
assert _powi((0.0,2.0),0) == (1.0,0.0)
assert _powi((0.0,0.0),2) == (0.0,0.0)
@@ -213,6 +213,7 @@
assert a ** 105 == a ** 105
assert a ** -105 == a ** -105
assert a ** -30 == a ** -30
+ assert a ** 2 == a * a
assert 0.0j ** 0 == 1
diff --git a/pypy/objspace/std/test/test_listobject.py b/pypy/objspace/std/test/test_listobject.py
--- a/pypy/objspace/std/test/test_listobject.py
+++ b/pypy/objspace/std/test/test_listobject.py
@@ -397,6 +397,7 @@
on_cpython = (option.runappdirect and
not hasattr(sys, 'pypy_translation_info'))
cls.w_on_cpython = cls.space.wrap(on_cpython)
+ cls.w_runappdirect = cls.space.wrap(option.runappdirect)
def test_getstrategyfromlist_w(self):
l0 = ["a", "2", "a", True]
@@ -898,6 +899,18 @@
l[::-1] = l
assert l == [6,5,4,3,2,1]
+ def test_setitem_slice_performance(self):
+ # because of a complexity bug, this used to take forever on a
+ # translated pypy. On CPython2.6 -A, it takes around 5 seconds.
+ if self.runappdirect:
+ count = 16*1024*1024
+ else:
+ count = 1024
+ b = [None] * count
+ for i in range(count):
+ b[i:i+1] = ['y']
+ assert b == ['y'] * count
+
def test_recursive_repr(self):
l = []
assert repr(l) == '[]'
diff --git a/pypy/objspace/std/test/test_unicodeobject.py b/pypy/objspace/std/test/test_unicodeobject.py
--- a/pypy/objspace/std/test/test_unicodeobject.py
+++ b/pypy/objspace/std/test/test_unicodeobject.py
@@ -64,6 +64,12 @@
check(', '.join([u'a']), u'a')
check(', '.join(['a', u'b']), u'a, b')
check(u', '.join(['a', 'b']), u'a, b')
+ try:
+ u''.join([u'a', 2, 3])
+ except TypeError, e:
+ assert 'sequence item 1' in str(e)
+ else:
+ raise Exception("DID NOT RAISE")
if sys.version_info >= (2,3):
def test_contains_ex(self):
diff --git a/pypy/objspace/std/unicodeobject.py b/pypy/objspace/std/unicodeobject.py
--- a/pypy/objspace/std/unicodeobject.py
+++ b/pypy/objspace/std/unicodeobject.py
@@ -201,7 +201,7 @@
return space.newbool(container.find(item) != -1)
def unicode_join__Unicode_ANY(space, w_self, w_list):
- list_w = space.unpackiterable(w_list)
+ list_w = space.listview(w_list)
size = len(list_w)
if size == 0:
@@ -216,22 +216,21 @@
def _unicode_join_many_items(space, w_self, list_w, size):
self = w_self._value
- sb = UnicodeBuilder()
+ prealloc_size = len(self) * (size - 1)
+ for i in range(size):
+ try:
+ prealloc_size += len(space.unicode_w(list_w[i]))
+ except OperationError, e:
+ if not e.match(space, space.w_TypeError):
+ raise
+ raise operationerrfmt(space.w_TypeError,
+ "sequence item %d: expected string or Unicode", i)
+ sb = UnicodeBuilder(prealloc_size)
for i in range(size):
if self and i != 0:
sb.append(self)
w_s = list_w[i]
- if isinstance(w_s, W_UnicodeObject):
- # shortcut for performance
- sb.append(w_s._value)
- else:
- try:
- sb.append(space.unicode_w(w_s))
- except OperationError, e:
- if not e.match(space, space.w_TypeError):
- raise
- raise operationerrfmt(space.w_TypeError,
- "sequence item %d: expected string or Unicode", i)
+ sb.append(space.unicode_w(w_s))
return space.wrap(sb.build())
def hash__Unicode(space, w_uni):
diff --git a/pypy/rlib/jit_hooks.py b/pypy/rlib/jit_hooks.py
--- a/pypy/rlib/jit_hooks.py
+++ b/pypy/rlib/jit_hooks.py
@@ -52,7 +52,10 @@
from pypy.jit.metainterp.history import ResOperation
args = [_cast_to_box(llargs[i]) for i in range(len(llargs))]
- res = _cast_to_box(llres)
+ if llres:
+ res = _cast_to_box(llres)
+ else:
+ res = None
return _cast_to_gcref(ResOperation(no, args, res))
@register_helper(annmodel.SomePtr(llmemory.GCREF))
diff --git a/pypy/rlib/longlong2float.py b/pypy/rlib/longlong2float.py
--- a/pypy/rlib/longlong2float.py
+++ b/pypy/rlib/longlong2float.py
@@ -79,19 +79,23 @@
longlong2float = rffi.llexternal(
"pypy__longlong2float", [rffi.LONGLONG], rffi.DOUBLE,
_callable=longlong2float_emulator, compilation_info=eci,
- _nowrapper=True, elidable_function=True, sandboxsafe=True)
+ _nowrapper=True, elidable_function=True, sandboxsafe=True,
+ oo_primitive="pypy__longlong2float")
float2longlong = rffi.llexternal(
"pypy__float2longlong", [rffi.DOUBLE], rffi.LONGLONG,
_callable=float2longlong_emulator, compilation_info=eci,
- _nowrapper=True, elidable_function=True, sandboxsafe=True)
+ _nowrapper=True, elidable_function=True, sandboxsafe=True,
+ oo_primitive="pypy__float2longlong")
uint2singlefloat = rffi.llexternal(
"pypy__uint2singlefloat", [rffi.UINT], rffi.FLOAT,
_callable=uint2singlefloat_emulator, compilation_info=eci,
- _nowrapper=True, elidable_function=True, sandboxsafe=True)
+ _nowrapper=True, elidable_function=True, sandboxsafe=True,
+ oo_primitive="pypy__uint2singlefloat")
singlefloat2uint = rffi.llexternal(
"pypy__singlefloat2uint", [rffi.FLOAT], rffi.UINT,
_callable=singlefloat2uint_emulator, compilation_info=eci,
- _nowrapper=True, elidable_function=True, sandboxsafe=True)
+ _nowrapper=True, elidable_function=True, sandboxsafe=True,
+ oo_primitive="pypy__singlefloat2uint")
diff --git a/pypy/rlib/objectmodel.py b/pypy/rlib/objectmodel.py
--- a/pypy/rlib/objectmodel.py
+++ b/pypy/rlib/objectmodel.py
@@ -420,7 +420,7 @@
vobj.concretetype.TO._gckind == 'gc')
else:
from pypy.rpython.ootypesystem import ootype
- ok = isinstance(vobj.concretetype, ootype.Instance)
+ ok = isinstance(vobj.concretetype, (ootype.Instance, ootype.BuiltinType))
if not ok:
from pypy.rpython.error import TyperError
raise TyperError("compute_unique_id() cannot be applied to"
diff --git a/pypy/rpython/lltypesystem/rclass.py b/pypy/rpython/lltypesystem/rclass.py
--- a/pypy/rpython/lltypesystem/rclass.py
+++ b/pypy/rpython/lltypesystem/rclass.py
@@ -510,7 +510,13 @@
ctype = inputconst(Void, self.object_type)
cflags = inputconst(Void, flags)
vlist = [ctype, cflags]
- vptr = llops.genop('malloc', vlist,
+ cnonmovable = self.classdef.classdesc.read_attribute(
+ '_alloc_nonmovable_', Constant(False))
+ if cnonmovable.value:
+ opname = 'malloc_nonmovable'
+ else:
+ opname = 'malloc'
+ vptr = llops.genop(opname, vlist,
resulttype = Ptr(self.object_type))
ctypeptr = inputconst(CLASSTYPE, self.rclass.getvtable())
self.setfield(vptr, '__class__', ctypeptr, llops)
diff --git a/pypy/rpython/lltypesystem/rtuple.py b/pypy/rpython/lltypesystem/rtuple.py
--- a/pypy/rpython/lltypesystem/rtuple.py
+++ b/pypy/rpython/lltypesystem/rtuple.py
@@ -27,6 +27,10 @@
def newtuple(cls, llops, r_tuple, items_v):
# items_v should have the lowleveltype of the internal reprs
+ assert len(r_tuple.items_r) == len(items_v)
+ for r_item, v_item in zip(r_tuple.items_r, items_v):
+ assert r_item.lowleveltype == v_item.concretetype
+ #
if len(r_tuple.items_r) == 0:
return inputconst(Void, ()) # a Void empty tuple
c1 = inputconst(Void, r_tuple.lowleveltype.TO)
diff --git a/pypy/rpython/ootypesystem/ootype.py b/pypy/rpython/ootypesystem/ootype.py
--- a/pypy/rpython/ootypesystem/ootype.py
+++ b/pypy/rpython/ootypesystem/ootype.py
@@ -512,6 +512,7 @@
"ll_append_char": Meth([CHARTP], Void),
"ll_append": Meth([STRINGTP], Void),
"ll_build": Meth([], STRINGTP),
+ "ll_getlength": Meth([], Signed),
})
self._setup_methods({})
@@ -1376,6 +1377,9 @@
def _cast_to_object(self):
return make_object(self)
+ def _identityhash(self):
+ return object.__hash__(self)
+
class _string(_builtin_type):
def __init__(self, STRING, value = ''):
@@ -1543,6 +1547,9 @@
else:
return make_unicode(u''.join(self._buf))
+ def ll_getlength(self):
+ return self.ll_build().ll_strlen()
+
class _null_string_builder(_null_mixin(_string_builder), _string_builder):
def __init__(self, STRING_BUILDER):
self.__dict__["_TYPE"] = STRING_BUILDER
diff --git a/pypy/rpython/ootypesystem/rbuilder.py b/pypy/rpython/ootypesystem/rbuilder.py
--- a/pypy/rpython/ootypesystem/rbuilder.py
+++ b/pypy/rpython/ootypesystem/rbuilder.py
@@ -21,6 +21,10 @@
builder.ll_append_char(char)
@staticmethod
+ def ll_getlength(builder):
+ return builder.ll_getlength()
+
+ @staticmethod
def ll_append(builder, string):
builder.ll_append(string)
diff --git a/pypy/rpython/rrange.py b/pypy/rpython/rrange.py
--- a/pypy/rpython/rrange.py
+++ b/pypy/rpython/rrange.py
@@ -204,7 +204,10 @@
v_index = hop.gendirectcall(self.ll_getnextindex, v_enumerate)
hop2 = hop.copy()
hop2.args_r = [self.r_baseiter]
+ r_item_src = self.r_baseiter.r_list.external_item_repr
+ r_item_dst = hop.r_result.items_r[1]
v_item = self.r_baseiter.rtype_next(hop2)
+ v_item = hop.llops.convertvar(v_item, r_item_src, r_item_dst)
return hop.r_result.newtuple(hop.llops, hop.r_result,
[v_index, v_item])
diff --git a/pypy/rpython/test/test_rbuilder.py b/pypy/rpython/test/test_rbuilder.py
--- a/pypy/rpython/test/test_rbuilder.py
+++ b/pypy/rpython/test/test_rbuilder.py
@@ -124,9 +124,5 @@
pass
class TestOOtype(BaseTestStringBuilder, OORtypeMixin):
- def test_string_getlength(self):
- py.test.skip("getlength(): not implemented on ootype")
- def test_unicode_getlength(self):
- py.test.skip("getlength(): not implemented on ootype")
def test_append_charpsize(self):
py.test.skip("append_charpsize(): not implemented on ootype")
diff --git a/pypy/rpython/test/test_rbuiltin.py b/pypy/rpython/test/test_rbuiltin.py
--- a/pypy/rpython/test/test_rbuiltin.py
+++ b/pypy/rpython/test/test_rbuiltin.py
@@ -463,6 +463,31 @@
assert x1 == intmask(x0)
assert x3 == intmask(x2)
+ def test_id_on_builtins(self):
+ from pypy.rlib.objectmodel import compute_unique_id
+ from pypy.rlib.rstring import StringBuilder, UnicodeBuilder
+ def fn():
+ return (compute_unique_id("foo"),
+ compute_unique_id(u"bar"),
+ compute_unique_id([1]),
+ compute_unique_id({"foo": 3}),
+ compute_unique_id(StringBuilder()),
+ compute_unique_id(UnicodeBuilder()))
+ res = self.interpret(fn, [])
+ for id in self.ll_unpack_tuple(res, 6):
+ assert isinstance(id, (int, r_longlong))
+
+ def test_uniqueness_of_id_on_strings(self):
+ from pypy.rlib.objectmodel import compute_unique_id
+ def fn(s1, s2):
+ return (compute_unique_id(s1), compute_unique_id(s2))
+
+ s1 = "foo"
+ s2 = ''.join(['f','oo'])
+ res = self.interpret(fn, [self.string_to_ll(s1), self.string_to_ll(s2)])
+ i1, i2 = self.ll_unpack_tuple(res, 2)
+ assert i1 != i2
+
def test_cast_primitive(self):
from pypy.rpython.annlowlevel import LowLevelAnnotatorPolicy
def llf(u):
diff --git a/pypy/rpython/test/test_rclass.py b/pypy/rpython/test/test_rclass.py
--- a/pypy/rpython/test/test_rclass.py
+++ b/pypy/rpython/test/test_rclass.py
@@ -1130,6 +1130,18 @@
assert sorted([u]) == [6] # 32-bit types
assert sorted([i, r, d, l]) == [2, 3, 4, 5] # 64-bit types
+ def test_nonmovable(self):
+ for (nonmovable, opname) in [(True, 'malloc_nonmovable'),
+ (False, 'malloc')]:
+ class A(object):
+ _alloc_nonmovable_ = nonmovable
+ def f():
+ return A()
+ t, typer, graph = self.gengraph(f, [])
+ assert summary(graph) == {opname: 1,
+ 'cast_pointer': 1,
+ 'setfield': 1}
+
class TestOOtype(BaseTestRclass, OORtypeMixin):
diff --git a/pypy/rpython/test/test_rrange.py b/pypy/rpython/test/test_rrange.py
--- a/pypy/rpython/test/test_rrange.py
+++ b/pypy/rpython/test/test_rrange.py
@@ -169,6 +169,22 @@
res = self.interpret(fn, [2])
assert res == 789
+ def test_enumerate_instances(self):
+ class A:
+ pass
+ def fn(n):
+ a = A()
+ b = A()
+ a.k = 10
+ b.k = 20
+ for i, x in enumerate([a, b]):
+ if i == n:
+ return x.k
+ return 5
+ res = self.interpret(fn, [1])
+ assert res == 20
+
+
class TestLLtype(BaseTestRrange, LLRtypeMixin):
from pypy.rpython.lltypesystem import rrange
diff --git a/pypy/tool/jitlogparser/parser.py b/pypy/tool/jitlogparser/parser.py
--- a/pypy/tool/jitlogparser/parser.py
+++ b/pypy/tool/jitlogparser/parser.py
@@ -140,13 +140,15 @@
bytecode_name = None
is_bytecode = True
inline_level = None
+ has_dmp = False
def parse_code_data(self, arg):
m = re.search('<code object ([<>\w]+)[\.,] file \'(.+?)\'[\.,] line (\d+)> #(\d+) (\w+)',
arg)
if m is None:
# a non-code loop, like StrLiteralSearch or something
- self.bytecode_name = arg
+ if arg:
+ self.bytecode_name = arg
else:
self.name, self.filename, lineno, bytecode_no, self.bytecode_name = m.groups()
self.startlineno = int(lineno)
@@ -218,7 +220,7 @@
self.inputargs = inputargs
self.chunks = chunks
for chunk in self.chunks:
- if chunk.filename is not None:
+ if chunk.bytecode_name is not None:
self.startlineno = chunk.startlineno
self.filename = chunk.filename
self.name = chunk.name
diff --git a/pypy/tool/jitlogparser/test/test_parser.py b/pypy/tool/jitlogparser/test/test_parser.py
--- a/pypy/tool/jitlogparser/test/test_parser.py
+++ b/pypy/tool/jitlogparser/test/test_parser.py
@@ -283,3 +283,13 @@
assert loops[-1].count == 1234
assert loops[1].count == 123
assert loops[2].count == 12
+
+def test_parse_nonpython():
+ loop = parse("""
+ []
+ debug_merge_point(0, 'random')
+ debug_merge_point(0, '<code object f. file 'x.py'. line 2> #15 COMPARE_OP')
+ """)
+ f = Function.from_operations(loop.operations, LoopStorage())
+ assert f.chunks[-1].filename == 'x.py'
+ assert f.filename is None
diff --git a/pypy/tool/test/test_version.py b/pypy/tool/test/test_version.py
--- a/pypy/tool/test/test_version.py
+++ b/pypy/tool/test/test_version.py
@@ -1,6 +1,22 @@
import os, sys
import py
-from pypy.tool.version import get_repo_version_info
+from pypy.tool.version import get_repo_version_info, _get_hg_archive_version
+
+def test_hg_archival_version(tmpdir):
+ def version_for(name, **kw):
+ path = tmpdir.join(name)
+ path.write('\n'.join('%s: %s' % x for x in kw.items()))
+ return _get_hg_archive_version(str(path))
+
+ assert version_for('release',
+ tag='release-123',
+ node='000',
+ ) == ('PyPy', 'release-123', '000')
+ assert version_for('somebranch',
+ node='000',
+ branch='something',
+ ) == ('PyPy', 'something', '000')
+
def test_get_repo_version_info():
assert get_repo_version_info(None)
diff --git a/pypy/tool/version.py b/pypy/tool/version.py
--- a/pypy/tool/version.py
+++ b/pypy/tool/version.py
@@ -3,111 +3,139 @@
from subprocess import Popen, PIPE
import pypy
pypydir = os.path.dirname(os.path.abspath(pypy.__file__))
+pypyroot = os.path.dirname(pypydir)
+default_retval = 'PyPy', '?', '?'
+
+def maywarn(err, repo_type='Mercurial'):
+ if not err:
+ return
+
+ from pypy.tool.ansi_print import ansi_log
+ log = py.log.Producer("version")
+ py.log.setconsumer("version", ansi_log)
+ log.WARNING('Errors getting %s information: %s' % (repo_type, err))
def get_repo_version_info(hgexe=None):
'''Obtain version information by invoking the 'hg' or 'git' commands.'''
- # TODO: support extracting from .hg_archival.txt
-
- default_retval = 'PyPy', '?', '?'
- pypyroot = os.path.abspath(os.path.join(pypydir, '..'))
-
- def maywarn(err, repo_type='Mercurial'):
- if not err:
- return
-
- from pypy.tool.ansi_print import ansi_log
- log = py.log.Producer("version")
- py.log.setconsumer("version", ansi_log)
- log.WARNING('Errors getting %s information: %s' % (repo_type, err))
# Try to see if we can get info from Git if hgexe is not specified.
if not hgexe:
if os.path.isdir(os.path.join(pypyroot, '.git')):
- gitexe = py.path.local.sysfind('git')
- if gitexe:
- try:
- p = Popen(
- [str(gitexe), 'rev-parse', 'HEAD'],
- stdout=PIPE, stderr=PIPE, cwd=pypyroot
- )
- except OSError, e:
- maywarn(e, 'Git')
- return default_retval
- if p.wait() != 0:
- maywarn(p.stderr.read(), 'Git')
- return default_retval
- revision_id = p.stdout.read().strip()[:12]
- p = Popen(
- [str(gitexe), 'describe', '--tags', '--exact-match'],
- stdout=PIPE, stderr=PIPE, cwd=pypyroot
- )
- if p.wait() != 0:
- p = Popen(
- [str(gitexe), 'branch'], stdout=PIPE, stderr=PIPE,
- cwd=pypyroot
- )
- if p.wait() != 0:
- maywarn(p.stderr.read(), 'Git')
- return 'PyPy', '?', revision_id
- branch = '?'
- for line in p.stdout.read().strip().split('\n'):
- if line.startswith('* '):
- branch = line[1:].strip()
- if branch == '(no branch)':
- branch = '?'
- break
- return 'PyPy', branch, revision_id
- return 'PyPy', p.stdout.read().strip(), revision_id
+ return _get_git_version()
# Fallback to trying Mercurial.
if hgexe is None:
hgexe = py.path.local.sysfind('hg')
- if not os.path.isdir(os.path.join(pypyroot, '.hg')):
+ if os.path.isfile(os.path.join(pypyroot, '.hg_archival.txt')):
+ return _get_hg_archive_version(os.path.join(pypyroot, '.hg_archival.txt'))
+ elif not os.path.isdir(os.path.join(pypyroot, '.hg')):
maywarn('Not running from a Mercurial repository!')
return default_retval
elif not hgexe:
maywarn('Cannot find Mercurial command!')
return default_retval
else:
- env = dict(os.environ)
- # get Mercurial into scripting mode
- env['HGPLAIN'] = '1'
- # disable user configuration, extensions, etc.
- env['HGRCPATH'] = os.devnull
+ return _get_hg_version(hgexe)
- try:
- p = Popen([str(hgexe), 'version', '-q'],
- stdout=PIPE, stderr=PIPE, env=env)
- except OSError, e:
- maywarn(e)
- return default_retval
- if not p.stdout.read().startswith('Mercurial Distributed SCM'):
- maywarn('command does not identify itself as Mercurial')
- return default_retval
+def _get_hg_version(hgexe):
+ env = dict(os.environ)
+ # get Mercurial into scripting mode
+ env['HGPLAIN'] = '1'
+ # disable user configuration, extensions, etc.
+ env['HGRCPATH'] = os.devnull
- p = Popen([str(hgexe), 'id', '-i', pypyroot],
+ try:
+ p = Popen([str(hgexe), 'version', '-q'],
stdout=PIPE, stderr=PIPE, env=env)
- hgid = p.stdout.read().strip()
+ except OSError, e:
+ maywarn(e)
+ return default_retval
+
+ if not p.stdout.read().startswith('Mercurial Distributed SCM'):
+ maywarn('command does not identify itself as Mercurial')
+ return default_retval
+
+ p = Popen([str(hgexe), 'id', '-i', pypyroot],
+ stdout=PIPE, stderr=PIPE, env=env)
+ hgid = p.stdout.read().strip()
+ maywarn(p.stderr.read())
+ if p.wait() != 0:
+ hgid = '?'
+
+ p = Popen([str(hgexe), 'id', '-t', pypyroot],
+ stdout=PIPE, stderr=PIPE, env=env)
+ hgtags = [t for t in p.stdout.read().strip().split() if t != 'tip']
+ maywarn(p.stderr.read())
+ if p.wait() != 0:
+ hgtags = ['?']
+
+ if hgtags:
+ return 'PyPy', hgtags[0], hgid
+ else:
+ # use the branch instead
+ p = Popen([str(hgexe), 'id', '-b', pypyroot],
+ stdout=PIPE, stderr=PIPE, env=env)
+ hgbranch = p.stdout.read().strip()
maywarn(p.stderr.read())
+
+ return 'PyPy', hgbranch, hgid
+
+
+def _get_hg_archive_version(path):
+ fp = open(path)
+ try:
+ data = dict(x.split(': ', 1) for x in fp.read().splitlines())
+ finally:
+ fp.close()
+ if 'tag' in data:
+ return 'PyPy', data['tag'], data['node']
+ else:
+ return 'PyPy', data['branch'], data['node']
+
+
+def _get_git_version():
+ #XXX: this function is a untested hack,
+ # so the git mirror tav made will work
+ gitexe = py.path.local.sysfind('git')
+ if not gitexe:
+ return default_retval
+
+ try:
+ p = Popen(
+ [str(gitexe), 'rev-parse', 'HEAD'],
+ stdout=PIPE, stderr=PIPE, cwd=pypyroot
+ )
+ except OSError, e:
+ maywarn(e, 'Git')
+ return default_retval
+ if p.wait() != 0:
+ maywarn(p.stderr.read(), 'Git')
+ return default_retval
+ revision_id = p.stdout.read().strip()[:12]
+ p = Popen(
+ [str(gitexe), 'describe', '--tags', '--exact-match'],
+ stdout=PIPE, stderr=PIPE, cwd=pypyroot
+ )
+ if p.wait() != 0:
+ p = Popen(
+ [str(gitexe), 'branch'], stdout=PIPE, stderr=PIPE,
+ cwd=pypyroot
+ )
if p.wait() != 0:
- hgid = '?'
+ maywarn(p.stderr.read(), 'Git')
+ return 'PyPy', '?', revision_id
+ branch = '?'
+ for line in p.stdout.read().strip().split('\n'):
+ if line.startswith('* '):
+ branch = line[1:].strip()
+ if branch == '(no branch)':
+ branch = '?'
+ break
+ return 'PyPy', branch, revision_id
+ return 'PyPy', p.stdout.read().strip(), revision_id
- p = Popen([str(hgexe), 'id', '-t', pypyroot],
- stdout=PIPE, stderr=PIPE, env=env)
- hgtags = [t for t in p.stdout.read().strip().split() if t != 'tip']
- maywarn(p.stderr.read())
- if p.wait() != 0:
- hgtags = ['?']
- if hgtags:
- return 'PyPy', hgtags[0], hgid
- else:
- # use the branch instead
- p = Popen([str(hgexe), 'id', '-b', pypyroot],
- stdout=PIPE, stderr=PIPE, env=env)
- hgbranch = p.stdout.read().strip()
- maywarn(p.stderr.read())
-
- return 'PyPy', hgbranch, hgid
+if __name__ == '__main__':
+ print get_repo_version_info()
diff --git a/pypy/translator/c/src/profiling.c b/pypy/translator/c/src/profiling.c
--- a/pypy/translator/c/src/profiling.c
+++ b/pypy/translator/c/src/profiling.c
@@ -29,33 +29,33 @@
profiling_setup = 0;
}
}
-
-#elif defined(_WIN32)
-#include <windows.h>
-
-DWORD_PTR base_affinity_mask;
-int profiling_setup = 0;
-
-void pypy_setup_profiling() {
- if (!profiling_setup) {
- DWORD_PTR affinity_mask, system_affinity_mask;
- GetProcessAffinityMask(GetCurrentProcess(),
- &base_affinity_mask, &system_affinity_mask);
- affinity_mask = 1;
- /* Pick one cpu allowed by the system */
- if (system_affinity_mask)
- while ((affinity_mask & system_affinity_mask) == 0)
- affinity_mask <<= 1;
- SetProcessAffinityMask(GetCurrentProcess(), affinity_mask);
- profiling_setup = 1;
- }
-}
-
-void pypy_teardown_profiling() {
- if (profiling_setup) {
- SetProcessAffinityMask(GetCurrentProcess(), base_affinity_mask);
- profiling_setup = 0;
- }
+
+#elif defined(_WIN32)
+#include <windows.h>
+
+DWORD_PTR base_affinity_mask;
+int profiling_setup = 0;
+
+void pypy_setup_profiling() {
+ if (!profiling_setup) {
+ DWORD_PTR affinity_mask, system_affinity_mask;
+ GetProcessAffinityMask(GetCurrentProcess(),
+ &base_affinity_mask, &system_affinity_mask);
+ affinity_mask = 1;
+ /* Pick one cpu allowed by the system */
+ if (system_affinity_mask)
+ while ((affinity_mask & system_affinity_mask) == 0)
+ affinity_mask <<= 1;
+ SetProcessAffinityMask(GetCurrentProcess(), affinity_mask);
+ profiling_setup = 1;
+ }
+}
+
+void pypy_teardown_profiling() {
+ if (profiling_setup) {
+ SetProcessAffinityMask(GetCurrentProcess(), base_affinity_mask);
+ profiling_setup = 0;
+ }
}
#else
diff --git a/pypy/translator/goal/translate.py b/pypy/translator/goal/translate.py
--- a/pypy/translator/goal/translate.py
+++ b/pypy/translator/goal/translate.py
@@ -293,17 +293,18 @@
drv.exe_name = targetspec_dic['__name__'] + '-%(backend)s'
# Double check to ensure we are not overwriting the current interpreter
- try:
- this_exe = py.path.local(sys.executable).new(ext='')
- exe_name = drv.compute_exe_name()
- samefile = this_exe.samefile(exe_name)
- assert not samefile, (
- 'Output file %s is the currently running '
- 'interpreter (use --output=...)'% exe_name)
- except EnvironmentError:
- pass
+ goals = translateconfig.goals
+ if not goals or 'compile' in goals:
+ try:
+ this_exe = py.path.local(sys.executable).new(ext='')
+ exe_name = drv.compute_exe_name()
+ samefile = this_exe.samefile(exe_name)
+ assert not samefile, (
+ 'Output file %s is the currently running '
+ 'interpreter (use --output=...)'% exe_name)
+ except EnvironmentError:
+ pass
- goals = translateconfig.goals
try:
drv.proceed(goals)
finally:
diff --git a/pypy/translator/jvm/builtin.py b/pypy/translator/jvm/builtin.py
--- a/pypy/translator/jvm/builtin.py
+++ b/pypy/translator/jvm/builtin.py
@@ -84,6 +84,9 @@
(ootype.StringBuilder.__class__, "ll_build"):
jvm.Method.v(jStringBuilder, "toString", (), jString),
+ (ootype.StringBuilder.__class__, "ll_getlength"):
+ jvm.Method.v(jStringBuilder, "length", (), jInt),
+
(ootype.String.__class__, "ll_hash"):
jvm.Method.v(jString, "hashCode", (), jInt),
diff --git a/pypy/translator/jvm/database.py b/pypy/translator/jvm/database.py
--- a/pypy/translator/jvm/database.py
+++ b/pypy/translator/jvm/database.py
@@ -358,7 +358,7 @@
ootype.Unsigned:jvm.PYPYSERIALIZEUINT,
ootype.SignedLongLong:jvm.LONGTOSTRINGL,
ootype.UnsignedLongLong: jvm.PYPYSERIALIZEULONG,
- ootype.Float:jvm.DOUBLETOSTRINGD,
+ ootype.Float:jvm.PYPYSERIALIZEDOUBLE,
ootype.Bool:jvm.PYPYSERIALIZEBOOLEAN,
ootype.Void:jvm.PYPYSERIALIZEVOID,
ootype.Char:jvm.PYPYESCAPEDCHAR,
diff --git a/pypy/translator/jvm/metavm.py b/pypy/translator/jvm/metavm.py
--- a/pypy/translator/jvm/metavm.py
+++ b/pypy/translator/jvm/metavm.py
@@ -92,6 +92,7 @@
CASTS = {
# FROM TO
(ootype.Signed, ootype.UnsignedLongLong): jvm.I2L,
+ (ootype.Unsigned, ootype.UnsignedLongLong): jvm.I2L,
(ootype.SignedLongLong, ootype.Signed): jvm.L2I,
(ootype.UnsignedLongLong, ootype.Unsigned): jvm.L2I,
(ootype.UnsignedLongLong, ootype.Signed): jvm.L2I,
diff --git a/pypy/translator/jvm/opcodes.py b/pypy/translator/jvm/opcodes.py
--- a/pypy/translator/jvm/opcodes.py
+++ b/pypy/translator/jvm/opcodes.py
@@ -101,6 +101,7 @@
'jit_force_virtualizable': Ignore,
'jit_force_virtual': DoNothing,
'jit_force_quasi_immutable': Ignore,
+ 'jit_is_virtual': PushPrimitive(ootype.Bool, False),
'debug_assert': [], # TODO: implement?
'debug_start_traceback': Ignore,
diff --git a/pypy/translator/jvm/src/pypy/PyPy.java b/pypy/translator/jvm/src/pypy/PyPy.java
--- a/pypy/translator/jvm/src/pypy/PyPy.java
+++ b/pypy/translator/jvm/src/pypy/PyPy.java
@@ -283,6 +283,14 @@
}
}
+ public double pypy__longlong2float(long l) {
+ return Double.longBitsToDouble(l);
+ }
+
+ public long pypy__float2longlong(double d) {
+ return Double.doubleToRawLongBits(d);
+ }
+
public double ooparse_float(String s) {
try {
return Double.parseDouble(s);
@@ -353,6 +361,19 @@
return "False";
}
+ public static String serialize_double(double d) {
+ if (Double.isNaN(d)) {
+ return "float(\"nan\")";
+ } else if (Double.isInfinite(d)) {
+ if (d > 0)
+ return "float(\"inf\")";
+ else
+ return "float(\"-inf\")";
+ } else {
+ return Double.toString(d);
+ }
+ }
+
private static String format_char(char c) {
String res = "\\x";
if (c <= 0x0F) res = res + "0";
diff --git a/pypy/translator/jvm/test/runtest.py b/pypy/translator/jvm/test/runtest.py
--- a/pypy/translator/jvm/test/runtest.py
+++ b/pypy/translator/jvm/test/runtest.py
@@ -56,6 +56,7 @@
# CLI could-be duplicate
class JvmGeneratedSourceWrapper(object):
+
def __init__(self, gensrc):
""" gensrc is an instance of JvmGeneratedSource """
self.gensrc = gensrc
diff --git a/pypy/translator/jvm/test/test_builder.py b/pypy/translator/jvm/test/test_builder.py
new file mode 100644
--- /dev/null
+++ b/pypy/translator/jvm/test/test_builder.py
@@ -0,0 +1,7 @@
+from pypy.translator.jvm.test.runtest import JvmTest
+from pypy.rpython.test.test_rbuilder import BaseTestStringBuilder
+import py
+
+class TestJvmStringBuilder(JvmTest, BaseTestStringBuilder):
+ def test_append_charpsize(self):
+ py.test.skip("append_charpsize(): not implemented on ootype")
diff --git a/pypy/translator/jvm/test/test_longlong2float.py b/pypy/translator/jvm/test/test_longlong2float.py
new file mode 100644
--- /dev/null
+++ b/pypy/translator/jvm/test/test_longlong2float.py
@@ -0,0 +1,20 @@
+from pypy.translator.jvm.test.runtest import JvmTest
+from pypy.rlib.longlong2float import *
+from pypy.rlib.test.test_longlong2float import enum_floats
+from pypy.rlib.test.test_longlong2float import fn as float2longlong2float
+import py
+
+class TestLongLong2Float(JvmTest):
+
+ def test_float2longlong_and_longlong2float(self):
+ def func(f):
+ return float2longlong2float(f)
+
+ for f in enum_floats():
+ assert repr(f) == repr(self.interpret(func, [f]))
+
+ def test_uint2singlefloat(self):
+ py.test.skip("uint2singlefloat is not implemented in ootype")
+
+ def test_singlefloat2uint(self):
+ py.test.skip("singlefloat2uint is not implemented in ootype")
diff --git a/pypy/translator/jvm/typesystem.py b/pypy/translator/jvm/typesystem.py
--- a/pypy/translator/jvm/typesystem.py
+++ b/pypy/translator/jvm/typesystem.py
@@ -955,6 +955,7 @@
PYPYSERIALIZEUINT = Method.s(jPyPy, 'serialize_uint', (jInt,), jString)
PYPYSERIALIZEULONG = Method.s(jPyPy, 'serialize_ulonglong', (jLong,),jString)
PYPYSERIALIZEVOID = Method.s(jPyPy, 'serialize_void', (), jString)
+PYPYSERIALIZEDOUBLE = Method.s(jPyPy, 'serialize_double', (jDouble,), jString)
PYPYESCAPEDCHAR = Method.s(jPyPy, 'escaped_char', (jChar,), jString)
PYPYESCAPEDUNICHAR = Method.s(jPyPy, 'escaped_unichar', (jChar,), jString)
PYPYESCAPEDSTRING = Method.s(jPyPy, 'escaped_string', (jString,), jString)
diff --git a/pypy/translator/oosupport/test_template/cast.py b/pypy/translator/oosupport/test_template/cast.py
--- a/pypy/translator/oosupport/test_template/cast.py
+++ b/pypy/translator/oosupport/test_template/cast.py
@@ -13,6 +13,9 @@
def to_longlong(x):
return r_longlong(x)
+def to_ulonglong(x):
+ return r_ulonglong(x)
+
def uint_to_int(x):
return intmask(x)
@@ -56,6 +59,9 @@
def test_unsignedlonglong_to_unsigned4(self):
self.check(to_uint, [r_ulonglong(18446744073709551615l)]) # max 64 bit num
+ def test_unsigned_to_usignedlonglong(self):
+ self.check(to_ulonglong, [r_uint(42)])
+
def test_uint_to_int(self):
self.check(uint_to_int, [r_uint(sys.maxint+1)])
More information about the pypy-commit
mailing list