[pypy-commit] pypy release-2.3.x: merge default into release to profit from last-minute struct, buffer improvements
mattip
noreply at buildbot.pypy.org
Tue May 6 10:28:20 CEST 2014
Author: mattip <matti.picus at gmail.com>
Branch: release-2.3.x
Changeset: r71316:3d7f7e8ac940
Date: 2014-05-06 11:08 +0300
http://bitbucket.org/pypy/pypy/changeset/3d7f7e8ac940/
Log: merge default into release to profit from last-minute struct, buffer
improvements
diff --git a/pypy/interpreter/baseobjspace.py b/pypy/interpreter/baseobjspace.py
--- a/pypy/interpreter/baseobjspace.py
+++ b/pypy/interpreter/baseobjspace.py
@@ -390,11 +390,7 @@
self.user_del_action = UserDelAction(self)
self._code_of_sys_exc_info = None
- from pypy.interpreter.pycode import cpython_magic, default_magic
- self.our_magic = default_magic
- self.host_magic = cpython_magic
# can be overridden to a subclass
-
self.initialize()
def startup(self):
diff --git a/pypy/module/array/interp_array.py b/pypy/module/array/interp_array.py
--- a/pypy/module/array/interp_array.py
+++ b/pypy/module/array/interp_array.py
@@ -612,6 +612,15 @@
data[index] = char
array._charbuf_stop()
+ def getslice(self, start, stop, step, size):
+ if step == 1:
+ data = self.array._charbuf_start()
+ try:
+ return rffi.charpsize2str(rffi.ptradd(data, start), size)
+ finally:
+ self.array._charbuf_stop()
+ return Buffer.getslice(self, start, stop, step, size)
+
def get_raw_address(self):
return self.array._charbuf_start()
diff --git a/pypy/module/mmap/interp_mmap.py b/pypy/module/mmap/interp_mmap.py
--- a/pypy/module/mmap/interp_mmap.py
+++ b/pypy/module/mmap/interp_mmap.py
@@ -40,10 +40,10 @@
self.check_valid()
return self.space.wrap(self.mmap.read(num))
- @unwrap_spec(tofind='bufferstr')
- def find(self, tofind, w_start=None, w_end=None):
+ def find(self, w_tofind, w_start=None, w_end=None):
self.check_valid()
space = self.space
+ tofind = space.getarg_w('s#', w_tofind)
if w_start is None:
start = self.mmap.pos
else:
@@ -54,10 +54,10 @@
end = space.getindex_w(w_end, None)
return space.wrap(self.mmap.find(tofind, start, end))
- @unwrap_spec(tofind='bufferstr')
- def rfind(self, tofind, w_start=None, w_end=None):
+ def rfind(self, w_tofind, w_start=None, w_end=None):
self.check_valid()
space = self.space
+ tofind = space.getarg_w('s#', w_tofind)
if w_start is None:
start = self.mmap.pos
else:
@@ -87,9 +87,9 @@
except OSError, e:
raise mmap_error(self.space, e)
- @unwrap_spec(data='bufferstr')
- def write(self, data):
+ def write(self, w_data):
self.check_valid()
+ data = self.space.getarg_w('s#', w_data)
self.check_writeable()
try:
self.mmap.write(data)
diff --git a/pypy/module/posix/interp_posix.py b/pypy/module/posix/interp_posix.py
--- a/pypy/module/posix/interp_posix.py
+++ b/pypy/module/posix/interp_posix.py
@@ -142,12 +142,13 @@
else:
return space.wrap(s)
- at unwrap_spec(fd=c_int, data='bufferstr')
-def write(space, fd, data):
+ at unwrap_spec(fd=c_int)
+def write(space, fd, w_data):
"""Write a string to a file descriptor. Return the number of bytes
actually written, which may be smaller than len(data)."""
+ data = space.getarg_w('s*', w_data)
try:
- res = os.write(fd, data)
+ res = os.write(fd, data.as_str())
except OSError, e:
raise wrap_oserror(space, e)
else:
diff --git a/pypy/module/pypyjit/test_pypy_c/test_buffers.py b/pypy/module/pypyjit/test_pypy_c/test_buffers.py
--- a/pypy/module/pypyjit/test_pypy_c/test_buffers.py
+++ b/pypy/module/pypyjit/test_pypy_c/test_buffers.py
@@ -25,3 +25,38 @@
guard_true(i69, descr=...)
--TICK--
""")
+
+ def test_struct_unpack(self):
+ def main(n):
+ import struct
+ import array
+ a = array.array('c', struct.pack('i', 42))
+ i = 0
+ while i < n:
+ i += 1
+ struct.unpack('i', a) # ID: unpack
+ return i
+ log = self.run(main, [1000])
+ assert log.result == 1000
+ loop, = log.loops_by_filename(self.filepath)
+ assert loop.match_by_id('unpack', """
+ guard_not_invalidated(descr=...)
+ p90 = newstr(4)
+ call(ConstClass(copy_raw_to_string), i55, p90, 0, 4, descr=<Callv 0 irii EF=4>)
+ guard_no_exception(descr=...)
+ i91 = strgetitem(p90, 0)
+ i92 = strgetitem(p90, 1)
+ i93 = int_lshift(i92, 8)
+ i94 = int_or(i91, i93)
+ i95 = strgetitem(p90, 2)
+ i96 = int_lshift(i95, 16)
+ i97 = int_or(i94, i96)
+ i98 = strgetitem(p90, 3)
+ i99 = int_ge(i98, 128)
+ guard_false(i99, descr=...)
+ i100 = int_lshift(i98, 24)
+ i101 = int_or(i97, i100)
+ i102 = getfield_raw(\d+, descr=<FieldS pypysig_long_struct.c_value 0>)
+ i103 = int_lt(i102, 0)
+ guard_false(i103, descr=...)
+ """)
diff --git a/pypy/module/pypyjit/test_pypy_c/test_misc.py b/pypy/module/pypyjit/test_pypy_c/test_misc.py
--- a/pypy/module/pypyjit/test_pypy_c/test_misc.py
+++ b/pypy/module/pypyjit/test_pypy_c/test_misc.py
@@ -348,51 +348,6 @@
loop, = log.loops_by_id("globalread", is_entry_bridge=True)
assert len(loop.ops_by_id("globalread")) == 0
- def test_struct_module(self):
- def main():
- import struct
- i = 1
- while i < 1000:
- x = struct.unpack("i", struct.pack("i", i))[0] # ID: struct
- i += x / i
- return i
-
- log = self.run(main)
- assert log.result == main()
-
- loop, = log.loops_by_id("struct")
- if sys.maxint == 2 ** 63 - 1:
- extra = """
- i8 = int_ge(i4, -2147483648)
- guard_true(i8, descr=...)
- """
- else:
- extra = ""
- # This could, of course stand some improvement, to remove all these
- # arithmatic ops, but we've removed all the core overhead.
- assert loop.match_by_id("struct", """
- guard_not_invalidated(descr=...)
- # struct.pack
- %(32_bit_only)s
- i11 = int_and(i4, 255)
- i13 = int_rshift(i4, 8)
- i14 = int_and(i13, 255)
- i16 = int_rshift(i13, 8)
- i17 = int_and(i16, 255)
- i19 = int_rshift(i16, 8)
- i20 = int_and(i19, 255)
-
- # struct.unpack
- i22 = int_lshift(i14, 8)
- i23 = int_or(i11, i22)
- i25 = int_lshift(i17, 16)
- i26 = int_or(i23, i25)
- i28 = int_ge(i20, 128)
- guard_false(i28, descr=...)
- i30 = int_lshift(i20, 24)
- i31 = int_or(i26, i30)
- """ % {"32_bit_only": extra})
-
def test_eval(self):
def main():
i = 1
diff --git a/pypy/module/pypyjit/test_pypy_c/test_struct.py b/pypy/module/pypyjit/test_pypy_c/test_struct.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/pypyjit/test_pypy_c/test_struct.py
@@ -0,0 +1,84 @@
+from pypy.module.pypyjit.test_pypy_c.test_00_model import BaseTestPyPyC
+
+
+class TestStruct(BaseTestPyPyC):
+ def test_struct_function(self):
+ def main(n):
+ import struct
+ i = 1
+ while i < n:
+ x = struct.unpack("i", struct.pack("i", i))[0] # ID: struct
+ i += x / i
+ return i
+
+ log = self.run(main, [1000])
+ assert log.result == main(1000)
+
+ loop, = log.loops_by_filename(self.filepath)
+ # This could, of course stand some improvement, to remove all these
+ # arithmatic ops, but we've removed all the core overhead.
+ assert loop.match_by_id("struct", """
+ guard_not_invalidated(descr=...)
+ # struct.pack
+ i8 = int_ge(i4, -2147483648)
+ guard_true(i8, descr=...)
+ i9 = int_le(i4, 2147483647)
+ guard_true(i9, descr=...)
+ i11 = int_and(i4, 255)
+ i13 = int_rshift(i4, 8)
+ i14 = int_and(i13, 255)
+ i16 = int_rshift(i13, 8)
+ i17 = int_and(i16, 255)
+ i19 = int_rshift(i16, 8)
+ i20 = int_and(i19, 255)
+
+ # struct.unpack
+ i22 = int_lshift(i14, 8)
+ i23 = int_or(i11, i22)
+ i25 = int_lshift(i17, 16)
+ i26 = int_or(i23, i25)
+ i28 = int_ge(i20, 128)
+ guard_false(i28, descr=...)
+ i30 = int_lshift(i20, 24)
+ i31 = int_or(i26, i30)
+ """)
+
+ def test_struct_object(self):
+ def main(n):
+ import struct
+ s = struct.Struct("i")
+ i = 1
+ while i < n:
+ x = s.unpack(s.pack(i))[0] # ID: struct
+ i += x / i
+ return i
+
+ log = self.run(main, [1000])
+ assert log.result == main(1000)
+
+ loop, = log.loops_by_filename(self.filepath)
+ assert loop.match_by_id('struct', """
+ guard_not_invalidated(descr=...)
+ # struct.pack
+ i8 = int_ge(i4, -2147483648)
+ guard_true(i8, descr=...)
+ i9 = int_le(i4, 2147483647)
+ guard_true(i9, descr=...)
+ i11 = int_and(i4, 255)
+ i13 = int_rshift(i4, 8)
+ i14 = int_and(i13, 255)
+ i16 = int_rshift(i13, 8)
+ i17 = int_and(i16, 255)
+ i19 = int_rshift(i16, 8)
+ i20 = int_and(i19, 255)
+
+ # struct.unpack
+ i22 = int_lshift(i14, 8)
+ i23 = int_or(i11, i22)
+ i25 = int_lshift(i17, 16)
+ i26 = int_or(i23, i25)
+ i28 = int_ge(i20, 128)
+ guard_false(i28, descr=...)
+ i30 = int_lshift(i20, 24)
+ i31 = int_or(i26, i30)
+ """)
diff --git a/pypy/module/struct/__init__.py b/pypy/module/struct/__init__.py
--- a/pypy/module/struct/__init__.py
+++ b/pypy/module/struct/__init__.py
@@ -46,6 +46,8 @@
The variable struct.error is an exception raised on errors."""
interpleveldefs = {
+ 'error': 'interp_struct.get_error(space)',
+
'calcsize': 'interp_struct.calcsize',
'pack': 'interp_struct.pack',
'pack_into': 'interp_struct.pack_into',
@@ -56,5 +58,4 @@
}
appleveldefs = {
- 'error': 'app_struct.error',
}
diff --git a/pypy/module/struct/app_struct.py b/pypy/module/struct/app_struct.py
deleted file mode 100644
--- a/pypy/module/struct/app_struct.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# NOT_RPYTHON
-"""
-Application-level definitions for the struct module.
-"""
-
-
-class error(Exception):
- """Exception raised on various occasions; argument is a string
- describing what is wrong."""
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
@@ -8,7 +8,6 @@
class PackFormatIterator(FormatIterator):
-
def __init__(self, space, args_w, size):
self.space = space
self.args_w = args_w
@@ -105,11 +104,11 @@
class UnpackFormatIterator(FormatIterator):
-
- def __init__(self, space, input):
+ def __init__(self, space, buf):
self.space = space
- self.input = input
- self.inputpos = 0
+ self.buf = buf
+ self.length = buf.getlength()
+ self.pos = 0
self.result_w = [] # list of wrapped objects
# See above comment on operate.
@@ -124,18 +123,18 @@
_operate_is_specialized_ = True
def align(self, mask):
- self.inputpos = (self.inputpos + mask) & ~mask
+ self.pos = (self.pos + mask) & ~mask
def finished(self):
- if self.inputpos != len(self.input):
+ if self.pos != self.length:
raise StructError("unpack str size too long for format")
def read(self, count):
- end = self.inputpos + count
- if end > len(self.input):
+ end = self.pos + count
+ if end > self.length:
raise StructError("unpack str size too short for format")
- s = self.input[self.inputpos : end]
- self.inputpos = end
+ s = self.buf.getslice(self.pos, end, 1, count)
+ self.pos = end
return s
@specialize.argtype(1)
diff --git a/pypy/module/struct/interp_struct.py b/pypy/module/struct/interp_struct.py
--- a/pypy/module/struct/interp_struct.py
+++ b/pypy/module/struct/interp_struct.py
@@ -1,7 +1,7 @@
from rpython.rlib import jit
+from rpython.rlib.buffer import SubBuffer
from rpython.rlib.rstruct.error import StructError, StructOverflowError
from rpython.rlib.rstruct.formatiterator import CalcSizeFormatIterator
-from rpython.tool.sourcetools import func_with_new_name
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.gateway import interp2app, unwrap_spec
@@ -12,6 +12,15 @@
)
+class Cache:
+ def __init__(self, space):
+ self.error = space.new_exception_class("struct.error", space.w_Exception)
+
+
+def get_error(space):
+ return space.fromcache(Cache).error
+
+
@unwrap_spec(format=str)
def calcsize(space, format):
return space.wrap(_calcsize(space, format))
@@ -24,9 +33,7 @@
except StructOverflowError, e:
raise OperationError(space.w_OverflowError, space.wrap(e.msg))
except StructError, e:
- w_module = space.getbuiltinmodule('struct')
- w_error = space.getattr(w_module, space.wrap('error'))
- raise OperationError(w_error, space.wrap(e.msg))
+ raise OperationError(get_error(space), space.wrap(e.msg))
return fmtiter.totalsize
@@ -42,62 +49,56 @@
except StructOverflowError, e:
raise OperationError(space.w_OverflowError, space.wrap(e.msg))
except StructError, e:
- w_module = space.getbuiltinmodule('struct')
- w_error = space.getattr(w_module, space.wrap('error'))
- raise OperationError(w_error, space.wrap(e.msg))
+ raise OperationError(get_error(space), space.wrap(e.msg))
return space.wrap(fmtiter.result.build())
# XXX inefficient
@unwrap_spec(format=str, offset=int)
-def pack_into(space, format, w_buf, offset, args_w):
+def pack_into(space, format, w_buffer, offset, args_w):
res = pack(space, format, args_w).str_w(space)
- buf = space.writebuf_w(w_buf)
+ buf = space.writebuf_w(w_buffer)
if offset < 0:
offset += buf.getlength()
size = len(res)
if offset < 0 or (buf.getlength() - offset) < size:
- w_module = space.getbuiltinmodule('struct')
- w_error = space.getattr(w_module, space.wrap('error'))
- raise oefmt(w_error,
+ raise oefmt(get_error(space),
"pack_into requires a buffer of at least %d bytes",
size)
buf.setslice(offset, res)
- at unwrap_spec(format=str, input='bufferstr')
-def unpack(space, format, input):
- fmtiter = UnpackFormatIterator(space, input)
+def _unpack(space, format, buf):
+ fmtiter = UnpackFormatIterator(space, buf)
try:
fmtiter.interpret(format)
except StructOverflowError, e:
raise OperationError(space.w_OverflowError, space.wrap(e.msg))
except StructError, e:
- w_module = space.getbuiltinmodule('struct')
- w_error = space.getattr(w_module, space.wrap('error'))
- raise OperationError(w_error, space.wrap(e.msg))
+ raise OperationError(get_error(space), space.wrap(e.msg))
return space.newtuple(fmtiter.result_w[:])
-# XXX inefficient
+ at unwrap_spec(format=str)
+def unpack(space, format, w_str):
+ buf = space.getarg_w('s*', w_str)
+ return _unpack(space, format, buf)
+
+
@unwrap_spec(format=str, offset=int)
-def unpack_from(space, format, w_buf, offset=0):
+def unpack_from(space, format, w_buffer, offset=0):
size = _calcsize(space, format)
- buf = space.getarg_w('z*', w_buf)
+ buf = space.getarg_w('z*', w_buffer)
if buf is None:
- w_module = space.getbuiltinmodule('struct')
- w_error = space.getattr(w_module, space.wrap('error'))
- raise oefmt(w_error, "unpack_from requires a buffer argument")
+ raise oefmt(get_error(space), "unpack_from requires a buffer argument")
if offset < 0:
offset += buf.getlength()
if offset < 0 or (buf.getlength() - offset) < size:
- w_module = space.getbuiltinmodule('struct')
- w_error = space.getattr(w_module, space.wrap('error'))
- raise oefmt(w_error,
+ raise oefmt(get_error(space),
"unpack_from requires a buffer of at least %d bytes",
size)
- data = buf.getslice(offset, offset + size, 1, size)
- return unpack(space, format, data)
+ buf = SubBuffer(buf, offset, size)
+ return _unpack(space, format, buf)
class W_Struct(W_Root):
@@ -113,21 +114,19 @@
W_Struct.__init__(self, space, format)
return self
- def wrap_struct_method(name):
- def impl(self, space, __args__):
- w_module = space.getbuiltinmodule('struct')
- w_method = space.getattr(w_module, space.wrap(name))
- return space.call_obj_args(
- w_method, space.wrap(self.format), __args__
- )
+ def descr_pack(self, space, args_w):
+ return pack(space, jit.promote_string(self.format), args_w)
- return func_with_new_name(impl, 'descr_' + name)
+ @unwrap_spec(offset=int)
+ def descr_pack_into(self, space, w_buffer, offset, args_w):
+ return pack_into(space, jit.promote_string(self.format), w_buffer, offset, args_w)
- descr_pack = wrap_struct_method("pack")
- descr_unpack = wrap_struct_method("unpack")
- descr_pack_into = wrap_struct_method("pack_into")
- descr_unpack_from = wrap_struct_method("unpack_from")
+ def descr_unpack(self, space, w_str):
+ return unpack(space, jit.promote_string(self.format), w_str)
+ @unwrap_spec(offset=int)
+ def descr_unpack_from(self, space, w_buffer, offset=0):
+ return unpack_from(space, jit.promote_string(self.format), w_buffer, offset)
W_Struct.typedef = TypeDef("Struct",
__new__=interp2app(W_Struct.descr__new__.im_func),
diff --git a/pypy/module/struct/test/test_struct.py b/pypy/module/struct/test/test_struct.py
--- a/pypy/module/struct/test/test_struct.py
+++ b/pypy/module/struct/test/test_struct.py
@@ -24,6 +24,10 @@
struct.error should be an exception class.
"""
assert issubclass(self.struct.error, Exception)
+ assert self.struct.error.__mro__ == (self.struct.error, Exception,
+ BaseException, object)
+ assert self.struct.error.__name__ == "error"
+ assert self.struct.error.__module__ == "struct"
def test_calcsize_standard(self):
"""
@@ -403,6 +407,11 @@
assert type(obj2) is float
assert obj2 == 42.3
+ def test_struct_object(self):
+ s = self.struct.Struct('i')
+ assert s.unpack(s.pack(42)) == (42,)
+ assert s.unpack_from(memoryview(s.pack(42))) == (42,)
+
class AppTestStructBuffer(object):
spaceconfig = dict(usemodules=['struct', '__pypy__'])
diff --git a/rpython/annotator/bookkeeper.py b/rpython/annotator/bookkeeper.py
--- a/rpython/annotator/bookkeeper.py
+++ b/rpython/annotator/bookkeeper.py
@@ -353,7 +353,7 @@
result = description.FunctionDesc(self, pyobj)
elif isinstance(pyobj, (type, types.ClassType)):
if pyobj is object:
- raise Exception, "ClassDesc for object not supported"
+ raise Exception("ClassDesc for object not supported")
if pyobj.__module__ == '__builtin__': # avoid making classdefs for builtin types
result = self.getfrozen(pyobj)
else:
@@ -591,7 +591,7 @@
for name, value in dict.iteritems():
if value is func:
return cls, name
- raise Exception, "could not match bound-method to attribute name: %r" % (boundmeth,)
+ raise Exception("could not match bound-method to attribute name: %r" % (boundmeth,))
def ishashable(x):
try:
diff --git a/rpython/annotator/builtin.py b/rpython/annotator/builtin.py
--- a/rpython/annotator/builtin.py
+++ b/rpython/annotator/builtin.py
@@ -65,14 +65,14 @@
s_start, s_stop = args[:2]
s_step = args[2]
else:
- raise Exception, "range() takes 1 to 3 arguments"
+ raise Exception("range() takes 1 to 3 arguments")
empty = False # so far
if not s_step.is_constant():
step = 0 # this case signals a variable step
else:
step = s_step.const
if step == 0:
- raise Exception, "range() with step zero"
+ raise Exception("range() with step zero")
if s_start.is_constant() and s_stop.is_constant():
try:
if len(xrange(s_start.const, s_stop.const, step)) == 0:
diff --git a/rpython/annotator/classdef.py b/rpython/annotator/classdef.py
--- a/rpython/annotator/classdef.py
+++ b/rpython/annotator/classdef.py
@@ -394,7 +394,7 @@
return SomePBC([subdef.classdesc for subdef in self.getallsubdefs()])
def _freeze_(self):
- raise Exception, "ClassDefs are used as knowntype for instances but cannot be used as immutablevalue arguments directly"
+ raise Exception("ClassDefs are used as knowntype for instances but cannot be used as immutablevalue arguments directly")
# ____________________________________________________________
diff --git a/rpython/annotator/policy.py b/rpython/annotator/policy.py
--- a/rpython/annotator/policy.py
+++ b/rpython/annotator/policy.py
@@ -30,7 +30,7 @@
except (KeyboardInterrupt, SystemExit):
raise
except:
- raise Exception, "broken specialize directive parms: %s" % directive
+ raise Exception("broken specialize directive parms: %s" % directive)
name = name.replace(':', '__')
try:
specializer = getattr(pol, name)
diff --git a/rpython/annotator/test/test_annrpython.py b/rpython/annotator/test/test_annrpython.py
--- a/rpython/annotator/test/test_annrpython.py
+++ b/rpython/annotator/test/test_annrpython.py
@@ -1435,7 +1435,7 @@
elif a==2:
raise X(1)
elif a==3:
- raise X,4
+ raise X(4)
else:
try:
l[0]
@@ -3628,7 +3628,7 @@
def f():
e = OverflowError()
lle = cast_instance_to_base_ptr(e)
- raise Exception, lle
+ raise Exception(lle)
# ^^^ instead, must cast back from a base ptr to an instance
a = self.RPythonAnnotator()
py.test.raises(AssertionError, a.build_types, f, [])
diff --git a/rpython/flowspace/flowcontext.py b/rpython/flowspace/flowcontext.py
--- a/rpython/flowspace/flowcontext.py
+++ b/rpython/flowspace/flowcontext.py
@@ -7,7 +7,6 @@
import __builtin__
from rpython.tool.error import source_lines
-from rpython.tool.stdlib_opcode import host_bytecode_spec
from rpython.rlib import rstackovf
from rpython.flowspace.argument import CallSpec
from rpython.flowspace.model import (Constant, Variable, Block, Link,
@@ -305,8 +304,6 @@
]
class FlowContext(object):
- opcode_method_names = host_bytecode_spec.method_names
-
def __init__(self, graph, code):
self.graph = graph
func = graph.func
diff --git a/rpython/rlib/buffer.py b/rpython/rlib/buffer.py
--- a/rpython/rlib/buffer.py
+++ b/rpython/rlib/buffer.py
@@ -1,7 +1,7 @@
"""
Buffer protocol support.
"""
-from rpython.rlib.objectmodel import import_from_mixin
+from rpython.rlib import jit
class Buffer(object):
@@ -61,7 +61,7 @@
if step == 1:
assert 0 <= start <= stop
return self.value[start:stop]
- return "".join([self.value[start + i*step] for i in xrange(size)])
+ return Buffer.getslice(self, start, stop, step, size)
class SubBuffer(Buffer):
diff --git a/rpython/rlib/jit.py b/rpython/rlib/jit.py
--- a/rpython/rlib/jit.py
+++ b/rpython/rlib/jit.py
@@ -593,7 +593,7 @@
def can_enter_jit(_self, **livevars):
if _self.autoreds:
- raise TypeError, "Cannot call can_enter_jit on a driver with reds='auto'"
+ raise TypeError("Cannot call can_enter_jit on a driver with reds='auto'")
# special-cased by ExtRegistryEntry
if _self.check_untranslated:
_self._check_arguments(livevars, False)
diff --git a/rpython/rlib/libffi.py b/rpython/rlib/libffi.py
--- a/rpython/rlib/libffi.py
+++ b/rpython/rlib/libffi.py
@@ -109,11 +109,11 @@
def _check_type(TYPE):
if isinstance(TYPE, lltype.Ptr):
if TYPE.TO._gckind != 'raw':
- raise TypeError, "Can only push raw values to C, not 'gc'"
+ raise TypeError("Can only push raw values to C, not 'gc'")
# XXX probably we should recursively check for struct fields here,
# lets just ignore that for now
if isinstance(TYPE.TO, lltype.Array) and 'nolength' not in TYPE.TO._hints:
- raise TypeError, "Can only push to C arrays without length info"
+ raise TypeError("Can only push to C arrays without length info")
class ArgChain(object):
@@ -136,7 +136,7 @@
elif TYPE is rffi.FLOAT:
cls = SingleFloatArg
else:
- raise TypeError, 'Unsupported argument type: %s' % TYPE
+ raise TypeError('Unsupported argument type: %s' % TYPE)
self._append(cls(val))
return self
@@ -247,8 +247,8 @@
# assuming that argchain is completely virtual.
self = jit.promote(self)
if argchain.numargs != len(self.argtypes):
- raise TypeError, 'Wrong number of arguments: %d expected, got %d' %\
- (len(self.argtypes), argchain.numargs)
+ raise TypeError('Wrong number of arguments: %d expected, got %d' %
+ (len(self.argtypes), argchain.numargs))
ll_args = self._prepare()
i = 0
arg = argchain.first
@@ -273,7 +273,7 @@
elif RESULT is lltype.Void:
return self._do_call_void(self.funcsym, ll_args)
else:
- raise TypeError, 'Unsupported result type: %s' % RESULT
+ raise TypeError('Unsupported result type: %s' % RESULT)
#
return rffi.cast(RESULT, res)
@@ -430,7 +430,7 @@
def getpointer_by_ordinal(self, name, argtypes, restype,
flags=FUNCFLAG_CDECL):
- return Func('by_ordinal', argtypes, restype,
+ return Func('by_ordinal', argtypes, restype,
dlsym_byordinal(self.lib, name),
flags=flags, keepalive=self)
def getaddressindll(self, name):
diff --git a/rpython/rlib/objectmodel.py b/rpython/rlib/objectmodel.py
--- a/rpython/rlib/objectmodel.py
+++ b/rpython/rlib/objectmodel.py
@@ -122,7 +122,7 @@
"""
typecheck = kwds.pop('typecheck', True)
if types_ and kwds:
- raise TypeError, 'Cannot mix positional arguments and keywords'
+ raise TypeError('Cannot mix positional arguments and keywords')
if not typecheck:
def decorator(f):
@@ -177,7 +177,7 @@
if not s_expected.contains(s_argtype):
msg = "%s argument %r must be of type %s" % (
f.func_name, srcargs[i], expected_type)
- raise TypeError, msg
+ raise TypeError(msg)
#
template = """
def {name}({arglist}):
@@ -576,7 +576,7 @@
# ____________________________________________________________
def hlinvoke(repr, llcallable, *args):
- raise TypeError, "hlinvoke is meant to be rtyped and not called direclty"
+ raise TypeError("hlinvoke is meant to be rtyped and not called direclty")
def invoke_around_extcall(before, after):
"""Call before() before any external function call, and after() after.
diff --git a/rpython/rlib/rarithmetic.py b/rpython/rlib/rarithmetic.py
--- a/rpython/rlib/rarithmetic.py
+++ b/rpython/rlib/rarithmetic.py
@@ -173,7 +173,7 @@
if type(r) is long and not is_valid_int(r):
# checks only if applicable to r's type.
# this happens in the garbage collector.
- raise OverflowError, "signed integer expression did overflow"
+ raise OverflowError("signed integer expression did overflow")
return r
# Strange things happening for float to int on 64 bit:
@@ -213,7 +213,7 @@
return other_type
if self_type.SIGNED == other_type.SIGNED:
return build_int(None, self_type.SIGNED, max(self_type.BITS, other_type.BITS))
- raise AssertionError, "Merging these types (%s, %s) is not supported" % (self_type, other_type)
+ raise AssertionError("Merging these types (%s, %s) is not supported" % (self_type, other_type))
def signedtype(t):
if t in (bool, int, long):
diff --git a/rpython/rlib/rsre/rpy/sre_compile.py b/rpython/rlib/rsre/rpy/sre_compile.py
--- a/rpython/rlib/rsre/rpy/sre_compile.py
+++ b/rpython/rlib/rsre/rpy/sre_compile.py
@@ -63,7 +63,7 @@
emit(OPCODES[ANY])
elif op in REPEATING_CODES:
if flags & SRE_FLAG_TEMPLATE:
- raise error, "internal: unsupported template operator"
+ raise error("internal: unsupported template operator")
emit(OPCODES[REPEAT])
skip = _len(code); emit(0)
emit(av[0])
@@ -112,7 +112,7 @@
else:
lo, hi = av[1].getwidth()
if lo != hi:
- raise error, "look-behind requires fixed-width pattern"
+ raise error("look-behind requires fixed-width pattern")
emit(lo) # look behind
_compile(code, av[1], flags)
emit(OPCODES[SUCCESS])
@@ -173,7 +173,7 @@
else:
code[skipyes] = _len(code) - skipyes + 1
else:
- raise ValueError, ("unsupported operand type", op)
+ raise ValueError("unsupported operand type", op)
def _compile_charset(charset, flags, code, fixup=None):
# compile charset subprogram
@@ -201,7 +201,7 @@
else:
emit(CHCODES[av])
else:
- raise error, "internal: unsupported set operator"
+ raise error("internal: unsupported set operator")
emit(OPCODES[FAILURE])
def _optimize_charset(charset, fixup):
diff --git a/rpython/rlib/rsre/rpy/sre_parse.py b/rpython/rlib/rsre/rpy/sre_parse.py
--- a/rpython/rlib/rsre/rpy/sre_parse.py
+++ b/rpython/rlib/rsre/rpy/sre_parse.py
@@ -75,7 +75,7 @@
if name is not None:
ogid = self.groupdict.get(name, None)
if ogid is not None:
- raise error, ("redefinition of group name %s as group %d; "
+ raise error("redefinition of group name %s as group %d; "
"was group %d" % (repr(name), gid, ogid))
self.groupdict[name] = gid
self.open.append(gid)
@@ -188,7 +188,7 @@
try:
c = self.string[self.index + 1]
except IndexError:
- raise error, "bogus escape (end of line)"
+ raise error("bogus escape (end of line)")
char = char + c
self.index = self.index + len(char)
self.next = char
@@ -238,7 +238,7 @@
escape = escape + source.get()
escape = escape[2:]
if len(escape) != 2:
- raise error, "bogus escape: %s" % repr("\\" + escape)
+ raise error("bogus escape: %s" % repr("\\" + escape))
return LITERAL, int(escape, 16) & 0xff
elif c in OCTDIGITS:
# octal escape (up to three digits)
@@ -247,12 +247,12 @@
escape = escape[1:]
return LITERAL, int(escape, 8) & 0xff
elif c in DIGITS:
- raise error, "bogus escape: %s" % repr(escape)
+ raise error("bogus escape: %s" % repr(escape))
if len(escape) == 2:
return LITERAL, ord(escape[1])
except ValueError:
pass
- raise error, "bogus escape: %s" % repr(escape)
+ raise error("bogus escape: %s" % repr(escape))
def _escape(source, escape, state):
# handle escape code in expression
@@ -289,14 +289,14 @@
group = int(escape[1:])
if group < state.groups:
if not state.checkgroup(group):
- raise error, "cannot refer to open group"
+ raise error("cannot refer to open group")
return GROUPREF, group
raise ValueError
if len(escape) == 2:
return LITERAL, ord(escape[1])
except ValueError:
pass
- raise error, "bogus escape: %s" % repr(escape)
+ raise error("bogus escape: %s" % repr(escape))
def _parse_sub(source, state, nested=1):
# parse an alternation: a|b|c
@@ -313,7 +313,7 @@
if not source.next or sourcematch(")", 0):
break
else:
- raise error, "pattern not properly closed"
+ raise error("pattern not properly closed")
if len(items) == 1:
return items[0]
@@ -362,11 +362,11 @@
if source.match("|"):
item_no = _parse(source, state)
if source.match("|"):
- raise error, "conditional backref with more than two branches"
+ raise error("conditional backref with more than two branches")
else:
item_no = None
if source.next and not source.match(")", 0):
- raise error, "pattern not properly closed"
+ raise error("pattern not properly closed")
subpattern = SubPattern(state)
subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
return subpattern
@@ -431,7 +431,7 @@
elif this:
code1 = LITERAL, ord(this)
else:
- raise error, "unexpected end of regular expression"
+ raise error("unexpected end of regular expression")
if sourcematch("-"):
# potential range
this = sourceget()
@@ -447,14 +447,14 @@
else:
code2 = LITERAL, ord(this)
if code1[0] != LITERAL or code2[0] != LITERAL:
- raise error, "bad character range"
+ raise error("bad character range")
lo = code1[1]
hi = code2[1]
if hi < lo:
- raise error, "bad character range"
+ raise error("bad character range")
setappend((RANGE, (lo, hi)))
else:
- raise error, "unexpected end of regular expression"
+ raise error("unexpected end of regular expression")
else:
if code1[0] is IN:
code1 = code1[1][0]
@@ -507,16 +507,16 @@
if max < min:
raise error("bad repeat interval")
else:
- raise error, "not supported"
+ raise error("not supported")
# figure out which item to repeat
if subpattern:
item = subpattern[-1:]
else:
item = None
if not item or (_len(item) == 1 and item[0][0] == AT):
- raise error, "nothing to repeat"
+ raise error("nothing to repeat")
if item[0][0] in REPEATCODES:
- raise error, "multiple repeat"
+ raise error("multiple repeat")
if sourcematch("?"):
subpattern[-1] = (MIN_REPEAT, (min, max, item))
else:
@@ -540,7 +540,7 @@
while 1:
char = sourceget()
if char is None:
- raise error, "unterminated name"
+ raise error("unterminated name")
if char == ">":
break
name = name + char
@@ -556,7 +556,7 @@
while 1:
char = sourceget()
if char is None:
- raise error, "unterminated name"
+ raise error("unterminated name")
if char == ")":
break
name = name + char
@@ -567,14 +567,14 @@
"%r" % name)
gid = state.groupdict.get(name)
if gid is None:
- raise error, "unknown group name"
+ raise error("unknown group name")
subpatternappend((GROUPREF, gid))
continue
else:
char = sourceget()
if char is None:
- raise error, "unexpected end of pattern"
- raise error, "unknown specifier: ?P%s" % char
+ raise error("unexpected end of pattern")
+ raise error("unknown specifier: ?P%s" % char)
elif sourcematch(":"):
# non-capturing group
group = 2
@@ -585,7 +585,7 @@
break
sourceget()
if not sourcematch(")"):
- raise error, "unbalanced parenthesis"
+ raise error("unbalanced parenthesis")
continue
elif source.next in ASSERTCHARS:
# lookahead assertions
@@ -593,12 +593,12 @@
dir = 1
if char == "<":
if source.next not in LOOKBEHINDASSERTCHARS:
- raise error, "syntax error"
+ raise error("syntax error")
dir = -1 # lookbehind
char = sourceget()
p = _parse_sub(source, state)
if not sourcematch(")"):
- raise error, "unbalanced parenthesis"
+ raise error("unbalanced parenthesis")
if char == "=":
subpatternappend((ASSERT, (dir, p)))
else:
@@ -610,7 +610,7 @@
while 1:
char = sourceget()
if char is None:
- raise error, "unterminated name"
+ raise error("unterminated name")
if char == ")":
break
condname = condname + char
@@ -620,16 +620,16 @@
if isname(condname):
condgroup = state.groupdict.get(condname)
if condgroup is None:
- raise error, "unknown group name"
+ raise error("unknown group name")
else:
try:
condgroup = int(condname)
except ValueError:
- raise error, "bad character in group name"
+ raise error("bad character in group name")
else:
# flags
if not source.next in FLAGS:
- raise error, "unexpected end of pattern"
+ raise error("unexpected end of pattern")
while source.next in FLAGS:
state.flags = state.flags | FLAGS[sourceget()]
if group:
@@ -644,7 +644,7 @@
else:
p = _parse_sub(source, state)
if not sourcematch(")"):
- raise error, "unbalanced parenthesis"
+ raise error("unbalanced parenthesis")
if group is not None:
state.closegroup(group)
subpatternappend((SUBPATTERN, (group, p)))
@@ -652,10 +652,10 @@
while 1:
char = sourceget()
if char is None:
- raise error, "unexpected end of pattern"
+ raise error("unexpected end of pattern")
if char == ")":
break
- raise error, "unknown extension"
+ raise error("unknown extension")
elif this == "^":
subpatternappend((AT, AT_BEGINNING))
@@ -668,7 +668,7 @@
subpatternappend(code)
else:
- raise error, "parser error"
+ raise error("parser error")
return subpattern
@@ -686,9 +686,9 @@
tail = source.get()
if tail == ")":
- raise error, "unbalanced parenthesis"
+ raise error("unbalanced parenthesis")
elif tail:
- raise error, "bogus characters at end of regular expression"
+ raise error("bogus characters at end of regular expression")
if flags & SRE_FLAG_DEBUG:
p.dump()
@@ -730,23 +730,23 @@
while 1:
char = sget()
if char is None:
- raise error, "unterminated group name"
+ raise error("unterminated group name")
if char == ">":
break
name = name + char
if not name:
- raise error, "missing group name"
+ raise error("missing group name")
try:
index = int(name)
if index < 0:
- raise error, "negative group number"
+ raise error("negative group number")
except ValueError:
if not isname(name):
- raise error, "bad character in group name"
+ raise error("bad character in group name")
try:
index = pattern.groupindex[name]
except KeyError:
- raise IndexError, "unknown group name"
+ raise IndexError("unknown group name")
a((MARK, index))
elif c == "0":
if s.next in OCTDIGITS:
@@ -796,7 +796,7 @@
for index, group in groups:
literals[index] = s = g(group)
if s is None:
- raise error, "unmatched group"
+ raise error("unmatched group")
except IndexError:
- raise error, "invalid group reference"
+ raise error("invalid group reference")
return sep.join(literals)
diff --git a/rpython/rlib/rstruct/formatiterator.py b/rpython/rlib/rstruct/formatiterator.py
--- a/rpython/rlib/rstruct/formatiterator.py
+++ b/rpython/rlib/rstruct/formatiterator.py
@@ -82,6 +82,7 @@
def finished(self):
pass
+
class CalcSizeFormatIterator(FormatIterator):
totalsize = 0
diff --git a/rpython/rlib/rzipfile.py b/rpython/rlib/rzipfile.py
--- a/rpython/rlib/rzipfile.py
+++ b/rpython/rlib/rzipfile.py
@@ -214,7 +214,7 @@
def _GetContents(self, fp):
endrec = _EndRecData(fp)
if not endrec:
- raise BadZipfile, "File is not a zip file"
+ raise BadZipfile("File is not a zip file")
size_cd = endrec.stuff[5] # bytes in central directory
offset_cd = endrec.stuff[6] # offset of central directory
self.comment = endrec.comment
@@ -227,7 +227,7 @@
centdir = fp.read(46)
total = total + 46
if centdir[0:4] != stringCentralDir:
- raise BadZipfile, "Bad magic number for central directory"
+ raise BadZipfile("Bad magic number for central directory")
centdir = runpack(structCentralDir, centdir)
filename = fp.read(centdir[_CD_FILENAME_LENGTH])
# Create ZipInfo instance to store file information
@@ -255,7 +255,7 @@
fp.seek(data.header_offset, 0)
fheader = fp.read(30)
if fheader[0:4] != stringFileHeader:
- raise BadZipfile, "Bad magic number for file header"
+ raise BadZipfile("Bad magic number for file header")
fheader = runpack(structFileHeader, fheader)
# file_offset is computed here, since the extra field for
# the central directory and for the local file header
@@ -266,9 +266,8 @@
+ fheader[_FH_EXTRA_FIELD_LENGTH])
fname = fp.read(fheader[_FH_FILENAME_LENGTH])
if fname != data.orig_filename:
- raise BadZipfile, \
- 'File name in directory "%s" and header "%s" differ.' % (
- data.orig_filename, fname)
+ raise BadZipfile('File name in directory "%s" and '
+ 'header "%s" differ.' % (data.orig_filename, fname))
fp.seek(self.start_dir, 0)
def getinfo(self, filename):
@@ -296,15 +295,13 @@
finally:
rzlib.inflateEnd(stream)
elif zinfo.compress_type == ZIP_DEFLATED:
- raise BadZipfile, \
- "Cannot decompress file, zlib not installed"
+ raise BadZipfile("Cannot decompress file, zlib not installed")
else:
- raise BadZipfile, \
- "Unsupported compression method %d for file %s" % \
- (zinfo.compress_type, filename)
+ raise BadZipfile("Unsupported compression method %d for "
+ "file %s" % (zinfo.compress_type, filename))
crc = crc32(bytes)
if crc != zinfo.CRC:
- raise BadZipfile, "Bad CRC-32 for file %s" % filename
+ raise BadZipfile("Bad CRC-32 for file %s" % filename)
return bytes
finally:
fp.close()
diff --git a/rpython/rlib/test/test_buffer.py b/rpython/rlib/test/test_buffer.py
--- a/rpython/rlib/test/test_buffer.py
+++ b/rpython/rlib/test/test_buffer.py
@@ -6,4 +6,5 @@
assert buf.getitem(4) == 'o'
assert buf.getlength() == 11
assert buf.getslice(1, 6, 1, 5) == 'ello '
+ assert buf.getslice(1, 6, 2, 3) == 'el '
assert buf.as_str() == 'hello world'
diff --git a/rpython/rlib/test/test_streamio.py b/rpython/rlib/test/test_streamio.py
--- a/rpython/rlib/test/test_streamio.py
+++ b/rpython/rlib/test/test_streamio.py
@@ -95,7 +95,7 @@
elif whence == 2:
offset += len(self.buf)
else:
- raise ValueError, "whence should be 0, 1 or 2"
+ raise ValueError("whence should be 0, 1 or 2")
if offset < 0:
offset = 0
self.pos = offset
diff --git a/rpython/rlib/unicodedata/unicodedb_5_2_0.py b/rpython/rlib/unicodedata/unicodedb_5_2_0.py
--- a/rpython/rlib/unicodedata/unicodedb_5_2_0.py
+++ b/rpython/rlib/unicodedata/unicodedb_5_2_0.py
@@ -39,7 +39,7 @@
charnode = left
else:
charnode = right
- raise KeyError, name
+ raise KeyError(name)
def name_of_node(charnode):
res = []
@@ -112664,7 +112664,7 @@
if code == 917505: res = 9201
if 917536 <= code <= 917631: res = _charnames_917536[code-917536]
if 917760 <= code <= 917999: res = _charnames_917760[code-917760]
- if res == -1: raise KeyError, code
+ if res == -1: raise KeyError(code)
return name_of_node(res)
# the following dictionary is used by modules that take this as a base
diff --git a/rpython/rtyper/callparse.py b/rpython/rtyper/callparse.py
--- a/rpython/rtyper/callparse.py
+++ b/rpython/rtyper/callparse.py
@@ -58,7 +58,7 @@
try:
holders = arguments.match_signature(signature, defs_h)
except ArgErr, e:
- raise TyperError, "signature mismatch: %s" % e.getmsg(graph.name)
+ raise TyperError("signature mismatch: %s" % e.getmsg(graph.name))
assert len(holders) == len(rinputs), "argument parsing mismatch"
vlist = []
diff --git a/rpython/rtyper/lltypesystem/ll2ctypes.py b/rpython/rtyper/lltypesystem/ll2ctypes.py
--- a/rpython/rtyper/lltypesystem/ll2ctypes.py
+++ b/rpython/rtyper/lltypesystem/ll2ctypes.py
@@ -257,7 +257,7 @@
@classmethod
def _malloc(cls, n=None):
if not isinstance(n, int):
- raise TypeError, "array length must be an int"
+ raise TypeError("array length must be an int")
biggercls = get_ctypes_array_of_size(A, n)
bigarray = allocate_ctypes(biggercls)
if hasattr(bigarray, 'length'):
diff --git a/rpython/rtyper/lltypesystem/lltype.py b/rpython/rtyper/lltypesystem/lltype.py
--- a/rpython/rtyper/lltypesystem/lltype.py
+++ b/rpython/rtyper/lltypesystem/lltype.py
@@ -191,7 +191,7 @@
_adtmeths = {}
def _inline_is_varsize(self, last):
- raise TypeError, "%r cannot be inlined in structure" % self
+ raise TypeError("%r cannot be inlined in structure" % self)
def _install_extras(self, adtmeths={}, hints={}):
self._adtmeths = frozendict(adtmeths)
@@ -253,7 +253,7 @@
self._arrayfld = None
for name, typ in fields:
if name.startswith('_'):
- raise NameError, ("%s: field name %r should not start with "
+ raise NameError("%s: field name %r should not start with "
"an underscore" % (self._name, name,))
names.append(name)
if name in flds:
@@ -311,8 +311,8 @@
def _nofield(self, name):
- raise AttributeError, 'struct %s has no field %r' % (self._name,
- name)
+ raise AttributeError('struct %s has no field %r' % (self._name,
+ name))
def _names_without_voids(self):
names_without_voids = [name for name in self._names if self._flds[name] is not Void]
@@ -545,7 +545,7 @@
self.ARGS = tuple(args)
assert isinstance(result, LowLevelType)
if isinstance(result, ContainerType):
- raise TypeError, "function result can only be primitive or pointer"
+ raise TypeError("function result can only be primitive or pointer")
self.RESULT = result
self.ABI = abi
@@ -602,7 +602,7 @@
return "%s (gcopaque)" % self.tag
def _inline_is_varsize(self, last):
- raise TypeError, "%r cannot be inlined in structure" % self
+ raise TypeError("%r cannot be inlined in structure" % self)
class ForwardReference(ContainerType):
@@ -714,7 +714,7 @@
_cache = WeakValueDictionary() # cache the Ptrs
def __new__(cls, TO, use_cache=True):
if not isinstance(TO, ContainerType):
- raise TypeError, ("can only point to a Container type, "
+ raise TypeError("can only point to a Container type, "
"not to %s" % (TO,))
if not use_cache:
obj = LowLevelType.__new__(cls)
@@ -835,7 +835,7 @@
def cast_primitive(TGT, value):
ORIG = typeOf(value)
if not isinstance(TGT, Primitive) or not isinstance(ORIG, Primitive):
- raise TypeError, "can only primitive to primitive"
+ raise TypeError("can only primitive to primitive")
if ORIG == TGT:
return value
if ORIG == Char or ORIG == UniChar:
@@ -855,7 +855,7 @@
return float(value)
if ORIG == LongFloat and TGT == Float:
return float(value)
- raise TypeError, "unsupported cast"
+ raise TypeError("unsupported cast")
def _cast_whatever(TGT, value):
from rpython.rtyper.lltypesystem import llmemory, rffi
@@ -932,13 +932,13 @@
def cast_pointer(PTRTYPE, ptr):
CURTYPE = typeOf(ptr)
if not isinstance(CURTYPE, Ptr) or not isinstance(PTRTYPE, Ptr):
- raise TypeError, "can only cast pointers to other pointers"
+ raise TypeError("can only cast pointers to other pointers")
return ptr._cast_to(PTRTYPE)
def cast_opaque_ptr(PTRTYPE, ptr):
CURTYPE = typeOf(ptr)
if not isinstance(CURTYPE, Ptr) or not isinstance(PTRTYPE, Ptr):
- raise TypeError, "can only cast pointers to other pointers"
+ raise TypeError("can only cast pointers to other pointers")
if CURTYPE == PTRTYPE:
return ptr
if CURTYPE.TO._gckind != PTRTYPE.TO._gckind:
@@ -989,9 +989,9 @@
"""
CURTYPE = typeOf(structptr).TO
if not isinstance(CURTYPE, Struct):
- raise TypeError, "direct_fieldptr: not a struct"
+ raise TypeError("direct_fieldptr: not a struct")
if fieldname not in CURTYPE._flds:
- raise TypeError, "%s has no field %r" % (CURTYPE, fieldname)
+ raise TypeError("%s has no field %r" % (CURTYPE, fieldname))
if not structptr:
raise RuntimeError("direct_fieldptr: NULL argument")
return _subarray._makeptr(structptr._obj, fieldname, structptr._solid)
@@ -1004,7 +1004,7 @@
"""
CURTYPE = typeOf(arrayptr).TO
if not isinstance(CURTYPE, (Array, FixedSizeArray)):
- raise TypeError, "direct_arrayitems: not an array"
+ raise TypeError("direct_arrayitems: not an array")
if not arrayptr:
raise RuntimeError("direct_arrayitems: NULL argument")
return _subarray._makeptr(arrayptr._obj, 0, arrayptr._solid)
@@ -1247,7 +1247,7 @@
from rpython.rtyper.lltypesystem import rffi
if isinstance(self._T, FuncType):
if len(args) != len(self._T.ARGS):
- raise TypeError,"calling %r with wrong argument number: %r" % (self._T, args)
+ raise TypeError("calling %r with wrong argument number: %r" % (self._T, args))
for i, a, ARG in zip(range(len(self._T.ARGS)), args, self._T.ARGS):
if typeOf(a) != ARG:
# ARG could be Void
@@ -1272,11 +1272,11 @@
pass
else:
args_repr = [typeOf(arg) for arg in args]
- raise TypeError, ("calling %r with wrong argument "
+ raise TypeError("calling %r with wrong argument "
"types: %r" % (self._T, args_repr))
callb = self._obj._callable
if callb is None:
- raise RuntimeError,"calling undefined function"
+ raise RuntimeError("calling undefined function")
return callb(*args)
raise TypeError("%r instance is not a function" % (self._T,))
@@ -1421,7 +1421,7 @@
self._set_offsets(_offsets)
def __nonzero__(self):
- raise RuntimeError, "do not test an interior pointer for nullity"
+ raise RuntimeError("do not test an interior pointer for nullity")
def _get_obj(self):
ob = self._parent
@@ -1657,9 +1657,9 @@
def __init__(self, TYPE, n, initialization=None, parent=None, parentindex=None):
if not is_valid_int(n):
- raise TypeError, "array length must be an int"
+ raise TypeError("array length must be an int")
if n < 0:
- raise ValueError, "negative array length"
+ raise ValueError("negative array length")
_parentable.__init__(self, TYPE)
myrange = self._check_range(n)
self.items = [TYPE.OF._allocate(initialization=initialization,
@@ -1977,9 +1977,9 @@
assert n is None
o = _opaque(T, initialization=initialization)
else:
- raise TypeError, "malloc: unmallocable type"
+ raise TypeError("malloc: unmallocable type")
if flavor == 'gc' and T._gckind != 'gc' and not immortal:
- raise TypeError, "gc flavor malloc of a non-GC non-immortal structure"
+ raise TypeError("gc flavor malloc of a non-GC non-immortal structure")
if flavor == "raw" and not immortal and track_allocation:
leakfinder.remember_malloc(o, framedepth=2)
solid = immortal or flavor == 'raw'
@@ -1987,10 +1987,10 @@
def free(p, flavor, track_allocation=True):
if flavor.startswith('gc'):
- raise TypeError, "gc flavor free"
+ raise TypeError("gc flavor free")
T = typeOf(p)
if not isinstance(T, Ptr) or p._togckind() != 'raw':
- raise TypeError, "free(): only for pointers to non-gc containers"
+ raise TypeError("free(): only for pointers to non-gc containers")
if track_allocation:
leakfinder.remember_free(p._obj0)
p._obj0._free()
@@ -1998,7 +1998,7 @@
def render_immortal(p, track_allocation=True):
T = typeOf(p)
if not isinstance(T, Ptr) or p._togckind() != 'raw':
- raise TypeError, "free(): only for pointers to non-gc containers"
+ raise TypeError("free(): only for pointers to non-gc containers")
if track_allocation:
leakfinder.remember_free(p._obj0)
@@ -2033,7 +2033,7 @@
def functionptr(TYPE, name, **attrs):
if not isinstance(TYPE, FuncType):
- raise TypeError, "functionptr() for FuncTypes only"
+ raise TypeError("functionptr() for FuncTypes only")
try:
hash(tuple(attrs.items()))
except TypeError:
@@ -2046,7 +2046,7 @@
def opaqueptr(TYPE, name, **attrs):
if not isinstance(TYPE, OpaqueType):
- raise TypeError, "opaqueptr() for OpaqueTypes only"
+ raise TypeError("opaqueptr() for OpaqueTypes only")
o = _opaque(TYPE, _name=name, **attrs)
return _ptr(Ptr(TYPE), o, solid=True)
@@ -2064,23 +2064,23 @@
def attachRuntimeTypeInfo(GCSTRUCT, funcptr=None, destrptr=None,
customtraceptr=None):
if not isinstance(GCSTRUCT, RttiStruct):
- raise TypeError, "expected a RttiStruct: %s" % GCSTRUCT
+ raise TypeError("expected a RttiStruct: %s" % GCSTRUCT)
GCSTRUCT._attach_runtime_type_info_funcptr(funcptr, destrptr,
customtraceptr)
return _ptr(Ptr(RuntimeTypeInfo), GCSTRUCT._runtime_type_info)
def getRuntimeTypeInfo(GCSTRUCT):
if not isinstance(GCSTRUCT, RttiStruct):
- raise TypeError, "expected a RttiStruct: %s" % GCSTRUCT
+ raise TypeError("expected a RttiStruct: %s" % GCSTRUCT)
if GCSTRUCT._runtime_type_info is None:
- raise ValueError, ("no attached runtime type info for GcStruct %s" %
+ raise ValueError("no attached runtime type info for GcStruct %s" %
GCSTRUCT._name)
return _ptr(Ptr(RuntimeTypeInfo), GCSTRUCT._runtime_type_info)
def runtime_type_info(p):
T = typeOf(p)
if not isinstance(T, Ptr) or not isinstance(T.TO, RttiStruct):
- raise TypeError, "runtime_type_info on non-RttiStruct pointer: %s" % p
+ raise TypeError("runtime_type_info on non-RttiStruct pointer: %s" % p)
struct = p._obj
top_parent = top_container(struct)
result = getRuntimeTypeInfo(top_parent._TYPE)
@@ -2090,7 +2090,7 @@
T = typeOf(query_funcptr).TO.ARGS[0]
result2 = query_funcptr(cast_pointer(T, p))
if result != result2:
- raise RuntimeError, ("runtime type-info function for %s:\n"
+ raise RuntimeError("runtime type-info function for %s:\n"
" returned: %s,\n"
"should have been: %s" % (p, result2, result))
return result
diff --git a/rpython/rtyper/rstr.py b/rpython/rtyper/rstr.py
--- a/rpython/rtyper/rstr.py
+++ b/rpython/rtyper/rstr.py
@@ -379,7 +379,7 @@
def rtype_method_replace(self, hop):
rstr = hop.args_r[0].repr
if not (hop.args_r[1] == rstr.char_repr and hop.args_r[2] == rstr.char_repr):
- raise TyperError, 'replace only works for char args'
+ raise TyperError('replace only works for char args')
v_str, v_c1, v_c2 = hop.inputargs(rstr.repr, rstr.char_repr, rstr.char_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_replace_chr_chr, v_str, v_c1, v_c2)
diff --git a/rpython/translator/backendopt/all.py b/rpython/translator/backendopt/all.py
--- a/rpython/translator/backendopt/all.py
+++ b/rpython/translator/backendopt/all.py
@@ -22,12 +22,12 @@
try:
mod = __import__(module, {}, {}, ['__doc__'])
except ImportError, e:
- raise Exception, "Import error loading %s: %s" % (dottedname, e)
+ raise Exception("Import error loading %s: %s" % (dottedname, e))
try:
func = getattr(mod, name)
except AttributeError:
- raise Exception, "Function %s not found in module" % dottedname
+ raise Exception("Function %s not found in module" % dottedname)
return func
diff --git a/rpython/translator/c/funcgen.py b/rpython/translator/c/funcgen.py
--- a/rpython/translator/c/funcgen.py
+++ b/rpython/translator/c/funcgen.py
@@ -178,7 +178,7 @@
else:
return self.db.get(value)
else:
- raise TypeError, "expr(%r)" % (v,)
+ raise TypeError("expr(%r)" % (v,))
# ____________________________________________________________
diff --git a/rpython/translator/c/node.py b/rpython/translator/c/node.py
--- a/rpython/translator/c/node.py
+++ b/rpython/translator/c/node.py
@@ -934,7 +934,7 @@
elif hasattr(fnobj._callable, "c_name"):
return []
else:
- raise ValueError, "don't know how to generate code for %r" % (fnobj,)
+ raise ValueError("don't know how to generate code for %r" % (fnobj,))
class ExtType_OpaqueNode(ContainerNode):
nodekind = 'rpyopaque'
diff --git a/rpython/translator/c/src/entrypoint.c b/rpython/translator/c/src/entrypoint.c
--- a/rpython/translator/c/src/entrypoint.c
+++ b/rpython/translator/c/src/entrypoint.c
@@ -10,6 +10,7 @@
#include <src/rtyper.h>
#include <src/exception.h>
#include <src/debug_traceback.h>
+#include <src/asm.h>
#include <stdlib.h>
#include <stdio.h>
@@ -35,9 +36,6 @@
pypy_g_rpython_rtyper_lltypesystem_rffi_StackCounter.sc_inst_stacks_counter++;
#endif
pypy_asm_stack_bottom();
-#ifdef PYPY_X86_CHECK_SSE2_DEFINED
- pypy_x86_check_sse2();
-#endif
instrument_setup();
#ifndef MS_WINDOWS
@@ -83,6 +81,9 @@
int PYPY_MAIN_FUNCTION(int argc, char *argv[])
{
+#ifdef PYPY_X86_CHECK_SSE2_DEFINED
+ pypy_x86_check_sse2();
+#endif
return pypy_main_function(argc, argv);
}
diff --git a/rpython/translator/c/test/test_extfunc.py b/rpython/translator/c/test/test_extfunc.py
--- a/rpython/translator/c/test/test_extfunc.py
+++ b/rpython/translator/c/test/test_extfunc.py
@@ -627,7 +627,7 @@
elif output.startswith('T'):
return output[1:]
else:
- raise ValueError, 'probing for env var returned %r' % (output,)
+ raise ValueError('probing for env var returned %r' % (output,))
def test_dictlike_environ_getitem():
def fn(s):
diff --git a/rpython/translator/driver.py b/rpython/translator/driver.py
--- a/rpython/translator/driver.py
+++ b/rpython/translator/driver.py
@@ -234,9 +234,9 @@
if os.WIFEXITED(status):
status = os.WEXITSTATUS(status)
if status != 0:
- raise Exception, "instrumentation child failed: %d" % status
+ raise Exception("instrumentation child failed: %d" % status)
else:
- raise Exception, "instrumentation child aborted"
+ raise Exception("instrumentation child aborted")
import array, struct
n = datafile.size()//struct.calcsize('L')
datafile = datafile.open('rb')
diff --git a/rpython/translator/gensupp.py b/rpython/translator/gensupp.py
--- a/rpython/translator/gensupp.py
+++ b/rpython/translator/gensupp.py
@@ -39,7 +39,7 @@
before generating any new names."""
for name in txt.split():
if name in self.seennames:
- raise NameError, "%s has already been seen!"
+ raise NameError("%s has already been seen!")
self.seennames[name] = 1
def _ensure_unique(self, basename):
diff --git a/rpython/translator/goal/bpnn.py b/rpython/translator/goal/bpnn.py
--- a/rpython/translator/goal/bpnn.py
+++ b/rpython/translator/goal/bpnn.py
@@ -74,7 +74,7 @@
def update(self, inputs):
if len(inputs) != self.ni-1:
- raise ValueError, 'wrong number of inputs'
+ raise ValueError('wrong number of inputs')
# input activations
for i in range(self.ni-1):
@@ -100,7 +100,7 @@
def backPropagate(self, targets, N, M):
if len(targets) != self.no:
- raise ValueError, 'wrong number of target values'
+ raise ValueError('wrong number of target values')
# calculate error terms for output
output_deltas = [0.0] * self.no
diff --git a/rpython/translator/goal/richards.py b/rpython/translator/goal/richards.py
--- a/rpython/translator/goal/richards.py
+++ b/rpython/translator/goal/richards.py
@@ -102,13 +102,13 @@
self.task_waiting = False
self.task_holding = False
return self
-
+
def waitingWithPacket(self):
self.packet_pending = True
self.task_waiting = True
self.task_holding = False
return self
-
+
def isPacketPending(self):
return self.packet_pending
@@ -144,6 +144,9 @@
class TaskWorkArea(object):
def __init__(self):
+ self.reset()
+
+ def reset(self):
self.taskTab = [None] * TASKTABSIZE
self.taskList = None
@@ -233,7 +236,7 @@
if t is None:
raise Exception("Bad task id %d" % id)
return t
-
+
# DeviceTask
@@ -307,7 +310,7 @@
else:
i.control = i.control/2 ^ 0xd008
return self.release(I_DEVB)
-
+
# WorkTask
@@ -361,8 +364,7 @@
def run(self, iterations):
for i in xrange(iterations):
- taskWorkArea.holdCount = 0
- taskWorkArea.qpktCount = 0
+ taskWorkArea.reset()
IdleTask(I_IDLE, 1, 10000, TaskState().running(), IdleTaskRec())
@@ -383,7 +385,7 @@
wkq = None;
DeviceTask(I_DEVA, 4000, wkq, TaskState().waiting(), DeviceTaskRec());
DeviceTask(I_DEVB, 5000, wkq, TaskState().waiting(), DeviceTaskRec());
-
+
schedule()
if taskWorkArea.holdCount == 9297 and taskWorkArea.qpktCount == 23246:
diff --git a/rpython/translator/platform/__init__.py b/rpython/translator/platform/__init__.py
--- a/rpython/translator/platform/__init__.py
+++ b/rpython/translator/platform/__init__.py
@@ -267,7 +267,7 @@
# Only required on armhf and mips{,el}, not armel. But there's no way to
# detect armhf without shelling out
if (platform.architecture()[0] == '64bit'
- or platform.machine().startswith(('arm', 'mips'))):
+ or platform.machine().startswith(('arm', 'mips', 'ppc'))):
host_factory = LinuxPIC
else:
host_factory = Linux
diff --git a/rpython/translator/platform/windows.py b/rpython/translator/platform/windows.py
--- a/rpython/translator/platform/windows.py
+++ b/rpython/translator/platform/windows.py
@@ -20,8 +20,8 @@
try:
subprocess.check_output([cc, '--version'])
except:
- raise ValueError,"Could not find compiler specified by cc option" + \
- " '%s', it must be a valid exe file on your path"%cc
+ raise ValueError("Could not find compiler specified by cc option '%s',"
+ " it must be a valid exe file on your path" % cc)
return MingwPlatform(cc)
def Windows(cc=None):
@@ -31,7 +31,7 @@
raise Exception("Win64 is not supported. You must either build for Win32"
" or contribute the missing support in PyPy.")
return _get_compiler_type(cc, True)
-
+
def _get_msvc_env(vsver, x64flag):
try:
toolsdir = os.environ['VS%sCOMNTOOLS' % vsver]
@@ -94,7 +94,7 @@
name = "msvc"
so_ext = 'dll'
exe_ext = 'exe'
-
+
relevant_environ = ('PATH', 'INCLUDE', 'LIB')
cc = 'cl.exe'
@@ -105,7 +105,7 @@
standalone_only = ()
shared_only = ()
environ = None
-
+
def __init__(self, cc=None, x64=False):
self.x64 = x64
msvc_compiler_environ = find_msvc_env(x64)
@@ -134,7 +134,7 @@
else:
masm32 = 'ml.exe'
masm64 = 'ml64.exe'
-
+
if x64:
self.masm = masm64
else:
@@ -338,10 +338,10 @@
definitions.append(('CREATE_PCH', '/Ycstdafx.h /Fpstdafx.pch /FIstdafx.h'))
definitions.append(('USE_PCH', '/Yustdafx.h /Fpstdafx.pch /FIstdafx.h'))
rules.append(('$(OBJECTS)', 'stdafx.pch', []))
- rules.append(('stdafx.pch', 'stdafx.h',
+ rules.append(('stdafx.pch', 'stdafx.h',
'$(CC) stdafx.c /c /nologo $(CFLAGS) $(CFLAGSEXTRA) '
'$(CREATE_PCH) $(INCLUDEDIRS)'))
- rules.append(('.c.obj', '',
+ rules.append(('.c.obj', '',
'$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) $(USE_PCH) '
'/Fo$@ /c $< $(INCLUDEDIRS)'))
#Do not use precompiled headers for some files
@@ -361,7 +361,7 @@
'/Fo%s /c %s $(INCLUDEDIRS)' %(target, f)))
else:
- rules.append(('.c.obj', '',
+ rules.append(('.c.obj', '',
'$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) '
'/Fo$@ /c $< $(INCLUDEDIRS)'))
@@ -371,7 +371,7 @@
for rule in rules:
m.rule(*rule)
-
+
if self.version < 80:
m.rule('$(TARGET)', '$(OBJECTS)',
[ '$(CC_LINK) /nologo $(LDFLAGS) $(LDFLAGSEXTRA) /out:$@' +\
diff --git a/rpython/translator/translator.py b/rpython/translator/translator.py
--- a/rpython/translator/translator.py
+++ b/rpython/translator/translator.py
@@ -116,7 +116,7 @@
print >>f, " ",op
print >>f, '--end--'
return
- raise TypeError, "don't know about %r" % x
+ raise TypeError("don't know about %r" % x)
def view(self):
More information about the pypy-commit
mailing list