[pypy-commit] pypy jitframe-on-heap: merge default
fijal
noreply at buildbot.pypy.org
Thu Feb 21 11:03:55 CET 2013
Author: Maciej Fijalkowski <fijall at gmail.com>
Branch: jitframe-on-heap
Changeset: r61532:e7aebccb738e
Date: 2013-02-21 12:02 +0200
http://bitbucket.org/pypy/pypy/changeset/e7aebccb738e/
Log: merge default
diff too long, truncating to 2000 out of 2427 lines
diff --git a/lib_pypy/datetime.py b/lib_pypy/datetime.py
--- a/lib_pypy/datetime.py
+++ b/lib_pypy/datetime.py
@@ -271,6 +271,8 @@
raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
def _check_int_field(value):
+ if isinstance(value, int):
+ return value
if not isinstance(value, float):
try:
value = value.__int__()
@@ -279,7 +281,7 @@
else:
if isinstance(value, (int, long)):
return value
- raise TypeError('integer argument expected')
+ raise TypeError('an integer is required')
def _check_date_fields(year, month, day):
year = _check_int_field(year)
@@ -457,6 +459,8 @@
felt like it.
"""
+ __slots__ = '_days', '_seconds', '_microseconds'
+
def __new__(cls, days=0, seconds=0, microseconds=0,
# XXX The following should only be used as keyword args:
milliseconds=0, minutes=0, hours=0, weeks=0):
@@ -770,6 +774,8 @@
year, month, day
"""
+ __slots__ = '_year', '_month', '_day'
+
def __new__(cls, year, month=None, day=None):
"""Constructor.
@@ -777,7 +783,7 @@
year, month, day (required, base 1)
"""
- if isinstance(year, str):
+ if isinstance(year, str) and len(year) == 4:
# Pickle support
self = object.__new__(cls)
self.__setstate(year)
@@ -1063,6 +1069,8 @@
Subclasses must override the name(), utcoffset() and dst() methods.
"""
+ __slots__ = ()
+
def tzname(self, dt):
"datetime -> string name of time zone."
raise NotImplementedError("tzinfo subclass must override tzname()")
@@ -1155,6 +1163,8 @@
hour, minute, second, microsecond, tzinfo
"""
+ __slots__ = '_hour', '_minute', '_second', '_microsecond', '_tzinfo'
+
def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
"""Constructor.
@@ -1457,9 +1467,11 @@
instance of a tzinfo subclass. The remaining arguments may be ints or longs.
"""
+ __slots__ = date.__slots__ + time.__slots__
+
def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
microsecond=0, tzinfo=None):
- if isinstance(year, str):
+ if isinstance(year, str) and len(year) == 10:
# Pickle support
self = date.__new__(cls, year[:4])
self.__setstate(year, month)
diff --git a/pypy/doc/coding-guide.rst b/pypy/doc/coding-guide.rst
--- a/pypy/doc/coding-guide.rst
+++ b/pypy/doc/coding-guide.rst
@@ -303,7 +303,7 @@
dicts with a unique key type only, provided it is hashable. Custom
hash functions and custom equality will not be honored.
- Use ``pypy.rlib.objectmodel.r_dict`` for custom hash functions.
+ Use ``rpython.rlib.objectmodel.r_dict`` for custom hash functions.
**list comprehensions**
@@ -365,7 +365,7 @@
We use normal integers for signed arithmetic. It means that before
translation we get longs in case of overflow, and after translation we get a
silent wrap-around. Whenever we need more control, we use the following
-helpers (which live the `pypy/rlib/rarithmetic.py`_):
+helpers (which live in `rpython/rlib/rarithmetic.py`_):
**ovfcheck()**
diff --git a/pypy/doc/getting-started-dev.rst b/pypy/doc/getting-started-dev.rst
--- a/pypy/doc/getting-started-dev.rst
+++ b/pypy/doc/getting-started-dev.rst
@@ -58,8 +58,7 @@
only use low level types that are available in C (e.g. int). The compiled
version is now in a ``.so`` library. You can run it say using ctypes:
- >>> from ctypes import CDLL
- >>> f = CDLL(lib)
+ >>> f = get_c_function(lib, snippet.is_perfect_number)
>>> f(5)
0
>>> f(6)
diff --git a/pypy/doc/rlib.rst b/pypy/doc/rlib.rst
--- a/pypy/doc/rlib.rst
+++ b/pypy/doc/rlib.rst
@@ -7,18 +7,18 @@
.. contents::
-This page lists some of the modules in `pypy/rlib`_ together with some hints
+This page lists some of the modules in `rpython/rlib`_ together with some hints
for what they can be used for. The modules here will make up some general
library useful for RPython programs (since most of the standard library modules
are not RPython). Most of these modules are somewhat rough still and are likely
to change at some point. Usually it is useful to look at the tests in
-`pypy/rlib/test`_ to get an impression of how to use a module.
+`rpython/rlib/test`_ to get an impression of how to use a module.
``listsort``
============
-The `pypy/rlib/listsort.py`_ module contains an implementation of the timsort sorting algorithm
+The `rpython/rlib/listsort.py`_ module contains an implementation of the timsort sorting algorithm
(the sort method of lists is not RPython). To use it, subclass from the
``listsort.TimSort`` class and override the ``lt`` method to change the
comparison behaviour. The constructor of ``TimSort`` takes a list as an
@@ -30,7 +30,7 @@
``nonconst``
============
-The `pypy/rlib/nonconst.py`_ module is useful mostly for tests. The `flow object space`_ and
+The `rpython/rlib/nonconst.py`_ module is useful mostly for tests. The `flow object space`_ and
the `annotator`_ do quite some constant folding, which is sometimes not desired
in a test. To prevent constant folding on a certain value, use the ``NonConst``
class. The constructor of ``NonConst`` takes an arbitrary value. The instance of
@@ -44,7 +44,7 @@
``objectmodel``
===============
-The `pypy/rlib/objectmodel.py`_ module is a mixed bag of various functionality. Some of the
+The `rpython/rlib/objectmodel.py`_ module is a mixed bag of various functionality. Some of the
more useful ones are:
``ComputedIntSymbolic``:
@@ -94,7 +94,7 @@
``rarithmetic``
===============
-The `pypy/rlib/rarithmetic.py`_ module contains functionality to handle the small differences
+The `rpython/rlib/rarithmetic.py`_ module contains functionality to handle the small differences
in the behaviour of arithmetic code in regular Python and RPython code. Most of
them are already described in the `coding guide`_
@@ -104,7 +104,7 @@
``rbigint``
===========
-The `pypy/rlib/rbigint.py`_ module contains a full RPython implementation of the Python ``long``
+The `rpython/rlib/rbigint.py`_ module contains a full RPython implementation of the Python ``long``
type (which itself is not supported in RPython). The ``rbigint`` class contains
that implementation. To construct ``rbigint`` instances use the static methods
``fromint``, ``frombool``, ``fromfloat`` and ``fromdecimalstr``. To convert back
@@ -118,7 +118,7 @@
``rrandom``
===========
-The `pypy/rlib/rrandom.py`_ module contains an implementation of the mersenne twister random
+The `rpython/rlib/rrandom.py`_ module contains an implementation of the mersenne twister random
number generator. It contains one class ``Random`` which most importantly has a
``random`` method which returns a pseudo-random floating point number between
0.0 and 1.0.
@@ -126,7 +126,7 @@
``rsocket``
===========
-The `pypy/rlib/rsocket.py`_ module contains an RPython implementation of the functionality of
+The `rpython/rlib/rsocket.py`_ module contains an RPython implementation of the functionality of
the socket standard library with a slightly different interface. The
difficulty with the Python socket API is that addresses are not "well-typed"
objects: depending on the address family they are tuples, or strings, and
@@ -137,7 +137,7 @@
``streamio``
============
-The `pypy/rlib/streamio.py`_ contains an RPython stream I/O implementation (which was started
+The `rpython/rlib/streamio.py`_ contains an RPython stream I/O implementation (which was started
by Guido van Rossum as `sio.py`_ in the CPython sandbox as a prototype for the
upcoming new file implementation in Python 3000).
@@ -146,7 +146,7 @@
``unroll``
==========
-The `pypy/rlib/unroll.py`_ module most importantly contains the function ``unrolling_iterable``
+The `rpython/rlib/unroll.py`_ module most importantly contains the function ``unrolling_iterable``
which wraps an iterator. Looping over the iterator in RPython code will not
produce a loop in the resulting flow graph but will unroll the loop instead.
@@ -154,7 +154,7 @@
``parsing``
===========
-The `pypy/rlib/parsing/`_ module is a still in-development module to generate tokenizers and
+The `rpython/rlib/parsing/`_ module is a still in-development module to generate tokenizers and
parsers in RPython. It is still highly experimental and only really used by the
`Prolog interpreter`_ (although in slightly non-standard ways). The easiest way
to specify a tokenizer/grammar is to write it down using regular expressions and
@@ -204,7 +204,7 @@
anything except a.
To parse a regular expression and to get a matcher for it, you can use the
-function ``make_runner(s)`` in the ``pypy.rlib.parsing.regexparse`` module. It
+function ``make_runner(s)`` in the ``rpython.rlib.parsing.regexparse`` module. It
returns a object with a ``recognize(input)`` method that returns True or False
depending on whether ``input`` matches the string or not.
@@ -213,7 +213,7 @@
EBNF
----
-To describe a tokenizer and a grammar the ``pypy.rlib.parsing.ebnfparse``
+To describe a tokenizer and a grammar the ``rpython.rlib.parsing.ebnfparse``
defines a syntax for doing that.
The syntax file contains a sequence or rules. Every rule either describes a
@@ -295,7 +295,7 @@
The parsing process builds up a tree consisting of instances of ``Symbol`` and
``Nonterminal``, the former corresponding to tokens, the latter to nonterminal
-symbols. Both classes live in the `pypy/rlib/parsing/tree.py`_ module. You can use
+symbols. Both classes live in the `rpython/rlib/parsing/tree.py`_ module. You can use
the ``view()`` method ``Nonterminal`` instances to get a pygame view of the
parse tree.
@@ -310,7 +310,7 @@
++++++++
To write tree visitors for the parse trees that are RPython, there is a special
-baseclass ``RPythonVisitor`` in `pypy/rlib/parsing/tree.py`_ to use. If your
+baseclass ``RPythonVisitor`` in `rpython/rlib/parsing/tree.py`_ to use. If your
class uses this, it will grow a ``dispatch(node)`` method, that calls an
appropriate ``visit_<symbol>`` method, depending on the ``node`` argument. Here
the <symbol> is replaced by the ``symbol`` attribute of the visited node.
diff --git a/pypy/interpreter/baseobjspace.py b/pypy/interpreter/baseobjspace.py
--- a/pypy/interpreter/baseobjspace.py
+++ b/pypy/interpreter/baseobjspace.py
@@ -1494,10 +1494,11 @@
)
return fd
- def warn(self, msg, w_warningcls):
- self.appexec([self.wrap(msg), w_warningcls], """(msg, warningcls):
+ def warn(self, w_msg, w_warningcls, stacklevel=2):
+ self.appexec([w_msg, w_warningcls, self.wrap(stacklevel)],
+ """(msg, warningcls, stacklevel):
import _warnings
- _warnings.warn(msg, warningcls, stacklevel=2)
+ _warnings.warn(msg, warningcls, stacklevel=stacklevel)
""")
diff --git a/pypy/interpreter/pyopcode.py b/pypy/interpreter/pyopcode.py
--- a/pypy/interpreter/pyopcode.py
+++ b/pypy/interpreter/pyopcode.py
@@ -776,17 +776,16 @@
@jit.unroll_safe
def cmp_exc_match(self, w_1, w_2):
- if self.space.is_true(self.space.isinstance(w_2, self.space.w_tuple)):
- for w_t in self.space.fixedview(w_2):
- if self.space.is_true(self.space.isinstance(w_t,
- self.space.w_str)):
- self.space.warn("catching of string exceptions is "
- "deprecated",
- self.space.w_DeprecationWarning)
- elif self.space.is_true(self.space.isinstance(w_2, self.space.w_str)):
- self.space.warn("catching of string exceptions is deprecated",
- self.space.w_DeprecationWarning)
- return self.space.newbool(self.space.exception_match(w_1, w_2))
+ space = self.space
+ if space.is_true(space.isinstance(w_2, space.w_tuple)):
+ for w_t in space.fixedview(w_2):
+ if space.is_true(space.isinstance(w_t, space.w_str)):
+ msg = "catching of string exceptions is deprecated"
+ space.warn(space.wrap(msg), space.w_DeprecationWarning)
+ elif space.is_true(space.isinstance(w_2, space.w_str)):
+ msg = "catching of string exceptions is deprecated"
+ space.warn(space.wrap(msg), space.w_DeprecationWarning)
+ return space.newbool(space.exception_match(w_1, w_2))
def COMPARE_OP(self, testnum, next_instr):
w_2 = self.popvalue()
diff --git a/pypy/module/__builtin__/functional.py b/pypy/module/__builtin__/functional.py
--- a/pypy/module/__builtin__/functional.py
+++ b/pypy/module/__builtin__/functional.py
@@ -133,56 +133,77 @@
v = v.add(step)
return space.newlist(res_w)
+min_jitdriver = jit.JitDriver(name='min',
+ greens=['w_type'], reds='auto')
+max_jitdriver = jit.JitDriver(name='max',
+ greens=['w_type'], reds='auto')
+
+def make_min_max(unroll):
+ @specialize.arg(2)
+ def min_max_impl(space, args, implementation_of):
+ if implementation_of == "max":
+ compare = space.gt
+ jitdriver = max_jitdriver
+ else:
+ compare = space.lt
+ jitdriver = min_jitdriver
+ args_w = args.arguments_w
+ if len(args_w) > 1:
+ w_sequence = space.newtuple(args_w)
+ elif len(args_w):
+ w_sequence = args_w[0]
+ else:
+ msg = "%s() expects at least one argument" % (implementation_of,)
+ raise OperationError(space.w_TypeError, space.wrap(msg))
+ w_key = None
+ kwds = args.keywords
+ if kwds:
+ if kwds[0] == "key" and len(kwds) == 1:
+ w_key = args.keywords_w[0]
+ else:
+ msg = "%s() got unexpected keyword argument" % (implementation_of,)
+ raise OperationError(space.w_TypeError, space.wrap(msg))
+
+ w_iter = space.iter(w_sequence)
+ w_type = space.type(w_iter)
+ w_max_item = None
+ w_max_val = None
+ while True:
+ if not unroll:
+ jitdriver.jit_merge_point(w_type=w_type)
+ try:
+ w_item = space.next(w_iter)
+ except OperationError, e:
+ if not e.match(space, space.w_StopIteration):
+ raise
+ break
+ if w_key is not None:
+ w_compare_with = space.call_function(w_key, w_item)
+ else:
+ w_compare_with = w_item
+ if w_max_item is None or \
+ space.is_true(compare(w_compare_with, w_max_val)):
+ w_max_item = w_item
+ w_max_val = w_compare_with
+ if w_max_item is None:
+ msg = "arg is an empty sequence"
+ raise OperationError(space.w_ValueError, space.wrap(msg))
+ return w_max_item
+ if unroll:
+ min_max_impl = jit.unroll_safe(min_max_impl)
+ return min_max_impl
+
+min_max_unroll = make_min_max(True)
+min_max_normal = make_min_max(False)
@specialize.arg(2)
- at jit.look_inside_iff(lambda space, args, implementation_of:
- jit.isconstant(len(args.arguments_w)) and
- len(args.arguments_w) == 2
-)
def min_max(space, args, implementation_of):
- if implementation_of == "max":
- compare = space.gt
+ if not jit.we_are_jitted() or (jit.isconstant(len(args.arguments_w)) and
+ len(args.arguments_w) == 2):
+ return min_max_unroll(space, args, implementation_of)
else:
- compare = space.lt
- args_w = args.arguments_w
- if len(args_w) > 1:
- w_sequence = space.newtuple(args_w)
- elif len(args_w):
- w_sequence = args_w[0]
- else:
- msg = "%s() expects at least one argument" % (implementation_of,)
- raise OperationError(space.w_TypeError, space.wrap(msg))
- w_key = None
- kwds = args.keywords
- if kwds:
- if kwds[0] == "key" and len(kwds) == 1:
- w_key = args.keywords_w[0]
- else:
- msg = "%s() got unexpected keyword argument" % (implementation_of,)
- raise OperationError(space.w_TypeError, space.wrap(msg))
-
- w_iter = space.iter(w_sequence)
- w_max_item = None
- w_max_val = None
- while True:
- try:
- w_item = space.next(w_iter)
- except OperationError, e:
- if not e.match(space, space.w_StopIteration):
- raise
- break
- if w_key is not None:
- w_compare_with = space.call_function(w_key, w_item)
- else:
- w_compare_with = w_item
- if w_max_item is None or \
- space.is_true(compare(w_compare_with, w_max_val)):
- w_max_item = w_item
- w_max_val = w_compare_with
- if w_max_item is None:
- msg = "arg is an empty sequence"
- raise OperationError(space.w_ValueError, space.wrap(msg))
- return w_max_item
+ return min_max_normal(space, args, implementation_of)
+min_max._always_inline = True
def max(space, __args__):
"""max(iterable[, key=func]) -> value
diff --git a/pypy/module/__builtin__/interp_classobj.py b/pypy/module/__builtin__/interp_classobj.py
--- a/pypy/module/__builtin__/interp_classobj.py
+++ b/pypy/module/__builtin__/interp_classobj.py
@@ -154,9 +154,9 @@
return
elif name == "__del__":
if self.lookup(space, name) is None:
- msg = ("a __del__ method added to an existing class "
- "will not be called")
- space.warn(msg, space.w_RuntimeWarning)
+ msg = ("a __del__ method added to an existing class will "
+ "not be called")
+ space.warn(space.wrap(msg), space.w_RuntimeWarning)
space.setitem(self.w_dict, w_attr, w_value)
def descr_delattr(self, space, w_attr):
@@ -395,9 +395,9 @@
cache = space.fromcache(Cache)
if (not isinstance(self, cache.cls_with_del)
and self.getdictvalue(space, '__del__') is None):
- msg = ("a __del__ method added to an instance "
- "with no __del__ in the class will not be called")
- space.warn(msg, space.w_RuntimeWarning)
+ msg = ("a __del__ method added to an instance with no "
+ "__del__ in the class will not be called")
+ space.warn(space.wrap(msg), space.w_RuntimeWarning)
if w_meth is not None:
space.call_function(w_meth, w_name, w_value)
else:
@@ -454,11 +454,9 @@
else:
w_as_str = self.descr_str(space)
if space.len_w(w_format_spec) > 0:
- space.warn(
- ("object.__format__ with a non-empty format string is "
- "deprecated"),
- space.w_PendingDeprecationWarning
- )
+ msg = ("object.__format__ with a non-empty format string is "
+ "deprecated")
+ space.warn(space.wrap(msg), space.w_PendingDeprecationWarning)
return space.format(w_as_str, w_format_spec)
def descr_len(self, space):
diff --git a/pypy/module/_io/interp_bufferedio.py b/pypy/module/_io/interp_bufferedio.py
--- a/pypy/module/_io/interp_bufferedio.py
+++ b/pypy/module/_io/interp_bufferedio.py
@@ -76,7 +76,7 @@
raise NotImplementedError
def _deprecated_max_buffer_size(self, space):
- space.warn("max_buffer_size is deprecated",
+ space.warn(space.wrap("max_buffer_size is deprecated"),
space.w_DeprecationWarning)
def read_w(self, space, w_size=None):
diff --git a/pypy/module/_io/interp_fileio.py b/pypy/module/_io/interp_fileio.py
--- a/pypy/module/_io/interp_fileio.py
+++ b/pypy/module/_io/interp_fileio.py
@@ -3,6 +3,7 @@
from pypy.interpreter.error import OperationError, wrap_oserror, wrap_oserror2
from rpython.rlib.rarithmetic import r_longlong
from rpython.rlib.rstring import StringBuilder
+from rpython.rlib.rposix import validate_fd
from os import O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC
import sys, os, stat, errno
from pypy.module._io.interp_iobase import W_RawIOBase, convert_size
@@ -117,9 +118,6 @@
return currentsize + BIGCHUNK
return currentsize + SMALLCHUNK
-def verify_fd(fd):
- return
-
class W_FileIO(W_RawIOBase):
def __init__(self, space):
W_RawIOBase.__init__(self, space)
@@ -156,7 +154,7 @@
fd_is_own = False
try:
if fd >= 0:
- verify_fd(fd)
+ validate_fd(fd)
try:
os.fstat(fd)
except OSError, e:
@@ -237,7 +235,7 @@
self.fd = -1
try:
- verify_fd(fd)
+ validate_fd(fd)
os.close(fd)
except OSError, e:
raise wrap_oserror(space, e,
diff --git a/pypy/module/cpyext/import_.py b/pypy/module/cpyext/import_.py
--- a/pypy/module/cpyext/import_.py
+++ b/pypy/module/cpyext/import_.py
@@ -46,8 +46,9 @@
@cpython_api([CONST_STRING], PyObject)
def PyImport_ImportModuleNoBlock(space, name):
- space.warn('PyImport_ImportModuleNoBlock() is not non-blocking',
- space.w_RuntimeWarning)
+ space.warn(
+ space.wrap('PyImport_ImportModuleNoBlock() is not non-blocking'),
+ space.w_RuntimeWarning)
return PyImport_Import(space, space.wrap(rffi.charp2str(name)))
@cpython_api([PyObject], PyObject)
diff --git a/pypy/module/exceptions/interp_exceptions.py b/pypy/module/exceptions/interp_exceptions.py
--- a/pypy/module/exceptions/interp_exceptions.py
+++ b/pypy/module/exceptions/interp_exceptions.py
@@ -176,8 +176,8 @@
if self.w_message is None:
raise OperationError(space.w_AttributeError,
space.wrap("message was deleted"))
- space.warn("BaseException.message has been deprecated as of Python 2.6",
- space.w_DeprecationWarning)
+ msg = "BaseException.message has been deprecated as of Python 2.6"
+ space.warn(space.wrap(msg), space.w_DeprecationWarning)
return self.w_message
def descr_message_set(self, space, w_new):
diff --git a/pypy/module/imp/importing.py b/pypy/module/imp/importing.py
--- a/pypy/module/imp/importing.py
+++ b/pypy/module/imp/importing.py
@@ -174,9 +174,9 @@
"Parent module '%s' not loaded, "
"cannot perform relative import" % ctxt_package))
else:
- space.warn("Parent module '%s' not found "
- "while handling absolute import" % ctxt_package,
- space.w_RuntimeWarning)
+ msg = ("Parent module '%s' not found while handling absolute "
+ "import" % ctxt_package)
+ space.warn(space.wrap(msg), space.w_RuntimeWarning)
rel_modulename = ctxt_package[:dot_position]
rel_level = rel_modulename.count('.') + 1
@@ -533,9 +533,9 @@
if modtype in (PY_SOURCE, PY_COMPILED):
return FindInfo(PKG_DIRECTORY, filepart, None)
else:
- msg = "Not importing directory " +\
- "'%s' missing __init__.py" % (filepart,)
- space.warn(msg, space.w_ImportWarning)
+ msg = ("Not importing directory '%s' missing __init__.py" %
+ (filepart,))
+ space.warn(space.wrap(msg), space.w_ImportWarning)
modtype, suffix, filemode = find_modtype(space, filepart)
try:
if modtype in (PY_SOURCE, PY_COMPILED, C_EXTENSION):
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
@@ -67,11 +67,15 @@
def min(a, axis=None, out=None):
if not hasattr(a, "min"):
a = _numpypy.array(a)
+ if a.size < 1:
+ return _numpypy.array([])
return a.min(axis=axis, out=out)
def max(a, axis=None, out=None):
if not hasattr(a, "max"):
a = _numpypy.array(a)
+ if a.size < 1:
+ return _numpypy.array([])
return a.max(axis=axis, out=out)
def arange(start, stop=None, step=1, dtype=None):
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
@@ -250,7 +250,7 @@
ret = self.implementation.get_imag(self)
if ret:
return W_NDimArray(ret)
- raise OperationError(space.w_NotImplementedError,
+ raise OperationError(space.w_NotImplementedError,
space.wrap('imag not implemented for this dtype'))
def descr_set_real(self, space, w_value):
@@ -261,7 +261,7 @@
def descr_set_imag(self, space, w_value):
# if possible, copy (broadcast) values into self
if not self.get_dtype().is_complex_type():
- raise OperationError(space.w_TypeError,
+ raise OperationError(space.w_TypeError,
space.wrap('array does not have imaginary part to set'))
tmp = self.implementation.get_imag(self)
tmp.setslice(space, convert_to_array(space, w_value))
@@ -302,11 +302,11 @@
@unwrap_spec(axis1=int, axis2=int)
def descr_swapaxes(self, space, axis1, axis2):
"""a.swapaxes(axis1, axis2)
-
+
Return a view of the array with `axis1` and `axis2` interchanged.
-
+
Refer to `numpy.swapaxes` for full documentation.
-
+
See Also
--------
numpy.swapaxes : equivalent function
@@ -439,7 +439,7 @@
ret = impl.base()
if ret is None:
return space.w_None
- return ret
+ return ret
@unwrap_spec(inplace=bool)
def descr_byteswap(self, space, inplace=False):
@@ -492,7 +492,7 @@
"axis1 and axis2 cannot be the same"))
return interp_arrayops.diagonal(space, self.implementation, offset,
axis1, axis2)
-
+
def descr_dump(self, space, w_file):
raise OperationError(space.w_NotImplementedError, space.wrap(
"dump not implemented yet"))
@@ -509,7 +509,7 @@
raise OperationError(space.w_NotImplementedError, space.wrap(
"setting flags not implemented yet"))
- @unwrap_spec(offset=int)
+ @unwrap_spec(offset=int)
def descr_getfield(self, space, w_dtype, offset):
raise OperationError(space.w_NotImplementedError, space.wrap(
"getfield not implemented yet"))
@@ -518,7 +518,7 @@
raise OperationError(space.w_NotImplementedError, space.wrap(
"itemset not implemented yet"))
- @unwrap_spec(neworder=str)
+ @unwrap_spec(neworder=str)
def descr_newbyteorder(self, space, neworder):
raise OperationError(space.w_NotImplementedError, space.wrap(
"newbyteorder not implemented yet"))
@@ -551,7 +551,7 @@
raise OperationError(space.w_NotImplementedError, space.wrap(
"setfield not implemented yet"))
- def descr_setflags(self, space, w_write=None, w_align=None, w_uic=None):
+ def descr_setflags(self, space, w_write=None, w_align=None, w_uic=None):
raise OperationError(space.w_NotImplementedError, space.wrap(
"setflags not implemented yet"))
@@ -572,7 +572,7 @@
"tofile not implemented yet"))
def descr_trace(self, space, w_offset=0, w_axis1=0, w_axis2=1,
- w_dtype=None, w_out=None):
+ w_dtype=None, w_out=None):
raise OperationError(space.w_NotImplementedError, space.wrap(
"trace not implemented yet"))
@@ -627,12 +627,23 @@
w_remainder = self.descr_mod(space, w_other)
return space.newtuple([w_quotient, w_remainder])
- descr_eq = _binop_impl("equal")
- descr_ne = _binop_impl("not_equal")
- descr_lt = _binop_impl("less")
- descr_le = _binop_impl("less_equal")
- descr_gt = _binop_impl("greater")
- descr_ge = _binop_impl("greater_equal")
+ def _binop_comp_impl(ufunc):
+ def impl(self, space, w_other, w_out=None):
+ try:
+ return ufunc(self, space, w_other, w_out)
+ except OperationError, e:
+ if e.match(space, space.w_ValueError):
+ return space.w_False
+ raise e
+
+ return func_with_new_name(impl, ufunc.func_name)
+
+ descr_eq = _binop_comp_impl(_binop_impl("equal"))
+ descr_ne = _binop_comp_impl(_binop_impl("not_equal"))
+ descr_lt = _binop_comp_impl(_binop_impl("less"))
+ descr_le = _binop_comp_impl(_binop_impl("less_equal"))
+ descr_gt = _binop_comp_impl(_binop_impl("greater"))
+ descr_ge = _binop_comp_impl(_binop_impl("greater_equal"))
def _binop_right_impl(ufunc_name):
def impl(self, space, w_other, w_out=None):
@@ -698,7 +709,7 @@
if space.is_none(w_out):
out = None
elif not isinstance(w_out, W_NDimArray):
- raise OperationError(space.w_TypeError, space.wrap(
+ raise OperationError(space.w_TypeError, space.wrap(
'output must be an array'))
else:
out = w_out
@@ -718,7 +729,7 @@
descr_cumsum = _reduce_ufunc_impl('add', cumultative=True)
descr_cumprod = _reduce_ufunc_impl('multiply', cumultative=True)
-
+
def descr_mean(self, space, w_axis=None, w_out=None):
if space.is_none(w_axis):
w_denom = space.wrap(self.get_size())
@@ -863,7 +874,7 @@
swapaxes = interp2app(W_NDimArray.descr_swapaxes),
flat = GetSetProperty(W_NDimArray.descr_get_flatiter),
item = interp2app(W_NDimArray.descr_item),
- real = GetSetProperty(W_NDimArray.descr_get_real,
+ real = GetSetProperty(W_NDimArray.descr_get_real,
W_NDimArray.descr_set_real),
imag = GetSetProperty(W_NDimArray.descr_get_imag,
W_NDimArray.descr_set_imag),
@@ -923,7 +934,7 @@
dtype)
#if dtype is interp_dtype.get_dtype_cache(space).w_float64dtype:
# break
-
+
if dtype is None:
dtype = interp_dtype.get_dtype_cache(space).w_float64dtype
if ndmin > len(shape):
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
@@ -1769,6 +1769,12 @@
b = array(a, dtype='d')
assert a.dtype is b.dtype
+ def test_notequal_different_shapes(self):
+ from _numpypy import array
+ a = array([1, 2])
+ b = array([1, 2, 3, 4])
+ assert (a == b) == False
+
class AppTestMultiDim(BaseNumpyAppTest):
def test_init(self):
diff --git a/pypy/module/struct/formatiterator.py b/pypy/module/struct/formatiterator.py
--- a/pypy/module/struct/formatiterator.py
+++ b/pypy/module/struct/formatiterator.py
@@ -84,11 +84,10 @@
def _maybe_float(self, w_obj):
space = self.space
if space.is_true(space.isinstance(w_obj, space.w_float)):
- space.warn("struct: integer argument expected, got float",
- space.w_DeprecationWarning)
+ msg = "struct: integer argument expected, got float"
else:
- space.warn("integer argument expected, got non-integer",
- space.w_DeprecationWarning)
+ msg = "integer argument expected, got non-integer"
+ space.warn(space.wrap(msg), space.w_DeprecationWarning)
return space.int(w_obj) # wrapped float -> wrapped int or long
else:
diff --git a/pypy/module/test_lib_pypy/test_datetime.py b/pypy/module/test_lib_pypy/test_datetime.py
--- a/pypy/module/test_lib_pypy/test_datetime.py
+++ b/pypy/module/test_lib_pypy/test_datetime.py
@@ -9,6 +9,26 @@
expected = "datetime.datetime(1, 2, 3, 0, 0)"
assert repr(datetime.datetime(1,2,3)) == expected
+def test_attributes():
+ a = datetime.date.today()
+ raises(AttributeError, 'a.abc = 1')
+ a = datetime.time()
+ raises(AttributeError, 'a.abc = 1')
+ a = datetime.tzinfo()
+ raises(AttributeError, 'a.abc = 1')
+ a = datetime.datetime.utcnow()
+ raises(AttributeError, 'a.abc = 1')
+ a = datetime.timedelta()
+ raises(AttributeError, 'a.abc = 1')
+
+def test_unpickle():
+ e = raises(TypeError, datetime.date, '123')
+ assert e.value.args[0] == 'an integer is required'
+ e = raises(TypeError, datetime.time, '123')
+ assert e.value.args[0] == 'an integer is required'
+ e = raises(TypeError, datetime.datetime, '123')
+ assert e.value.args[0] == 'an integer is required'
+
def test_strptime():
import time, sys
if sys.version_info < (2, 6):
diff --git a/pypy/objspace/descroperation.py b/pypy/objspace/descroperation.py
--- a/pypy/objspace/descroperation.py
+++ b/pypy/objspace/descroperation.py
@@ -7,6 +7,7 @@
from rpython.tool.sourcetools import compile2, func_with_new_name
from pypy.module.__builtin__.interp_classobj import W_InstanceObject
from rpython.rlib.objectmodel import specialize
+from rpython.rlib import jit
def object_getattribute(space):
"Utility that returns the app-level descriptor object.__getattribute__."
@@ -118,6 +119,9 @@
def descr__init__(space, w_obj, __args__):
pass
+contains_jitdriver = jit.JitDriver(name='contains',
+ greens=['w_type'], reds='auto')
+
class DescrOperation(object):
_mixin_ = True
@@ -421,7 +425,9 @@
def _contains(space, w_container, w_item):
w_iter = space.iter(w_container)
+ w_type = space.type(w_iter)
while 1:
+ contains_jitdriver.jit_merge_point(w_type=w_type)
try:
w_next = space.next(w_iter)
except OperationError, e:
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
@@ -80,10 +80,8 @@
return W_ComplexObject(rr, ir)
def divmod(self, space, other):
- space.warn(
- "complex divmod(), // and % are deprecated",
- space.w_DeprecationWarning
- )
+ space.warn(space.wrap("complex divmod(), // and % are deprecated"),
+ space.w_DeprecationWarning)
w_div = self.div(other)
div = math.floor(w_div.realval)
w_mod = self.sub(
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
@@ -10,7 +10,7 @@
from rpython.rlib.rarithmetic import ovfcheck_float_to_int, intmask, LONG_BIT
from rpython.rlib.rfloat import (
isinf, isnan, isfinite, INFINITY, NAN, copysign, formatd,
- DTSF_ADD_DOT_0, DTSF_STR_PRECISION)
+ DTSF_ADD_DOT_0, DTSF_STR_PRECISION, float_as_rbigint_ratio)
from rpython.rlib.rbigint import rbigint
from rpython.rlib import rfloat
from rpython.tool.sourcetools import func_with_new_name
@@ -553,27 +553,18 @@
def float_as_integer_ratio__Float(space, w_float):
value = w_float.floatval
- if isinf(value):
+ try:
+ num, den = float_as_rbigint_ratio(value)
+ except OverflowError:
w_msg = space.wrap("cannot pass infinity to as_integer_ratio()")
raise OperationError(space.w_OverflowError, w_msg)
- elif isnan(value):
+ except ValueError:
w_msg = space.wrap("cannot pass nan to as_integer_ratio()")
raise OperationError(space.w_ValueError, w_msg)
- float_part, exp = math.frexp(value)
- for i in range(300):
- if float_part == math.floor(float_part):
- break
- float_part *= 2.0
- exp -= 1
- w_num = W_LongObject.fromfloat(space, float_part)
- w_den = space.newlong(1)
- w_exp = space.newlong(abs(exp))
- w_exp = space.lshift(w_den, w_exp)
- if exp > 0:
- w_num = space.mul(w_num, w_exp)
- else:
- w_den = w_exp
- # Try to return int.
+
+ w_num = space.newlong_from_rbigint(num)
+ w_den = space.newlong_from_rbigint(den)
+ # Try to return int
return space.newtuple([space.int(w_num), space.int(w_den)])
def float_is_integer__Float(space, w_float):
diff --git a/pypy/objspace/std/objecttype.py b/pypy/objspace/std/objecttype.py
--- a/pypy/objspace/std/objecttype.py
+++ b/pypy/objspace/std/objecttype.py
@@ -126,11 +126,8 @@
msg = "format_spec must be a string"
raise OperationError(space.w_TypeError, space.wrap(msg))
if space.len_w(w_format_spec) > 0:
- space.warn(
- ("object.__format__ with a non-empty format string is "
- "deprecated"),
- space.w_PendingDeprecationWarning
- )
+ msg = "object.__format__ with a non-empty format string is deprecated"
+ space.warn(space.wrap(msg), space.w_PendingDeprecationWarning)
return space.format(w_as_str, w_format_spec)
def descr___subclasshook__(space, __args__):
diff --git a/pypy/objspace/std/typeobject.py b/pypy/objspace/std/typeobject.py
--- a/pypy/objspace/std/typeobject.py
+++ b/pypy/objspace/std/typeobject.py
@@ -295,8 +295,9 @@
msg = "can't set attributes on type object '%s'"
raise operationerrfmt(space.w_TypeError, msg, w_self.name)
if name == "__del__" and name not in w_self.dict_w:
- msg = "a __del__ method added to an existing type will not be called"
- space.warn(msg, space.w_RuntimeWarning)
+ msg = ("a __del__ method added to an existing type will not be "
+ "called")
+ space.warn(space.wrap(msg), space.w_RuntimeWarning)
if space.config.objspace.std.withtypeversion:
version_tag = w_self.version_tag()
if version_tag is not None:
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
@@ -119,13 +119,10 @@
w_uni2 = uni_from_str(space, w_str)
except OperationError, e:
if e.match(space, space.w_UnicodeDecodeError):
- if inverse:
- msg = "Unicode unequal comparison failed to convert both " \
- "arguments to Unicode - interpreting them as being unequal"
- else :
- msg = "Unicode equal comparison failed to convert both " \
- "arguments to Unicode - interpreting them as being unequal"
- space.warn(msg, space.w_UnicodeWarning)
+ msg = ("Unicode %s comparison failed to convert both arguments to "
+ "Unicode - interpreting them as being unequal" %
+ "unequal" if inverse else "equal")
+ space.warn(space.wrap(msg), space.w_UnicodeWarning)
return space.newbool(inverse)
raise
result = space.eq(w_uni, w_uni2)
diff --git a/rpython/bin/translatorshell.py b/rpython/bin/translatorshell.py
--- a/rpython/bin/translatorshell.py
+++ b/rpython/bin/translatorshell.py
@@ -15,9 +15,10 @@
t.view() # graph + annotations under the mouse
t.rtype() # use low level operations
- f = t.compile_c() # C compilation
+ lib = t.compile_c() # C compilation as a library
+ f = get_c_function(lib, func) # get the function out of the library
assert f(arg) == func(arg) # sanity check (for C)
-
+
Some functions are provided for the benefit of interactive testing.
Try dir(snippet) for list of current snippets.
@@ -31,6 +32,13 @@
import py
+
+def get_c_function(lib, f):
+ from ctypes import CDLL
+ name = f.__name__
+ return getattr(CDLL(lib.strpath), 'pypy_g_' + name)
+
+
def setup_readline():
import readline
try:
diff --git a/rpython/jit/backend/x86/test/test_zrpy_releasegil.py b/rpython/jit/backend/x86/test/test_zrpy_releasegil.py
--- a/rpython/jit/backend/x86/test/test_zrpy_releasegil.py
+++ b/rpython/jit/backend/x86/test/test_zrpy_releasegil.py
@@ -1,18 +1,99 @@
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
from rpython.rlib.jit import dont_look_inside
+from rpython.rlib.objectmodel import invoke_around_extcall
from rpython.jit.metainterp.optimizeopt import ALL_OPTS_NAMES
-from rpython.rlib.libffi import CDLL, types, ArgChain, clibffi
-from rpython.rtyper.lltypesystem.ll2ctypes import libc_name
from rpython.rtyper.annlowlevel import llhelper
from rpython.jit.backend.x86.test.test_zrpy_gc import BaseFrameworkTests
from rpython.jit.backend.x86.test.test_zrpy_gc import check
+from rpython.tool.udir import udir
class ReleaseGILTests(BaseFrameworkTests):
compile_kwds = dict(enable_opts=ALL_OPTS_NAMES, thread=True)
+ def define_simple(self):
+ class Glob:
+ def __init__(self):
+ self.event = 0
+ glob = Glob()
+ #
+
+ c_strchr = rffi.llexternal('strchr', [rffi.CCHARP, lltype.Signed],
+ rffi.CCHARP)
+
+ def func():
+ glob.event += 1
+
+ def before(n, x):
+ invoke_around_extcall(func, func)
+ return (n, None, None, None, None, None,
+ None, None, None, None, None, None)
+ #
+ def f(n, x, *args):
+ a = rffi.str2charp(str(n))
+ c_strchr(a, ord('0'))
+ lltype.free(a, flavor='raw')
+ n -= 1
+ return (n, x) + args
+ return before, f, None
+
+ def test_simple(self):
+ self.run('simple')
+ assert 'call_release_gil' in udir.join('TestCompileFramework.log').read()
+
+ def define_close_stack(self):
+ #
+ class Glob(object):
+ pass
+ glob = Glob()
+ class X(object):
+ pass
+ #
+ def callback(p1, p2):
+ for i in range(100):
+ glob.lst.append(X())
+ return rffi.cast(rffi.INT, 1)
+ CALLBACK = lltype.Ptr(lltype.FuncType([lltype.Signed,
+ lltype.Signed], rffi.INT))
+ #
+ @dont_look_inside
+ def alloc1():
+ return llmemory.raw_malloc(16)
+ @dont_look_inside
+ def free1(p):
+ llmemory.raw_free(p)
+
+ c_qsort = rffi.llexternal('qsort', [rffi.VOIDP, rffi.SIZE_T,
+ rffi.SIZE_T, CALLBACK], lltype.Void)
+ #
+ def f42():
+ length = len(glob.lst)
+ raw = alloc1()
+ fn = llhelper(CALLBACK, rffi._make_wrapper_for(CALLBACK, callback))
+ c_qsort(rffi.cast(rffi.VOIDP, raw), rffi.cast(rffi.SIZE_T, 2),
+ rffi.cast(rffi.SIZE_T, 8), fn)
+ free1(raw)
+ check(len(glob.lst) > length)
+ del glob.lst[:]
+ #
+ def before(n, x):
+ glob.lst = []
+
+ return (n, None, None, None, None, None,
+ None, None, None, None, None, None)
+ #
+ def f(n, x, *args):
+ f42()
+ n -= 1
+ return (n, x) + args
+ return before, f, None
+
+ def test_close_stack(self):
+ self.run('close_stack')
+ assert 'call_release_gil' in udir.join('TestCompileFramework.log').read()
+
class TestShadowStack(ReleaseGILTests):
gcrootfinder = "shadowstack"
diff --git a/rpython/rlib/rfloat.py b/rpython/rlib/rfloat.py
--- a/rpython/rlib/rfloat.py
+++ b/rpython/rlib/rfloat.py
@@ -419,3 +419,25 @@
def isfinite(x):
"NOT_RPYTHON"
return not isinf(x) and not isnan(x)
+
+def float_as_rbigint_ratio(value):
+ from rpython.rlib.rbigint import rbigint
+
+ if isinf(value):
+ raise OverflowError("cannot pass infinity to as_integer_ratio()")
+ elif isnan(value):
+ raise ValueError("cannot pass nan to as_integer_ratio()")
+ float_part, exp_int = math.frexp(value)
+ for i in range(300):
+ if float_part == math.floor(float_part):
+ break
+ float_part *= 2.0
+ exp_int -= 1
+ num = rbigint.fromfloat(float_part)
+ den = rbigint.fromint(1)
+ exp = den.lshift(abs(exp_int))
+ if exp_int > 0:
+ num = num.mul(exp)
+ else:
+ den = exp
+ return num, den
diff --git a/rpython/rlib/test/test_rarithmetic.py b/rpython/rlib/test/test_rarithmetic.py
--- a/rpython/rlib/test/test_rarithmetic.py
+++ b/rpython/rlib/test/test_rarithmetic.py
@@ -395,16 +395,18 @@
assert not int_between(1, 1, 1)
# these can't be prebuilt on 32bit
-L1 = 0x0102030405060708L
-L2 = 0x0807060504030201L
+U1 = r_ulonglong(0x0102030405060708L)
+U2 = r_ulonglong(0x0807060504030201L)
+S1 = r_longlong(0x0102030405060708L)
+S2 = r_longlong(0x0807060504030201L)
def test_byteswap():
from rpython.rtyper.lltypesystem import rffi, lltype
assert rffi.cast(lltype.Signed, byteswap(rffi.cast(rffi.USHORT, 0x0102))) == 0x0201
assert rffi.cast(lltype.Signed, byteswap(rffi.cast(rffi.INT, 0x01020304))) == 0x04030201
- assert byteswap(rffi.cast(rffi.LONGLONG, L1)) == L2
- assert byteswap(rffi.cast(rffi.ULONGLONG, L1)) == L2
+ assert byteswap(U1) == U2
+ assert byteswap(S1) == S2
assert ((byteswap(2.3) - 1.903598566252326e+185) / 1e185) < 0.000001
assert (rffi.cast(lltype.Float, byteswap(rffi.cast(lltype.SingleFloat, 2.3))) - 4.173496037651603e-08) < 1e-16
diff --git a/rpython/rlib/test/test_rfloat.py b/rpython/rlib/test/test_rfloat.py
new file mode 100644
--- /dev/null
+++ b/rpython/rlib/test/test_rfloat.py
@@ -0,0 +1,131 @@
+import sys, py
+
+from rpython.rlib.rfloat import float_as_rbigint_ratio
+from rpython.rlib.rfloat import break_up_float
+from rpython.rlib.rfloat import copysign
+from rpython.rlib.rfloat import round_away
+from rpython.rlib.rfloat import round_double
+from rpython.rlib.rbigint import rbigint
+
+def test_copysign():
+ assert copysign(1, 1) == 1
+ assert copysign(-1, 1) == 1
+ assert copysign(-1, -1) == -1
+ assert copysign(1, -1) == -1
+ assert copysign(1, -0.) == -1
+
+def test_round_away():
+ assert round_away(.1) == 0.
+ assert round_away(.5) == 1.
+ assert round_away(.7) == 1.
+ assert round_away(1.) == 1.
+ assert round_away(-.5) == -1.
+ assert round_away(-.1) == 0.
+ assert round_away(-.7) == -1.
+ assert round_away(0.) == 0.
+
+def test_round_double():
+ def almost_equal(x, y):
+ assert round(abs(x-y), 7) == 0
+
+ almost_equal(round_double(0.125, 2), 0.13)
+ almost_equal(round_double(0.375, 2), 0.38)
+ almost_equal(round_double(0.625, 2), 0.63)
+ almost_equal(round_double(0.875, 2), 0.88)
+ almost_equal(round_double(-0.125, 2), -0.13)
+ almost_equal(round_double(-0.375, 2), -0.38)
+ almost_equal(round_double(-0.625, 2), -0.63)
+ almost_equal(round_double(-0.875, 2), -0.88)
+
+ almost_equal(round_double(0.25, 1), 0.3)
+ almost_equal(round_double(0.75, 1), 0.8)
+ almost_equal(round_double(-0.25, 1), -0.3)
+ almost_equal(round_double(-0.75, 1), -0.8)
+
+ round_double(-6.5, 0) == -7.0
+ round_double(-5.5, 0) == -6.0
+ round_double(-1.5, 0) == -2.0
+ round_double(-0.5, 0) == -1.0
+ round_double(0.5, 0) == 1.0
+ round_double(1.5, 0) == 2.0
+ round_double(2.5, 0) == 3.0
+ round_double(3.5, 0) == 4.0
+ round_double(4.5, 0) == 5.0
+ round_double(5.5, 0) == 6.0
+ round_double(6.5, 0) == 7.0
+
+ round_double(-25.0, -1) == -30.0
+ round_double(-15.0, -1) == -20.0
+ round_double(-5.0, -1) == -10.0
+ round_double(5.0, -1) == 10.0
+ round_double(15.0, -1) == 20.0
+ round_double(25.0, -1) == 30.0
+ round_double(35.0, -1) == 40.0
+ round_double(45.0, -1) == 50.0
+ round_double(55.0, -1) == 60.0
+ round_double(65.0, -1) == 70.0
+ round_double(75.0, -1) == 80.0
+ round_double(85.0, -1) == 90.0
+ round_double(95.0, -1) == 100.0
+ round_double(12325.0, -1) == 12330.0
+
+ round_double(350.0, -2) == 400.0
+ round_double(450.0, -2) == 500.0
+
+ almost_equal(round_double(0.5e21, -21), 1e21)
+ almost_equal(round_double(1.5e21, -21), 2e21)
+ almost_equal(round_double(2.5e21, -21), 3e21)
+ almost_equal(round_double(5.5e21, -21), 6e21)
+ almost_equal(round_double(8.5e21, -21), 9e21)
+
+ almost_equal(round_double(-1.5e22, -22), -2e22)
+ almost_equal(round_double(-0.5e22, -22), -1e22)
+ almost_equal(round_double(0.5e22, -22), 1e22)
+ almost_equal(round_double(1.5e22, -22), 2e22)
+
+def test_round_half_even():
+ from rpython.rlib import rfloat
+ for func in (rfloat.round_double_short_repr,
+ rfloat.round_double_fallback_repr):
+ # 2.x behavior
+ assert func(2.5, 0, False) == 3.0
+ # 3.x behavior
+ assert func(2.5, 0, True) == 2.0
+
+def test_break_up_float():
+ assert break_up_float('1') == ('', '1', '', '')
+ assert break_up_float('+1') == ('+', '1', '', '')
+ assert break_up_float('-1') == ('-', '1', '', '')
+
+ assert break_up_float('.5') == ('', '', '5', '')
+
+ assert break_up_float('1.2e3') == ('', '1', '2', '3')
+ assert break_up_float('1.2e+3') == ('', '1', '2', '+3')
+ assert break_up_float('1.2e-3') == ('', '1', '2', '-3')
+
+ # some that will get thrown out on return:
+ assert break_up_float('.') == ('', '', '', '')
+ assert break_up_float('+') == ('+', '', '', '')
+ assert break_up_float('-') == ('-', '', '', '')
+ assert break_up_float('e1') == ('', '', '', '1')
+
+ py.test.raises(ValueError, break_up_float, 'e')
+
+
+def test_float_as_rbigint_ratio():
+ for f, ratio in [
+ (0.875, (7, 8)),
+ (-0.875, (-7, 8)),
+ (0.0, (0, 1)),
+ (11.5, (23, 2)),
+ ]:
+ num, den = float_as_rbigint_ratio(f)
+ assert num.eq(rbigint.fromint(ratio[0]))
+ assert den.eq(rbigint.fromint(ratio[1]))
+
+ with py.test.raises(OverflowError):
+ float_as_rbigint_ratio(float('inf'))
+ with py.test.raises(OverflowError):
+ float_as_rbigint_ratio(float('-inf'))
+ with py.test.raises(ValueError):
+ float_as_rbigint_ratio(float('nan'))
diff --git a/rpython/rlib/test/test_timer.py b/rpython/rlib/test/test_timer.py
deleted file mode 100644
--- a/rpython/rlib/test/test_timer.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from rpython.rlib.timer import Timer
-from rpython.translator.c.test.test_genc import compile
-from rpython.annotator.policy import AnnotatorPolicy
-
-
-t = Timer()
-t.start("testc")
-t.stop("testc")
-
-def timer_user():
- assert "testc" not in t.timingorder
- t.start("testa")
- t.stop("testa")
- t.start("testb")
- t.start("testb")
- t.stop("testb")
- t.stop("testb")
- t.start_name("test", "one")
- t.stop_name("test", "one")
- t.dump()
-
-
-def test_compile_timer():
- policy = AnnotatorPolicy()
- f_compiled = compile(timer_user, [], annotatorpolicy=policy)
- f_compiled()
diff --git a/rpython/rlib/timer.py b/rpython/rlib/timer.py
deleted file mode 100644
--- a/rpython/rlib/timer.py
+++ /dev/null
@@ -1,77 +0,0 @@
-import time
-import os
-
-
-def _create_name(name, generation):
- if generation == 0:
- return name
- else:
- return "%s[%s]" % (name, str(generation))
-
-
-class Timer:
- def __init__(self):
- self.reset()
-
- def reset(self):
- self.timings = {}
- self.levels = {}
- self.timingorder = []
-
- def _cleanup_(self):
- self.reset()
-
- def start(self, timer):
- level = self.levels.setdefault(timer, -1)
- new_level = level + 1
- name = _create_name(timer, new_level)
- if name not in self.timings:
- self.timingorder.append(name)
- self.timings[name] = time.time() - self.timings.get(name, 0)
- self.levels[timer] = new_level
-
- def start_name(self, timerone, timertwo):
- self.start(timerone + " " + timertwo)
-
- def stop(self, timer):
- level = self.levels.setdefault(timer, -1)
- if level == -1:
- raise ValueError("Invalid timer name")
- if level >= 0: # timer is active
- name = _create_name(timer, level)
- self.timings[name] = time.time() - self.timings[name]
- self.levels[timer] = level - 1
-
- def stop_name(self, timerone, timertwo):
- self.stop(timerone + " " + timertwo)
-
- def value(self, timer):
- level = self.levels.get(timer, -1)
- if level == -1:
- result = "%fs" % self.timings[timer]
- else:
- result = "%fs (still running)" % (time.time() - self.timings[timer])
- return result
-
- def dump(self):
- outlist = []
- for timer in self.timingorder:
- value = self.value(timer)
- outlist.append("%s = %s" % (timer, value))
- os.write(2, "\n".join(outlist))
-
-
-class DummyTimer:
- def start(self, timer):
- pass
- def start_name(self, timerone, timertwo):
- pass
- def stop(self, timer):
- pass
- def stop_name(self, timerone, timertwo):
- pass
- def value(self, timer):
- return "Timing disabled"
- def dump(self):
- pass
-
diff --git a/rpython/rtyper/llinterp.py b/rpython/rtyper/llinterp.py
--- a/rpython/rtyper/llinterp.py
+++ b/rpython/rtyper/llinterp.py
@@ -11,7 +11,8 @@
from rpython.rlib.objectmodel import (ComputedIntSymbolic, CDefinedIntSymbolic,
Symbolic)
# intmask is used in an exec'd code block
-from rpython.rlib.rarithmetic import ovfcheck, is_valid_int, intmask
+from rpython.rlib.rarithmetic import (ovfcheck, is_valid_int, intmask,
+ r_uint, r_longlong, r_ulonglong, r_longlonglong)
from rpython.rtyper.lltypesystem import lltype, llmemory, lloperation, llheap, rclass
from rpython.rtyper.ootypesystem import ootype
diff --git a/rpython/rtyper/rint.py b/rpython/rtyper/rint.py
--- a/rpython/rtyper/rint.py
+++ b/rpython/rtyper/rint.py
@@ -1,17 +1,16 @@
import sys
-from rpython.tool.pairtype import pairtype
+
from rpython.annotator import model as annmodel
from rpython.flowspace.operation import op_appendices
-from rpython.rtyper.lltypesystem.lltype import Signed, Unsigned, Bool, Float, \
- Void, Char, UniChar, malloc, UnsignedLongLong, \
- SignedLongLong, build_number, Number, cast_primitive, typeOf, \
- SignedLongLongLong
-from rpython.rtyper.rmodel import IntegerRepr, inputconst
-from rpython.rlib.rarithmetic import intmask, r_int, r_uint, r_ulonglong, \
- r_longlong, is_emulated_long
-from rpython.rtyper.error import TyperError, MissingRTypeOperation
-from rpython.rtyper.rmodel import log
from rpython.rlib import objectmodel
+from rpython.rlib.rarithmetic import intmask, r_int, r_longlong
+from rpython.rtyper.error import TyperError
+from rpython.rtyper.lltypesystem.lltype import (Signed, Unsigned, Bool, Float,
+ Char, UniChar, UnsignedLongLong, SignedLongLong, build_number, Number,
+ cast_primitive, typeOf, SignedLongLongLong)
+from rpython.rtyper.rmodel import IntegerRepr, inputconst, log
+from rpython.tool.pairtype import pairtype
+
_integer_reprs = {}
def getintegerrepr(lltype, prefix=None):
@@ -128,7 +127,7 @@
#comparisons: eq is_ ne lt le gt ge
- def rtype_eq(_, hop):
+ def rtype_eq(_, hop):
return _rtype_compare_template(hop, 'eq')
rtype_is_ = rtype_eq
@@ -259,7 +258,7 @@
get_ll_le_function = get_ll_eq_function
def get_ll_ge_function(self):
- return None
+ return None
def get_ll_hash_function(self):
if (sys.maxint == 2147483647 and
@@ -279,7 +278,7 @@
ll_dummy_value = -1
def rtype_chr(_, hop):
- vlist = hop.inputargs(Signed)
+ vlist = hop.inputargs(Signed)
if hop.has_implicit_exception(ValueError):
hop.exception_is_here()
hop.gendirectcall(ll_check_chr, vlist[0])
@@ -301,8 +300,8 @@
vlist = hop.inputargs(self)
return hop.genop(self.opprefix + 'is_true', vlist, resulttype=Bool)
- #Unary arithmetic operations
-
+ #Unary arithmetic operations
+
def rtype_abs(self, hop):
self = self.as_int
vlist = hop.inputargs(self)
@@ -325,7 +324,7 @@
self = self.as_int
vlist = hop.inputargs(self)
return hop.genop(self.opprefix + 'invert', vlist, resulttype=self)
-
+
def rtype_neg(self, hop):
self = self.as_int
vlist = hop.inputargs(self)
diff --git a/rpython/rtyper/rmodel.py b/rpython/rtyper/rmodel.py
--- a/rpython/rtyper/rmodel.py
+++ b/rpython/rtyper/rmodel.py
@@ -1,20 +1,18 @@
+from rpython.annotator import model as annmodel, unaryop, binaryop, description
+from rpython.flowspace.model import Constant
+from rpython.rtyper.error import TyperError, MissingRTypeOperation
+from rpython.rtyper.lltypesystem import lltype
+from rpython.rtyper.lltypesystem.lltype import (Void, Bool, Float, typeOf,
+ LowLevelType, isCompatibleType)
from rpython.tool.pairtype import pairtype, extendabletype, pair
-from rpython.annotator import model as annmodel, unaryop, binaryop
-from rpython.annotator import description
-from rpython.flowspace.model import Constant
-from rpython.rtyper.lltypesystem.lltype import \
- Void, Bool, Float, Signed, Char, UniChar, \
- typeOf, LowLevelType, Ptr, isCompatibleType
-from rpython.rtyper.lltypesystem import lltype, llmemory
-from rpython.rtyper.ootypesystem import ootype
-from rpython.rtyper.error import TyperError, MissingRTypeOperation
-# initialization states for Repr instances
-class setupstate(object):
- NOTINITIALIZED = 0
+# initialization states for Repr instances
+
+class setupstate(object):
+ NOTINITIALIZED = 0
INPROGRESS = 1
- BROKEN = 2
+ BROKEN = 2
FINISHED = 3
DELAYED = 4
@@ -27,7 +25,7 @@
iterating over.
"""
__metaclass__ = extendabletype
- _initialized = setupstate.NOTINITIALIZED
+ _initialized = setupstate.NOTINITIALIZED
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.lowleveltype)
@@ -35,31 +33,31 @@
def compact_repr(self):
return '%s %s' % (self.__class__.__name__.replace('Repr','R'), self.lowleveltype._short_name())
- def setup(self):
+ def setup(self):
""" call _setup_repr() and keep track of the initializiation
status to e.g. detect recursive _setup_repr invocations.
- the '_initialized' attr has four states:
+ the '_initialized' attr has four states:
"""
- if self._initialized == setupstate.FINISHED:
- return
- elif self._initialized == setupstate.BROKEN:
+ if self._initialized == setupstate.FINISHED:
+ return
+ elif self._initialized == setupstate.BROKEN:
raise BrokenReprTyperError(
"cannot setup already failed Repr: %r" %(self,))
- elif self._initialized == setupstate.INPROGRESS:
+ elif self._initialized == setupstate.INPROGRESS:
raise AssertionError(
"recursive invocation of Repr setup(): %r" %(self,))
elif self._initialized == setupstate.DELAYED:
raise AssertionError(
"Repr setup() is delayed and cannot be called yet: %r" %(self,))
- assert self._initialized == setupstate.NOTINITIALIZED
- self._initialized = setupstate.INPROGRESS
- try:
- self._setup_repr()
- except TyperError, e:
- self._initialized = setupstate.BROKEN
- raise
- else:
- self._initialized = setupstate.FINISHED
+ assert self._initialized == setupstate.NOTINITIALIZED
+ self._initialized = setupstate.INPROGRESS
+ try:
+ self._setup_repr()
+ except TyperError, e:
+ self._initialized = setupstate.BROKEN
+ raise
+ else:
+ self._initialized = setupstate.FINISHED
def _setup_repr(self):
"For recursive data structure, which must be initialized in two steps."
@@ -68,15 +66,15 @@
"""Same as setup(), called a bit later, for effects that are only
needed after the typer finished (as opposed to needed for other parts
of the typer itself)."""
- if self._initialized == setupstate.BROKEN:
+ if self._initialized == setupstate.BROKEN:
raise BrokenReprTyperError("cannot perform setup_final_touch "
"on failed Repr: %r" %(self,))
assert self._initialized == setupstate.FINISHED, (
"setup_final() on repr with state %s: %r" %
(self._initialized, self))
- self._setup_repr_final()
+ self._setup_repr_final()
- def _setup_repr_final(self):
+ def _setup_repr_final(self):
pass
def is_setup_delayed(self):
@@ -98,8 +96,8 @@
def __getattr__(self, name):
# Assume that when an attribute is missing, it's because setup() needs
# to be called
- if not (name[:2] == '__' == name[-2:]):
- if self._initialized == setupstate.NOTINITIALIZED:
+ if not (name[:2] == '__' == name[-2:]):
+ if self._initialized == setupstate.NOTINITIALIZED:
self.setup()
try:
return self.__dict__[name]
@@ -119,7 +117,7 @@
else:
raise TyperError("convert_desc_or_const expects a Desc"
"or Constant: %r" % desc_or_const)
-
+
def convert_const(self, value):
"Convert the given constant value to the low-level repr of 'self'."
if self.lowleveltype is not Void:
@@ -137,12 +135,12 @@
values of this Repr.
This can return None to mean that simply using '==' is fine.
"""
- raise TyperError, 'no equality function for %r' % self
+ raise TyperError('no equality function for %r' % self)
def get_ll_hash_function(self):
"""Return a hash(x) function for low-level values of this Repr.
"""
- raise TyperError, 'no hashing function for %r' % self
+ raise TyperError('no hashing function for %r' % self)
def get_ll_fasthash_function(self):
"""Return a 'fast' hash(x) function for low-level values of this
@@ -272,12 +270,15 @@
r_baseiter = r_container.make_iterator_repr()
return EnumerateIteratorRepr(r_baseiter)
return r_container.make_iterator_repr(*self.variant)
+
def rtyper_makekey_ex(self, rtyper):
return self.__class__, rtyper.makekey(self.s_container), self.variant
+
class __extend__(annmodel.SomeImpossibleValue):
def rtyper_makerepr(self, rtyper):
return impossible_repr
+
def rtyper_makekey(self):
return self.__class__,
@@ -285,14 +286,14 @@
class __extend__(pairtype(Repr, Repr)):
-
+
def rtype_is_((robj1, robj2), hop):
if hop.s_result.is_constant():
return inputconst(Bool, hop.s_result.const)
return hop.rtyper.type_system.generic_is(robj1, robj2, hop)
# default implementation for checked getitems
-
+
def rtype_getitem_idx_key((r_c1, r_o1), hop):
return pair(r_c1, r_o1).rtype_getitem(hop)
@@ -343,7 +344,7 @@
return self._opprefix
opprefix = property(_get_opprefix)
-
+
class BoolRepr(IntegerRepr):
lowleveltype = Bool
# NB. no 'opprefix' here. Use 'as_int' systematically.
@@ -411,9 +412,9 @@
c.concretetype = lltype
return c
-class BrokenReprTyperError(TyperError):
- """ raised when trying to setup a Repr whose setup
- has failed already.
+class BrokenReprTyperError(TyperError):
+ """ raised when trying to setup a Repr whose setup
+ has failed already.
"""
def mangle(prefix, name):
@@ -489,6 +490,3 @@
def warning(msg):
log.WARNING(msg)
-
-
-
diff --git a/rpython/rtyper/rpbc.py b/rpython/rtyper/rpbc.py
--- a/rpython/rtyper/rpbc.py
+++ b/rpython/rtyper/rpbc.py
@@ -1,18 +1,15 @@
import types
-import sys
+
+from rpython.annotator import model as annmodel, description
+from rpython.flowspace.model import Constant
+from rpython.rtyper import rclass, callparse
+from rpython.rtyper.annlowlevel import llstr
+from rpython.rtyper.error import TyperError
+from rpython.rtyper.lltypesystem.lltype import typeOf, Void, Bool
+from rpython.rtyper.rmodel import (Repr, inputconst, CanBeNull, mangle,
+ inputdesc, warning, impossible_repr)
from rpython.tool.pairtype import pair, pairtype
-from rpython.annotator import model as annmodel
-from rpython.annotator import description
-from rpython.flowspace.model import Constant
-from rpython.rtyper.lltypesystem.lltype import \
- typeOf, Void, Bool, nullptr, frozendict, Ptr, Struct, malloc
-from rpython.rtyper.error import TyperError
-from rpython.rtyper.rmodel import Repr, inputconst, CanBeNull, \
- mangle, inputdesc, warning, impossible_repr
-from rpython.rtyper import rclass
-from rpython.rtyper.annlowlevel import llstr, llunicode
-from rpython.rtyper import callparse
def small_cand(rtyper, s_pbc):
if 1 < len(s_pbc.descriptions) < rtyper.getconfig().translation.withsmallfuncsets and \
@@ -26,7 +23,7 @@
class __extend__(annmodel.SomePBC):
def rtyper_makerepr(self, rtyper):
if self.isNone():
- return none_frozen_pbc_repr
+ return none_frozen_pbc_repr
kind = self.getKind()
if issubclass(kind, description.FunctionDesc):
sample = self.any_description()
@@ -50,7 +47,7 @@
elif issubclass(kind, description.MethodOfFrozenDesc):
getRepr = rtyper.type_system.rpbc.MethodOfFrozenPBCRepr
else:
- raise TyperError("unexpected PBC kind %r"%(kind,))
+ raise TyperError("unexpected PBC kind %r" % (kind,))
return getRepr(rtyper, self)
@@ -82,7 +79,7 @@
"""
concretetable = {} # (shape,index): row, maybe with duplicates
uniquerows = [] # list of rows, without duplicates
-
+
def lookuprow(row):
# a 'matching' row is one that has the same llfn, expect
# that it may have more or less 'holes'
@@ -333,15 +330,15 @@
return hop.llops.convertvar(v, rresult, hop.r_result)
class __extend__(pairtype(AbstractFunctionsPBCRepr, AbstractFunctionsPBCRepr)):
- def convert_from_to((r_fpbc1, r_fpbc2), v, llops):
- # this check makes sense because both source and dest repr are FunctionsPBCRepr
- if r_fpbc1.lowleveltype == r_fpbc2.lowleveltype:
- return v
- if r_fpbc1.lowleveltype is Void:
- return inputconst(r_fpbc2, r_fpbc1.s_pbc.const)
- if r_fpbc2.lowleveltype is Void:
- return inputconst(Void, None)
- return NotImplemented
+ def convert_from_to((r_fpbc1, r_fpbc2), v, llops):
+ # this check makes sense because both source and dest repr are FunctionsPBCRepr
+ if r_fpbc1.lowleveltype == r_fpbc2.lowleveltype:
+ return v
+ if r_fpbc1.lowleveltype is Void:
+ return inputconst(r_fpbc2, r_fpbc1.s_pbc.const)
+ if r_fpbc2.lowleveltype is Void:
+ return inputconst(Void, None)
+ return NotImplemented
class OverriddenFunctionPBCRepr(Repr):
def __init__(self, rtyper, s_pbc):
@@ -377,7 +374,7 @@
result = rtyper.type_system.rpbc.MultipleFrozenPBCRepr(rtyper,
access)
rtyper.pbc_reprs[access] = result
- rtyper.add_pendingsetup(result)
+ rtyper.add_pendingsetup(result)
return result
@@ -429,7 +426,7 @@
def convert_const(self, pbc):
if pbc is None:
- return self.null_instance()
+ return self.null_instance()
if isinstance(pbc, types.MethodType) and pbc.im_self is None:
value = pbc.im_func # unbound method -> bare function
frozendesc = self.rtyper.annotator.bookkeeper.getdesc(pbc)
@@ -455,7 +452,7 @@
mangled_name = mangle('pbc', attr)
fields.append((mangled_name, r_value.lowleveltype))
self.fieldmap[attr] = mangled_name, r_value
- return fields
+ return fields
def convert_desc(self, frozendesc):
if (self.access_set is not None and
@@ -525,7 +522,7 @@
# XXX sort this out
#call_families = rtyper.annotator.getpbccallfamilies()
#call_families.find((None, self.function))
-
+
if s_pbc.can_be_none():
raise TyperError("unsupported: variable of type "
"method-of-frozen-PBC or None")
@@ -534,7 +531,7 @@
for desc in s_pbc.descriptions:
assert desc.funcdesc is self.funcdesc
im_selves.append(desc.frozendesc)
-
+
self.s_im_self = annmodel.SomePBC(im_selves)
self.r_im_self = rtyper.getrepr(self.s_im_self)
self.lowleveltype = self.r_im_self.lowleveltype
@@ -548,7 +545,7 @@
def convert_desc(self, mdesc):
if mdesc.funcdesc is not self.funcdesc:
- raise TyperError("not a method bound on %r: %r" % (self.funcdesc,
+ raise TyperError("not a method bound on %r: %r" % (self.funcdesc,
mdesc))
return self.r_im_self.convert_desc(mdesc.frozendesc)
@@ -615,7 +612,7 @@
def convert_from_to((r_from, _), v, llops):
return inputconst(Void, None)
-
+
def rtype_is_((robj1, rnone2), hop):
if hop.s_result.is_constant():
return hop.inputconst(Bool, hop.s_result.const)
@@ -666,7 +663,7 @@
def convert_desc(self, desc):
if desc not in self.s_pbc.descriptions:
- raise TyperError("%r not in %r" % (cls, self))
+ raise TyperError("%r not in %r" % (desc, self))
if self.lowleveltype is Void:
return None
subclassdef = desc.getuniqueclassdef()
@@ -726,7 +723,7 @@
s_init = classdef.classdesc.s_read_attribute('__init__')
v_init = Constant("init-func-dummy") # this value not really used
- if (isinstance(s_init, annmodel.SomeImpossibleValue) and
+ if (isinstance(s_init, annmodel.SomeImpossibleValue) and
classdef.classdesc.is_exception_class() and
classdef.has_no_attrs()):
# special case for instanciating simple built-in
@@ -753,7 +750,7 @@
else:
s_init = access_set.s_value
v_init = r_class.getpbcfield(vtypeptr, access_set, '__init__',
- hop.llops)
+ hop.llops)
v_instance = self._instantiate_runtime_class(hop, vtypeptr, r_instance)
if isinstance(s_init, annmodel.SomeImpossibleValue):
@@ -771,7 +768,6 @@
return v_instance
-
class __extend__(pairtype(AbstractClassesPBCRepr, rclass.AbstractClassRepr)):
def convert_from_to((r_clspbc, r_cls), v, llops):
# turn a PBC of classes to a standard pointer-to-vtable class repr
@@ -904,4 +900,3 @@
for cdef1 in classdef.getmro():
for attrname in cdef1.attrs:
yield cdef1, attrname
-
diff --git a/rpython/rtyper/rptr.py b/rpython/rtyper/rptr.py
--- a/rpython/rtyper/rptr.py
+++ b/rpython/rtyper/rptr.py
@@ -1,10 +1,10 @@
-from rpython.tool.pairtype import pairtype
from rpython.annotator import model as annmodel
from rpython.flowspace import model as flowmodel
+from rpython.rlib.rarithmetic import r_uint
+from rpython.rtyper.error import TyperError
from rpython.rtyper.lltypesystem import lltype
-from rpython.rtyper.error import TyperError
from rpython.rtyper.rmodel import Repr, IntegerRepr
-from rpython.rlib.rarithmetic import r_uint
+from rpython.tool.pairtype import pairtype
class __extend__(annmodel.SomePtr):
@@ -345,4 +345,3 @@
if r_from.lowleveltype == r_to.lowleveltype:
return v
return NotImplemented
-
diff --git a/rpython/rtyper/rrange.py b/rpython/rtyper/rrange.py
--- a/rpython/rtyper/rrange.py
+++ b/rpython/rtyper/rrange.py
@@ -1,9 +1,9 @@
-from rpython.tool.pairtype import pairtype
+from rpython.flowspace.model import Constant
from rpython.rtyper.error import TyperError
from rpython.rtyper.lltypesystem.lltype import Signed, Void, Ptr
+from rpython.rtyper.rlist import dum_nocheck, dum_checkidx
from rpython.rtyper.rmodel import Repr, IntegerRepr, IteratorRepr
-from rpython.flowspace.model import Constant
-from rpython.rtyper.rlist import dum_nocheck, dum_checkidx
+from rpython.tool.pairtype import pairtype
class AbstractRangeRepr(Repr):
@@ -54,9 +54,9 @@
def _ll_rangelen(start, stop, step):
if step > 0:
- result = (stop - start + (step-1)) // step
+ result = (stop - start + (step - 1)) // step
else:
- result = (start - stop - (step+1)) // (-step)
+ result = (start - stop - (step + 1)) // (-step)
if result < 0:
result = 0
return result
diff --git a/rpython/rtyper/rstr.py b/rpython/rtyper/rstr.py
--- a/rpython/rtyper/rstr.py
+++ b/rpython/rtyper/rstr.py
@@ -1,16 +1,15 @@
-from rpython.tool.staticmethods import StaticMethods
+from rpython.annotator import model as annmodel
+from rpython.rlib import jit
+from rpython.rtyper import rint
+from rpython.rtyper.error import TyperError
+from rpython.rtyper.lltypesystem.lltype import (Signed, Bool, Void, UniChar,
+ typeOf)
+from rpython.rtyper.rmodel import IntegerRepr, IteratorRepr, inputconst, Repr
+from rpython.rtyper.rtuple import AbstractTupleRepr
from rpython.tool.pairtype import pairtype, pair
from rpython.tool.sourcetools import func_with_new_name
-from rpython.annotator import model as annmodel
-from rpython.rlib import jit
-from rpython.rlib.nonconst import NonConstant
-from rpython.rtyper.error import TyperError
-from rpython.rtyper.rmodel import IntegerRepr, IteratorRepr
-from rpython.rtyper.rmodel import inputconst, Repr
-from rpython.rtyper.rtuple import AbstractTupleRepr
-from rpython.rtyper import rint
-from rpython.rtyper.lltypesystem.lltype import Signed, Bool, Void, UniChar,\
- cast_primitive, typeOf
+from rpython.tool.staticmethods import StaticMethods
+
class AbstractStringRepr(Repr):
@@ -37,7 +36,7 @@
def ll_raise_unicode_exception_decode(self, errors, encoding, msg, s,
startingpos, endingpos):
raise UnicodeDecodeError(encoding, s, startingpos, endingpos, msg)
-
+
class AbstractCharRepr(AbstractStringRepr):
def rtype_method_lower(self, hop):
@@ -87,7 +86,7 @@
def ll_raise_unicode_exception_encode(self, errors, encoding, msg, u,
startingpos, endingpos):
raise UnicodeEncodeError(encoding, u, startingpos, endingpos, msg)
-
+
class __extend__(annmodel.SomeString):
def rtyper_makerepr(self, rtyper):
return rtyper.type_system.rstr.string_repr
@@ -356,8 +355,8 @@
hop.exception_is_here()
return hop.gendirectcall(self.ll.ll_int, v_str, c_base)
if not hop.args_r[1] == rint.signed_repr:
- raise TyperError, 'base needs to be an int'
- v_str, v_base= hop.inputargs(string_repr, rint.signed_repr)
+ raise TyperError('base needs to be an int')
+ v_str, v_base = hop.inputargs(string_repr, rint.signed_repr)
hop.exception_is_here()
More information about the pypy-commit
mailing list