Commits

Laurence Tratt committed d8a0476 Merge

Merge heads.

Comments (0)

Files changed (19)

lib-python/2.7/uuid.py

         overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
         """
 
-        if [hex, bytes, bytes_le, fields, int].count(None) != 4:
-            raise TypeError('need one of hex, bytes, bytes_le, fields, or int')
+        if (
+            ((hex is not None) + (bytes is not None) + (bytes_le is not None) +
+             (fields is not None) + (int is not None)) != 1
+        ):
+            raise TypeError('need exactly one of hex, bytes, bytes_le, fields,'
+                            ' or int')
         if hex is not None:
             hex = hex.replace('urn:', '').replace('uuid:', '')
             hex = hex.strip('{}').replace('-', '')

pypy/doc/tool/makecontributor.py

     'Roberto De Ioris': ['roberto@mrspurr'],
     'Sven Hager': ['hager'],
     'Tomo Cocoa': ['cocoatomo'],
+    'Romain Guillebert': ['rguillebert', 'rguillbert', 'romain', 'Guillebert Romain'],
+    'Ronan Lamy': ['ronan'],
+    'Edd Barrett': ['edd'],
+    'Manuel Jacob': ['mjacob'],
+    'Rami Chowdhury': ['necaris'],
     }
 
 alias_map = {}
     if not match:
         return set()
     ignore_words = ['around', 'consulting', 'yesterday', 'for a bit', 'thanks',
-                    'in-progress', 'bits of', 'even a little', 'floating',]
+                    'in-progress', 'bits of', 'even a little', 'floating',
+                    'a bit', 'reviewing']
     sep_words = ['and', ';', '+', '/', 'with special  by']
     nicknames = match.group(1)
     for word in ignore_words:
     ##         print '%5d %s' % (n, name)
     ##     else:
     ##         print name
-                
+
     items = authors_count.items()
     items.sort(key=operator.itemgetter(1), reverse=True)
     for name, n in items:

pypy/doc/whatsnew-head.rst

 .. branch: reflex-support
 .. branch: numpypy-inplace-op
 .. branch: rewritten-loop-logging
+
+.. branch: nobold-backtrace
+Work on improving UnionError messages and stack trace displays.
+
+.. branch: improve-errors-again
+More improvements and refactorings of error messages.
+
+.. branch: improve-errors-again2
+Unbreak tests in rlib.

pypy/module/micronumpy/loop.py

 
 reduce_driver = jit.JitDriver(name='numpy_reduce',
                               greens = ['shapelen', 'func', 'done_func',
-                                        'calc_dtype', 'identity'],
+                                        'calc_dtype'],
                               reds = 'auto')
 
 def compute_reduce(obj, calc_dtype, func, done_func, identity):
     while not obj_iter.done():
         reduce_driver.jit_merge_point(shapelen=shapelen, func=func,
                                       done_func=done_func,
-                                      calc_dtype=calc_dtype, identity=identity,
+                                      calc_dtype=calc_dtype,
                                       )
         rval = obj_iter.getitem().convert_to(calc_dtype)
         if done_func is not None and done_func(calc_dtype, rval):

pypy/module/micronumpy/test/test_zjit.py

             elif isinstance(w_res, interp_boxes.W_BoolBox):
                 return float(w_res.value)
             raise TypeError(w_res)
-
+      
         if self.graph is None:
             interp, graph = self.meta_interp(f, [0],
                                              listops=True,
                                 'int_add': 3,
                                 })
 
+    def define_reduce():
+        return """
+        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+        sum(a)
+        """
+
     def test_reduce_compile_only_once(self):
         self.compile_graph()
         reset_stats()
         pyjitpl._warmrunnerdesc.memory_manager.alive_loops.clear()
-        i = self.code_mapping['sum']
+        i = self.code_mapping['reduce']
         # run it twice
         retval = self.interp.eval_graph(self.graph, [i])
         retval = self.interp.eval_graph(self.graph, [i])

pypy/module/pypyjit/test_pypy_c/test_containers.py

         loop, = log.loops_by_filename(self.filepath)
         ops = loop.ops_by_id('getitem', include_guard_not_invalidated=False)
         assert log.opnames(ops) == []
-
-    def test_list_count_virtual_list(self):
-        def main(n):
-            i = 0
-            while i < n:
-                i += [n].count(n)
-            return i
-
-        log = self.run(main, [1000])
-        assert log.result == main(1000)
-        loop, = log.loops_by_filename(self.filepath)
-        assert loop.match("""
-            i7 = int_lt(i5, i6)
-            guard_true(i7, descr=...)
-            i9 = int_add(i5, 1)
-            guard_not_invalidated(descr=...)
-            --TICK--
-            jump(..., descr=...)
-        """)

pypy/objspace/std/dictmultiobject.py

     def get_empty_storage(self):
         raise NotImplementedError
 
+    @jit.look_inside_iff(lambda self, w_dict:
+                         w_dict_unrolling_heuristic(w_dict))
     def w_keys(self, w_dict):
         iterator = self.iterkeys(w_dict)
         result = newlist_hint(self.length(w_dict))

pypy/objspace/std/kwargsdict.py

     def _never_equal_to(self, w_lookup_type):
         return False
 
-    def w_keys(self, w_dict):
-        return self.space.newlist([self.space.wrap(key) for key in self.unerase(w_dict.dstorage)[0]])
-
     def setitem(self, w_dict, w_key, w_value):
         if self.is_correct_type(w_key):
             self.setitem_str(w_dict, self.unwrap(w_key), w_value)
             jit.isconstant(self.length(w_dict)) and jit.isconstant(key))
     def _setitem_str_indirection(self, w_dict, key, w_value):
         keys, values_w = self.unerase(w_dict.dstorage)
-        result = []
         for i in range(len(keys)):
             if keys[i] == key:
                 values_w[i] = w_value
                 values_w.append(w_value)
 
     def setdefault(self, w_dict, w_key, w_default):
-        space = self.space
         if self.is_correct_type(w_key):
             key = self.unwrap(w_key)
             w_result = self.getitem_str(w_dict, key)
             jit.isconstant(self.length(w_dict)) and jit.isconstant(key))
     def _getitem_str_indirection(self, w_dict, key):
         keys, values_w = self.unerase(w_dict.dstorage)
-        result = []
         for i in range(len(keys)):
             if keys[i] == key:
                 return values_w[i]
 
     def getiterkeys(self, w_dict):
         return iter(self.unerase(w_dict.dstorage)[0])
+
     def getitervalues(self, w_dict):
         return iter(self.unerase(w_dict.dstorage)[1])
+
     def getiteritems(self, w_dict):
         keys = self.unerase(w_dict.dstorage)[0]
         return iter(range(len(keys)))
+
     def wrapkey(space, key):
         return space.wrap(key)
 
+
 def next_item(self):
     strategy = self.strategy
     assert isinstance(strategy, KwargsDictStrategy)

pypy/objspace/std/listobject.py

         'L.reverse() -- reverse *IN PLACE*'
         self.reverse()
 
-    @jit.look_inside_iff(lambda self, space, w_value:
-            jit.loop_unrolling_heuristic(self, self.length(), UNROLL_CUTOFF))
     def descr_count(self, space, w_value):
         '''L.count(value) -> integer -- return number of
         occurrences of value'''

pypy/objspace/std/stringobject.py

 
     return space.wrap(builder.build())
 
-def str_title__String(space, w_self):
-    input = w_self._value
-    builder = StringBuilder(len(input))
+
+@jit.elidable
+def title(s):
+    builder = StringBuilder(len(s))
     prev_letter = ' '
 
-    for pos in range(len(input)):
-        ch = input[pos]
+    for ch in s:
         if not prev_letter.isalpha():
             ch = _upper(ch)
             builder.append(ch)
             builder.append(ch)
 
         prev_letter = ch
+    return builder.build()
 
-    return space.wrap(builder.build())
+
+def str_title__String(space, w_self):
+    return space.wrap(title(w_self._value))
+
 
 def str_split__String_None_ANY(space, w_self, w_none, w_maxsplit=-1):
     maxsplit = space.int_w(w_maxsplit)
-    res = []
     value = w_self._value
-    length = len(value)
-    i = 0
-    while True:
-        # find the beginning of the next word
-        while i < length:
-            if not value[i].isspace():
-                break   # found
-            i += 1
-        else:
-            break  # end of string, finished
-
-        # find the end of the word
-        if maxsplit == 0:
-            j = length   # take all the rest of the string
-        else:
-            j = i + 1
-            while j < length and not value[j].isspace():
-                j += 1
-            maxsplit -= 1   # NB. if it's already < 0, it stays < 0
-
-        # the word is value[i:j]
-        res.append(value[i:j])
-
-        # continue to look from the character following the space after the word
-        i = j + 1
-
+    res = split(value, maxsplit=maxsplit)
     return space.newlist_str(res)
 
 def str_split__String_String_ANY(space, w_self, w_by, w_maxsplit=-1):
 
 def str_rsplit__String_None_ANY(space, w_self, w_none, w_maxsplit=-1):
     maxsplit = space.int_w(w_maxsplit)
-    res = []
     value = w_self._value
-    i = len(value)-1
-    while True:
-        # starting from the end, find the end of the next word
-        while i >= 0:
-            if not value[i].isspace():
-                break   # found
-            i -= 1
-        else:
-            break  # end of string, finished
-
-        # find the start of the word
-        # (more precisely, 'j' will be the space character before the word)
-        if maxsplit == 0:
-            j = -1   # take all the rest of the string
-        else:
-            j = i - 1
-            while j >= 0 and not value[j].isspace():
-                j -= 1
-            maxsplit -= 1   # NB. if it's already < 0, it stays < 0
-
-        # the word is value[j+1:i+1]
-        j1 = j + 1
-        assert j1 >= 0
-        res.append(value[j1:i+1])
-
-        # continue to look from the character before the space before the word
-        i = j - 1
-
-    res.reverse()
+    res = rsplit(value, maxsplit=maxsplit)
     return space.newlist_str(res)
 
 def str_rsplit__String_String_ANY(space, w_self, w_by, w_maxsplit=-1):

pypy/tool/pytest/apptest.py

         try:
             target(*args)
         except OperationError, e:
+            if self.config.option.verbose:
+                raise
             tb = sys.exc_info()[2]
             if e.match(space, space.w_KeyboardInterrupt):
                 raise KeyboardInterrupt, KeyboardInterrupt(), tb

rpython/annotator/binaryop.py

                 if pbc.isNone():
                     return %(classname)s(%(constructor_args)s)
                 else:
-                    return SomeObject()
+                    raise UnionError(pbc, obj)
 
         class __extend__(pairtype(SomePBC, %(classname)s)):
             def union((pbc, obj)):
                 if pbc.isNone():
                     return %(classname)s(%(constructor_args)s)
                 else:
-                    return SomeObject()
+                    raise UnionError(pbc, obj)
     """ % loc)
     exec source.compile() in glob
 

rpython/annotator/listdef.py

 from rpython.annotator.model import s_ImpossibleValue
 from rpython.annotator.model import SomeList, SomeString
-from rpython.annotator.model import unionof, TLS, UnionError
+from rpython.annotator.model import unionof, TLS, UnionError, AnnotatorError
 
 
-class TooLateForChange(Exception):
+class TooLateForChange(AnnotatorError):
     pass
 
-class ListChangeUnallowed(Exception):
+class ListChangeUnallowed(AnnotatorError):
     pass
 
 class ListItem(object):

rpython/annotator/signature.py

 from rpython.annotator.model import SomeBool, SomeInteger, SomeString,\
      SomeFloat, SomeList, SomeDict, s_None, \
      SomeObject, SomeInstance, SomeTuple, lltype_to_annotation,\
-     unionof, SomeUnicodeString, SomeType
+     unionof, SomeUnicodeString, SomeType, AnnotatorError
 from rpython.annotator.listdef import ListDef
 from rpython.annotator.dictdef import DictDef
 
             else:
                 args_s.append(annotation(argtype, bookkeeper=funcdesc.bookkeeper))
         if len(inputcells) != len(args_s):
-            raise Exception("%r: expected %d args, got %d" % (funcdesc,
+            raise SignatureError("%r: expected %d args, got %d" % (funcdesc,
                                                               len(args_s),
                                                               len(inputcells)))
         for i, (s_arg, s_input) in enumerate(zip(args_s, inputcells)):
             s_input = unionof(s_input, s_arg)
             if not s_arg.contains(s_input):
-                raise Exception("%r argument %d:\n"
+                raise SignatureError("%r argument %d:\n"
                                 "expected %s,\n"
                                 "     got %s" % (funcdesc, i+1,
                                              s_arg,
                                              s_input))
         inputcells[:] = args_s
 
+class SignatureError(AnnotatorError):
+    pass
+
 def finish_type(paramtype, bookkeeper, func):
     from rpython.rlib.types import SelfTypeMarker, AnyTypeMarker
     if isinstance(paramtype, SomeObject):
         return paramtype
     elif isinstance(paramtype, SelfTypeMarker):
-        raise Exception("%r argument declared as annotation.types.self(); class needs decorator rlib.signature.finishsigs()" % (func,))
+        raise SignatureError("%r argument declared as annotation.types.self(); class needs decorator rlib.signature.finishsigs()" % (func,))
     elif isinstance(paramtype, AnyTypeMarker):
         return None
     else:
         if s_param is None: # can be anything
             continue
         if not s_param.contains(s_actual):
-            raise Exception("%r argument %d:\n"
+            raise SignatureError("%r argument %d:\n"
                             "expected %s,\n"
                             "     got %s" % (funcdesc, i+1, s_param, s_actual))
     for i, s_param in enumerate(params_s):
 def enforce_signature_return(funcdesc, sigtype, inferredtype):
     s_sigret = finish_type(sigtype, funcdesc.bookkeeper, funcdesc.pyobj)
     if s_sigret is not None and not s_sigret.contains(inferredtype):
-        raise Exception("%r return value:\n"
+        raise SignatureError("%r return value:\n"
                         "expected %s,\n"
                         "     got %s" % (funcdesc, s_sigret, inferredtype))
     return s_sigret

rpython/annotator/specialize.py

             assert not s.can_be_None, "memo call: cannot mix None and PBCs"
             for desc in s.descriptions:
                 if desc.pyobj is None:
-                    raise Exception("memo call with a class or PBC that has no "
-                                   "corresponding Python object (%r)" % (desc,))
+                    raise annmodel.AnnotatorError(
+                        "memo call with a class or PBC that has no "
+                        "corresponding Python object (%r)" % (desc,))
                 values.append(desc.pyobj)
         elif isinstance(s, SomeImpossibleValue):
             return s    # we will probably get more possible args later
         elif isinstance(s, SomeBool):
             values = [False, True]
         else:
-            raise Exception("memo call: argument must be a class or a frozen "
-                            "PBC, got %r" % (s,))
+            raise annmodel.AnnotatorError("memo call: argument must be a class"
+                                          "or a frozen PBC, got %r" % (s,))
         argvalues.append(values)
     # the list of all possible tuples of arguments to give to the memo function
     possiblevalues = cartesian_product(argvalues)
     except KeyError:
         func = funcdesc.pyobj
         if func is None:
-            raise Exception("memo call: no Python function object to call "
-                            "(%r)" % (funcdesc,))
+            raise annmodel.AnnotatorError("memo call: no Python function object"
+                                          "to call (%r)" % (funcdesc,))
 
         def compute_one_result(args):
             value = func(*args)
             desc, = s.descriptions
             key.append(desc)
         else:
-            raise Exception("specialize:arg(%d): argument not constant: %r"
-                            % (i, s))
+            raise annmodel.AnnotatorError("specialize:arg(%d): argument not "
+                                          "constant: %r" % (i, s))
     key = tuple(key)
     return maybe_star_args(funcdesc, key, args_s)
 

rpython/rlib/rstring.py

 # -------------- public API for string functions -----------------------
 
 @specialize.argtype(0)
-def split(value, by, maxsplit=-1):
+def split(value, by=None, maxsplit=-1):
+    if by is None:
+        length = len(value)
+        i = 0
+        res = []
+        while True:
+            # find the beginning of the next word
+            while i < length:
+                if not value[i].isspace():
+                    break   # found
+                i += 1
+            else:
+                break  # end of string, finished
+
+            # find the end of the word
+            if maxsplit == 0:
+                j = length   # take all the rest of the string
+            else:
+                j = i + 1
+                while j < length and not value[j].isspace():
+                    j += 1
+                maxsplit -= 1   # NB. if it's already < 0, it stays < 0
+
+            # the word is value[i:j]
+            res.append(value[i:j])
+
+            # continue to look from the character following the space after the word
+            i = j + 1
+        return res
+
     if isinstance(value, str):
         assert isinstance(by, str)
     else:
 
 
 @specialize.argtype(0)
-def rsplit(value, by, maxsplit=-1):
+def rsplit(value, by=None, maxsplit=-1):
+    if by is None:
+        res = []
+
+        i = len(value) - 1
+        while True:
+            # starting from the end, find the end of the next word
+            while i >= 0:
+                if not value[i].isspace():
+                    break   # found
+                i -= 1
+            else:
+                break  # end of string, finished
+
+            # find the start of the word
+            # (more precisely, 'j' will be the space character before the word)
+            if maxsplit == 0:
+                j = -1   # take all the rest of the string
+            else:
+                j = i - 1
+                while j >= 0 and not value[j].isspace():
+                    j -= 1
+                maxsplit -= 1   # NB. if it's already < 0, it stays < 0
+
+            # the word is value[j+1:i+1]
+            j1 = j + 1
+            assert j1 >= 0
+            res.append(value[j1:i+1])
+
+            # continue to look from the character before the space before the word
+            i = j - 1
+
+        res.reverse()
+        return res
+
     if isinstance(value, str):
         assert isinstance(by, str)
     else:

rpython/rlib/test/test_rstring.py

     assert split('endcase test', 'test') == ['endcase ', '']
     py.test.raises(ValueError, split, 'abc', '')
 
+def test_split_None():
+    assert split("") == []
+    assert split(' a\ta\na b') == ['a', 'a', 'a', 'b']
+    assert split(" a a ", maxsplit=1) == ['a', 'a ']
+
 def test_split_unicode():
     assert split(u"", u'x') == [u'']
     assert split(u"a", u"a", 1) == [u'', u'']
     assert rsplit('endcase test', 'test') == ['endcase ', '']
     py.test.raises(ValueError, rsplit, "abc", '')
 
+def test_rsplit_None():
+    assert rsplit("") == []
+    assert rsplit(' a\ta\na b') == ['a', 'a', 'a', 'b']
+    assert rsplit(" a a ", maxsplit=1) == [' a', 'a']
+
 def test_rsplit_unicode():
     assert rsplit(u"a", u"a", 1) == [u'', u'']
     assert rsplit(u" ", u" ", 1) == [u'', u'']
         def fn():
             res = True
             res = res and split('a//b//c//d', '//') == ['a', 'b', 'c', 'd']
+            res = res and split(' a\ta\na b') == ['a', 'a', 'a', 'b']
             res = res and split('a//b//c//d', '//', 2) == ['a', 'b', 'c//d']
             res = res and split(u'a//b//c//d', u'//') == [u'a', u'b', u'c', u'd']
             res = res and split(u'endcase test', u'test') == [u'endcase ', u'']

rpython/rlib/test/test_signature.py

 from rpython.rlib.signature import signature, finishsigs, FieldSpec, ClassSpec
 from rpython.rlib import types
 from rpython.annotator import model
+from rpython.annotator.signature import SignatureError
 from rpython.translator.translator import TranslationContext, graphof
 from rpython.rtyper.lltypesystem import rstr
 from rpython.rtyper.annlowlevel import LowLevelAnnotatorPolicy
     return sigof(a, f)
 
 def check_annotator_fails(caller):
-    exc = py.test.raises(Exception, annotate_at, caller).value
-    assert caller.func_name in repr(exc.args)
+    exc = py.test.raises(model.AnnotatorError, annotate_at, caller).value
+    assert caller.func_name in str(exc)
 
 
 def test_bookkeeping():
         def incomplete_sig_meth(self):
             pass
 
-    exc = py.test.raises(Exception, annotate_at, C.incomplete_sig_meth).value
-    assert 'incomplete_sig_meth' in repr(exc.args)
-    assert 'finishsigs' in repr(exc.args)
+    exc = py.test.raises(SignatureError, annotate_at, C.incomplete_sig_meth).value
+    assert 'incomplete_sig_meth' in str(exc)
+    assert 'finishsigs' in str(exc)
 
 def test_any_as_argument():
     @signature(types.any(), types.int(), returns=types.float())
     @signature(types.str(), returns=types.int())
     def cannot_add_string(x):
         return f(x, 2)
-    exc = py.test.raises(Exception, annotate_at, cannot_add_string).value
-    assert 'Blocked block' in repr(exc.args)
+    exc = py.test.raises(model.AnnotatorError, annotate_at, cannot_add_string).value
+    assert 'Blocked block' in str(exc)
 
 def test_return_any():
     @signature(types.int(), returns=types.any())
     @signature(types.str(), returns=types.any())
     def cannot_add_string(x):
         return f(3) + x
-    exc = py.test.raises(Exception, annotate_at, cannot_add_string).value
-    assert 'Blocked block' in repr(exc.args)
-    assert 'cannot_add_string' in repr(exc.args)
+    exc = py.test.raises(model.AnnotatorError, annotate_at, cannot_add_string).value
+    assert 'Blocked block' in str(exc)
+    assert 'cannot_add_string' in str(exc)
 
 
 

rpython/tool/test/test_error.py

 
 import py
 
+def compile_function(function, annotation=[]):
+    t = TranslationContext()
+    t.buildannotator().build_types(function, annotation)
+
+class AAA(object):
+    pass
+
 def test_someobject():
     def someobject_degeneration(n):
         if n == 3: