Author: Ronan Lamy <[email protected]>
Branch:
Changeset: r80185:d3bde7757257
Date: 2015-10-14 00:31 +0100
http://bitbucket.org/pypy/pypy/changeset/d3bde7757257/
Log: Merged raises(Exception)-must-die into default
diff --git a/rpython/annotator/bookkeeper.py b/rpython/annotator/bookkeeper.py
--- a/rpython/annotator/bookkeeper.py
+++ b/rpython/annotator/bookkeeper.py
@@ -8,12 +8,12 @@
from contextlib import contextmanager
from rpython.flowspace.model import Constant
-from rpython.annotator.model import (SomeOrderedDict,
- SomeString, SomeChar, SomeFloat, unionof, SomeInstance, SomeDict,
- SomeBuiltin, SomePBC, SomeInteger, TLS, SomeUnicodeCodePoint,
+from rpython.annotator.model import (
+ SomeOrderedDict, SomeString, SomeChar, SomeFloat, unionof, SomeInstance,
+ SomeDict, SomeBuiltin, SomePBC, SomeInteger, TLS, SomeUnicodeCodePoint,
s_None, s_ImpossibleValue, SomeBool, SomeTuple,
SomeImpossibleValue, SomeUnicodeString, SomeList, HarmlesslyBlocked,
- SomeWeakRef, SomeByteArray, SomeConstantType, SomeProperty)
+ SomeWeakRef, SomeByteArray, SomeConstantType, SomeProperty, AnnotatorError)
from rpython.annotator.classdef import InstanceSource, ClassDef
from rpython.annotator.listdef import ListDef, ListItem
from rpython.annotator.dictdef import DictDef
@@ -225,7 +225,8 @@
x = int(x)
result = SomeInteger(nonneg = x>=0)
else:
- raise Exception("seeing a prebuilt long (value %s)" % hex(x))
+ # XXX: better error reporting?
+ raise ValueError("seeing a prebuilt long (value %s)" % hex(x))
elif issubclass(tp, str): # py.lib uses annotated str subclasses
no_nul = not '\x00' in x
if len(x) == 1:
diff --git a/rpython/annotator/classdef.py b/rpython/annotator/classdef.py
--- a/rpython/annotator/classdef.py
+++ b/rpython/annotator/classdef.py
@@ -112,14 +112,10 @@
for desc in s_newvalue.descriptions:
if desc.selfclassdef is None:
if homedef.classdesc.settled:
- raise Exception("demoting method %s "
- "to settled class %s not "
- "allowed" %
- (self.name, homedef)
- )
- #self.bookkeeper.warning("demoting method %s "
- # "to base class %s" %
- # (self.name, homedef))
+ raise AnnotatorError(
+ "demoting method %s to settled class "
+ "%s not allowed" % (self.name, homedef)
+ )
break
# check for attributes forbidden by slots or _attrs_
diff --git a/rpython/annotator/description.py b/rpython/annotator/description.py
--- a/rpython/annotator/description.py
+++ b/rpython/annotator/description.py
@@ -801,8 +801,9 @@
s_init = basedesc.s_read_attribute('__init__')
parent_has_init = isinstance(s_init, SomePBC)
if has_init and not parent_has_init:
- raise Exception("some subclasses among %r declare __init__(),"
- " but not the common parent class" % (descs,))
+ raise AnnotatorError(
+ "some subclasses among %r declare __init__(),"
+ " but not the common parent class" % (descs,))
# make a PBC of MethodDescs, one for the __init__ of each class
initdescs = []
for desc, classdef in zip(descs, classdefs):
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
@@ -4,10 +4,12 @@
from rpython.conftest import option
from rpython.annotator import model as annmodel
+from rpython.annotator.model import AnnotatorError, UnionError
from rpython.annotator.annrpython import RPythonAnnotator as _RPythonAnnotator
+from rpython.annotator.classdef import NoSuchAttrError
from rpython.translator.translator import graphof as tgraphof
from rpython.annotator.policy import AnnotatorPolicy
-from rpython.annotator.signature import Sig
+from rpython.annotator.signature import Sig, SignatureError
from rpython.annotator.listdef import ListDef, ListChangeUnallowed
from rpython.annotator.dictdef import DictDef
from rpython.flowspace.model import *
@@ -213,7 +215,7 @@
def f():
return X().meth()
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, a.build_types, f, [])
+ py.test.raises(AnnotatorError, a.build_types, f, [])
def test_methodcall1(self):
a = self.RPythonAnnotator()
@@ -360,7 +362,7 @@
def f(l):
return g(*l)
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.AnnotatorError):
+ with py.test.raises(AnnotatorError):
a.build_types(f, [[int]])
def test_star_unpack_and_keywords(self):
@@ -769,7 +771,8 @@
def f():
return x
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
- py.test.raises(Exception, a.build_types, f, [])
+ with py.test.raises(Exception):
+ a.build_types(f, [])
def test_exception_deduction_with_raise1(self):
a = self.RPythonAnnotator()
@@ -959,14 +962,16 @@
def f():
return large_constant
a = self.RPythonAnnotator()
- py.test.raises(Exception, a.build_types, f, [])
+ with py.test.raises(ValueError):
+ a.build_types(f, [])
# if you want to get a r_uint, you have to be explicit about it
def test_add_different_ints(self):
def f(a, b):
return a + b
a = self.RPythonAnnotator()
- py.test.raises(Exception, a.build_types, f, [r_uint, int])
+ with py.test.raises(UnionError):
+ a.build_types(f, [r_uint, int])
def test_merge_different_ints(self):
def f(a, b):
@@ -976,7 +981,8 @@
c = b
return c
a = self.RPythonAnnotator()
- py.test.raises(Exception, a.build_types, f, [r_uint, int])
+ with py.test.raises(UnionError):
+ a.build_types(f, [r_uint, int])
def test_merge_ruint_zero(self):
def f(a):
@@ -2612,14 +2618,14 @@
def f():
return A()
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, a.build_types, f, [])
+ py.test.raises(AnnotatorError, a.build_types, f, [])
#
class B(object):
pass
x = B()
def g():
return isinstance(x, A)
- py.test.raises(annmodel.AnnotatorError, a.build_types, g, [])
+ py.test.raises(AnnotatorError, a.build_types, g, [])
def test_import_from_mixin(self):
class M(object):
@@ -2694,7 +2700,8 @@
return a.x # should explode here
a = self.RPythonAnnotator()
- e = py.test.raises(Exception, a.build_types, f, [int])
+ with py.test.raises(NoSuchAttrError) as excinfo:
+ a.build_types(f, [int])
# this should explode on reading the attribute 'a.x', but it can
# sometimes explode on 'self.x = x', which does not make much sense.
# But it looks hard to fix in general: we don't know yet during 'a.x'
@@ -2928,7 +2935,8 @@
s = a.build_types(fun, [s_nonneg, s_nonneg])
assert isinstance(s, annmodel.SomeInteger)
assert not s.nonneg
- py.test.raises(Exception, a.build_types, fun, [int, int])
+ with py.test.raises(SignatureError):
+ a.build_types(fun, [int, int])
def test_sig_simpler(self):
def fun(x, y):
@@ -2940,7 +2948,8 @@
s = a.build_types(fun, [s_nonneg, s_nonneg])
assert isinstance(s, annmodel.SomeInteger)
assert not s.nonneg
- py.test.raises(Exception, a.build_types, fun, [int, int])
+ with py.test.raises(SignatureError):
+ a.build_types(fun, [int, int])
def test_sig_lambda(self):
def fun(x, y):
@@ -2954,7 +2963,8 @@
s = a.build_types(fun, [int, s_nonneg])
assert isinstance(s, annmodel.SomeInteger)
assert not s.nonneg
- py.test.raises(Exception, a.build_types, fun, [s_nonneg, int])
+ with py.test.raises(SignatureError):
+ a.build_types(fun, [s_nonneg, int])
def test_sig_bug(self):
def g(x, y=5):
@@ -3004,8 +3014,8 @@
if works:
a.build_types(fun, [int])
else:
- from rpython.annotator.classdef import NoSuchAttrError
- py.test.raises(NoSuchAttrError, a.build_types, fun, [int])
+ with py.test.raises(NoSuchAttrError):
+ a.build_types(fun, [int])
def test_slots_enforce_attrs(self):
class Superbase(object):
@@ -3138,7 +3148,8 @@
return a.n()
a = self.RPythonAnnotator()
- py.test.raises(Exception, a.build_types, fun, [bool])
+ with py.test.raises(AnnotatorError):
+ a.build_types(fun, [bool])
def test_float_cmp(self):
def fun(x, y):
@@ -3227,6 +3238,7 @@
assert isinstance(s.items[2], annmodel.SomeInstance)
assert s.items[2].flags == {}
+ @py.test.mark.xfail
def test_no_access_directly_on_heap(self):
from rpython.rlib.jit import hint
@@ -3243,7 +3255,8 @@
i.x = x
a = self.RPythonAnnotator()
- py.test.raises(Exception, a.build_types, f, [])
+ with py.test.raises(AnnotatorError):
+ a.build_types(f, [])
class M:
@@ -3267,7 +3280,7 @@
c.m.l.append(x)
a = self.RPythonAnnotator()
- py.test.raises(AssertionError, a.build_types, f, [])
+ py.test.raises(AnnotatorError, a.build_types, f, [])
def f():
x = A()
@@ -3275,7 +3288,7 @@
c.m.d[None] = x
a = self.RPythonAnnotator()
- py.test.raises(AssertionError, a.build_types, f, [])
+ py.test.raises(AnnotatorError, a.build_types, f, [])
def f():
x = A()
@@ -3283,7 +3296,7 @@
c.m.d[x] = None
a = self.RPythonAnnotator()
- py.test.raises(AssertionError, a.build_types, f, [])
+ py.test.raises(AnnotatorError, a.build_types, f, [])
def test_ctr_location(self):
class A:
@@ -3342,7 +3355,8 @@
if g(x, y):
g(x, r_uint(y))
a = self.RPythonAnnotator()
- py.test.raises(Exception, a.build_types, f, [int, int])
+ with py.test.raises(UnionError):
+ a.build_types(f, [int, int])
def test_compare_with_zero(self):
def g():
@@ -3464,22 +3478,22 @@
return '%s' % unichr(x)
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, a.build_types, f, [int])
+ py.test.raises(AnnotatorError, a.build_types, f, [int])
def f(x):
return '%s' % (unichr(x) * 3)
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, a.build_types, f, [int])
+ py.test.raises(AnnotatorError, a.build_types, f, [int])
def f(x):
return '%s%s' % (1, unichr(x))
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, a.build_types, f, [int])
+ py.test.raises(AnnotatorError, a.build_types, f, [int])
def f(x):
return '%s%s' % (1, unichr(x) * 15)
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, a.build_types, f, [int])
+ py.test.raises(AnnotatorError, a.build_types, f, [int])
def test_strformatting_tuple(self):
@@ -3517,7 +3531,7 @@
return [1, 2, 3][s:e]
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, "a.build_types(f, [int, int])")
+ py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def f(x):
@@ -3530,20 +3544,20 @@
return "xyz".find("x", s, e)
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError, "a.build_types(f, [int, int])")
+ py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def f(s, e):
return "xyz".rfind("x", s, e)
- py.test.raises(annmodel.AnnotatorError, "a.build_types(f, [int, int])")
+ py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def f(s, e):
return "xyz".count("x", s, e)
- py.test.raises(annmodel.AnnotatorError, "a.build_types(f, [int, int])")
+ py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
@@ -3717,7 +3731,8 @@
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, [])
+ with py.test.raises(AssertionError):
+ a.build_types(f, [])
def test_enumerate(self):
def f():
@@ -4102,7 +4117,8 @@
e = cls()
e.foo = "bar"
a = self.RPythonAnnotator()
- py.test.raises(Exception, a.build_types, fn, [])
+ with py.test.raises(NoSuchAttrError):
+ a.build_types(fn, [])
def test_lower_char(self):
def fn(c):
@@ -4214,7 +4230,7 @@
return "bbb"
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as exc:
+ with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
the_exc = exc.value
@@ -4230,7 +4246,7 @@
return (1, 2)
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as exc:
+ with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert "RPython cannot unify tuples of different length: 2 versus 1"
in exc.value.msg
@@ -4243,7 +4259,7 @@
return -1
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as exc:
+ with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert ("RPython cannot prove that these integers are of the "
@@ -4260,7 +4276,7 @@
return B()
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as exc:
+ with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert ("RPython cannot unify instances with no common base class"
@@ -4276,7 +4292,7 @@
return d.itervalues()
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as exc:
+ with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert ("RPython cannot unify incompatible iterator variants" in
@@ -4288,7 +4304,7 @@
a = A()
return getattr(a, y)
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.AnnotatorError) as exc:
+ with py.test.raises(AnnotatorError) as exc:
a.build_types(f, [str])
assert ("variable argument to getattr" in exc.value.msg)
@@ -4296,7 +4312,7 @@
def f(x):
return x()
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.AnnotatorError) as exc:
+ with py.test.raises(AnnotatorError) as exc:
a.build_types(f, [str])
assert ("Cannot prove that the object is callable" in exc.value.msg)
@@ -4305,7 +4321,7 @@
def f(x):
l.append(x)
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as excinfo:
+ with py.test.raises(UnionError) as excinfo:
a.build_types(f, [int])
assert 'Happened at file' in excinfo.value.source
assert 'Known variable annotations:' in excinfo.value.source
@@ -4314,7 +4330,7 @@
def f(s, x):
return s.format(x)
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.AnnotatorError) as exc:
+ with py.test.raises(AnnotatorError) as exc:
a.build_types(f, [str, str])
assert ("format() is not RPython" in exc.value.msg)
@@ -4350,7 +4366,7 @@
def f(x):
a, b = x
a = self.RPythonAnnotator()
- py.test.raises(annmodel.AnnotatorError,
+ py.test.raises(AnnotatorError,
a.build_types, f, [annmodel.s_None])
def test_class___name__(self):
@@ -4464,10 +4480,10 @@
o = O2(n)
o.x = 20
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as exc:
+ with py.test.raises(UnionError) as exc:
a.build_types(f1, [int])
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.UnionError) as exc:
+ with py.test.raises(UnionError) as exc:
a.build_types(f2, [int])
def test_property_union_2(self):
@@ -4496,7 +4512,7 @@
a = self.RPythonAnnotator()
# Ideally, this should translate to something sensible,
# but for now, AnnotatorError is better than silently mistranslating.
- with py.test.raises(annmodel.AnnotatorError):
+ with py.test.raises(AnnotatorError):
a.build_types(f, [int])
def test_property_union_3(self):
@@ -4516,7 +4532,7 @@
obj = B()
return obj.x
a = self.RPythonAnnotator()
- with py.test.raises(annmodel.AnnotatorError):
+ with py.test.raises(AnnotatorError):
a.build_types(f, [int])
def test_dict_can_be_none_ordering_issue(self):
diff --git a/rpython/annotator/test/test_annsimplifyrpython.py
b/rpython/annotator/test/test_annsimplifyrpython.py
--- a/rpython/annotator/test/test_annsimplifyrpython.py
+++ b/rpython/annotator/test/test_annsimplifyrpython.py
@@ -3,6 +3,7 @@
from rpython.annotator.test.test_annrpython import graphof
from rpython.annotator.test.test_annrpython import TestAnnotateTestCase as
parent
+from rpython.annotator.model import AnnotatorError
class TestAnnotateAndSimplifyTestCase(parent):
@@ -132,5 +133,5 @@
cls = C
return cls().foo
a = self.RPythonAnnotator()
- with py.test.raises(Exception):
+ with py.test.raises(AnnotatorError):
a.build_types(f, [int])
diff --git a/rpython/rlib/rstrategies/rstrategies.py
b/rpython/rlib/rstrategies/rstrategies.py
--- a/rpython/rlib/rstrategies/rstrategies.py
+++ b/rpython/rlib/rstrategies/rstrategies.py
@@ -41,7 +41,7 @@
attrs['get_storage'] = get_storage
attrs['set_storage'] = set_storage
return type.__new__(self, name, bases, attrs)
-
+
def strategy(generalize=None, singleton=True):
"""
Strategy classes must be decorated with this.
@@ -71,19 +71,19 @@
class StrategyFactory(object):
_immutable_fields_ = ["strategies[*]", "logger",
"strategy_singleton_field"]
factory_instance_counter = 0
-
+
def __init__(self, root_class, all_strategy_classes=None):
if all_strategy_classes is None:
all_strategy_classes = self._collect_subclasses(root_class)
self.strategies = []
self.logger = logger.Logger()
-
+
# This is to avoid confusion between multiple factories existing
simultaneously (e.g. in tests)
self.strategy_singleton_field = "__singleton_%i" %
StrategyFactory.factory_instance_counter
StrategyFactory.factory_instance_counter += 1
-
+
self._create_strategy_instances(root_class, all_strategy_classes)
-
+
def _create_strategy_instances(self, root_class, all_strategy_classes):
for strategy_class in all_strategy_classes:
if strategy_class._is_strategy:
@@ -91,11 +91,11 @@
self.strategies.append(strategy_class)
self._patch_strategy_class(strategy_class, root_class)
self._order_strategies()
-
+
# =============================
# API methods
# =============================
-
+
def switch_strategy(self, w_self, new_strategy_type, new_element=None):
"""
Switch the strategy of w_self to the new type.
@@ -113,7 +113,7 @@
new_strategy.strategy_switched(w_self)
self.log(w_self, new_strategy, old_strategy, new_element)
return new_strategy
-
+
def set_initial_strategy(self, w_self, strategy_type, size, elements=None):
"""
Initialize the strategy and storage fields of w_self.
@@ -135,7 +135,7 @@
strategy.strategy_switched(w_self)
self.log(w_self, strategy, None, element)
return strategy
-
+
@jit.unroll_safe
def strategy_type_for(self, objects):
"""
@@ -153,8 +153,8 @@
for i, strategy_type in enumerate(self.strategies):
if can_handle[i]:
return strategy_type
- raise Exception("Could not find strategy to handle: %s" % objects)
-
+ raise ValueError("Could not find strategy to handle: %s" % objects)
+
def decorate_strategies(self, transitions):
"""
As an alternative to decorating all strategies with @strategy,
@@ -165,11 +165,11 @@
"NOT_RPYTHON"
for strategy_class, generalized in transitions.items():
strategy(generalized)(strategy_class)
-
+
# =============================
# The following methods can be overwritten to customize certain aspects of
the factory.
# =============================
-
+
def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0):
"""
Return a functional instance of strategy_type.
@@ -177,7 +177,7 @@
The two additional parameters should be ignored for
singleton-strategies.
"""
return strategy_type()
-
+
def log(self, w_self, new_strategy, old_strategy=None, new_element=None):
"""
This can be overwritten into a more appropriate call to self.logger.log
@@ -190,7 +190,7 @@
typename = ""
cause = "Switched" if old_strategy else "Created"
self.logger.log(new_strategy_str, size, cause, old_strategy_str,
typename, element_typename)
-
+
@specialize.call_location()
def log_string_for_object(self, obj):
"""
@@ -198,8 +198,8 @@
Keep the specialize-annotation in order to handle different kinds of
objects here.
"""
return obj.__class__.__name__ if obj else ""
-
- # These storage accessors are specialized because the storage field is
+
+ # These storage accessors are specialized because the storage field is
# populated by erased-objects which seem to be incompatible sometimes.
@specialize.call_location()
def get_storage(self, obj):
@@ -207,16 +207,16 @@
@specialize.call_location()
def set_storage(self, obj, val):
return obj._set_storage(val)
-
+
def get_strategy(self, obj):
return obj._get_strategy()
def set_strategy(self, obj, val):
return obj._set_strategy(val)
-
+
# =============================
# Internal methods
# =============================
-
+
def _patch_strategy_class(self, strategy_class, root_class):
"NOT_RPYTHON"
# Patch root class: Add default handler for visitor
@@ -225,12 +225,12 @@
funcname = "_convert_storage_from_" + strategy_class.__name__
_convert_storage_from_OTHER.func_name = funcname
setattr(root_class, funcname, _convert_storage_from_OTHER)
-
+
# Patch strategy class: Add polymorphic visitor function
def _convert_storage_to(self, w_self, new_strategy):
getattr(new_strategy, funcname)(w_self, self)
strategy_class._convert_storage_to = _convert_storage_to
-
+
def _collect_subclasses(self, cls):
"NOT_RPYTHON"
subclasses = []
@@ -238,7 +238,7 @@
subclasses.append(subcls)
subclasses.extend(self._collect_subclasses(subcls))
return subclasses
-
+
def _order_strategies(self):
"NOT_RPYTHON"
def get_generalization_depth(strategy, visited=None):
@@ -256,11 +256,11 @@
else:
return 0
self.strategies.sort(key=get_generalization_depth, reverse=True)
-
+
@jit.elidable
def strategy_singleton_instance(self, strategy_class):
return getattr(strategy_class, self.strategy_singleton_field)
-
+
def _freeze_(self):
# Instance will be frozen at compile time, making accesses constant.
# The constructor does meta stuff which is not possible after
translation.
@@ -271,65 +271,65 @@
== Required:
strategy_factory(self) - Access to StorageFactory
"""
-
+
def strategy_switched(self, w_self):
# Overwrite this method for a hook whenever the strategy
# of w_self was switched to self.
pass
-
+
# Main Fixedsize API
-
+
def store(self, w_self, index0, value):
raise NotImplementedError("Abstract method")
-
+
def fetch(self, w_self, index0):
raise NotImplementedError("Abstract method")
-
+
def size(self, w_self):
raise NotImplementedError("Abstract method")
-
+
# Fixedsize utility methods
-
+
def slice(self, w_self, start, end):
return [ self.fetch(w_self, i) for i in range(start, end)]
-
+
def fetch_all(self, w_self):
return self.slice(w_self, 0, self.size(w_self))
-
+
def store_all(self, w_self, elements):
for i, e in enumerate(elements):
self.store(w_self, i, e)
-
+
# Main Varsize API
-
+
def insert(self, w_self, index0, list_w):
raise NotImplementedError("Abstract method")
-
+
def delete(self, w_self, start, end):
raise NotImplementedError("Abstract method")
-
+
# Varsize utility methods
-
+
def append(self, w_self, list_w):
- self.insert(w_self, self.size(w_self), list_w)
-
+ self.insert(w_self, self.size(w_self), list_w)
+
def pop(self, w_self, index0):
e = self.fetch(w_self, index0)
self.delete(w_self, index0, index0+1)
return e
# Internal methods
-
+
def _initialize_storage(self, w_self, initial_size):
raise NotImplementedError("Abstract method")
-
+
def _check_can_handle(self, value):
raise NotImplementedError("Abstract method")
-
+
def _convert_storage_to(self, w_self, new_strategy):
# This will be overwritten in _patch_strategy_class
new_strategy._convert_storage_from(w_self, self)
-
+
@jit.unroll_safe
def _convert_storage_from(self, w_self, previous_strategy):
# This is a very unefficient (but most generic) way to do this.
@@ -338,16 +338,16 @@
self._initialize_storage(w_self, previous_strategy.size(w_self))
for i, field in enumerate(storage):
self.store(w_self, i, field)
-
+
def _generalize_for_value(self, w_self, value):
strategy_type = self.generalized_strategy_for(value)
new_instance = self.strategy_factory().switch_strategy(w_self,
strategy_type, new_element=value)
return new_instance
-
+
def _cannot_handle_store(self, w_self, index0, value):
new_instance = self._generalize_for_value(w_self, value)
new_instance.store(w_self, index0, value)
-
+
def _cannot_handle_insert(self, w_self, index0, list_w):
# TODO - optimize. Prevent multiple generalizations and slicing done
by callers.
new_strategy = self._generalize_for_value(w_self, list_w[0])
@@ -358,7 +358,7 @@
class EmptyStrategy(AbstractStrategy):
# == Required:
# See AbstractStrategy
-
+
def _initialize_storage(self, w_self, initial_size):
assert initial_size == 0
self.set_storage(w_self, None)
@@ -366,7 +366,7 @@
self.set_storage(w_self, None)
def _check_can_handle(self, value):
return False
-
+
def fetch(self, w_self, index0):
raise IndexError
def store(self, w_self, index0, value):
@@ -389,7 +389,7 @@
# See AbstractStrategy
# check_index_*(...) - use mixin SafeIndexingMixin or UnsafeIndexingMixin
# value(self) - the single value contained in this strategy. Should be
constant.
-
+
def _initialize_storage(self, w_self, initial_size):
storage_obj = SingleValueStrategyStorage(initial_size)
self.set_storage(w_self, storage_obj)
@@ -397,7 +397,7 @@
self._initialize_storage(w_self, previous_strategy.size(w_self))
def _check_can_handle(self, value):
return value is self.value()
-
+
def fetch(self, w_self, index0):
self.check_index_fetch(w_self, index0)
return self.value()
@@ -411,7 +411,7 @@
self.get_storage(w_self).size -= (end - start)
def size(self, w_self):
return self.get_storage(w_self).size
-
+
@jit.unroll_safe
def insert(self, w_self, index0, list_w):
storage_obj = self.get_storage(w_self)
@@ -429,18 +429,18 @@
# See AbstractStrategy
# check_index_*(...) - use mixin SafeIndexingMixin or UnsafeIndexingMixin
# default_value(self) - The value to be initially contained in this
strategy
-
+
def _initialize_storage(self, w_self, initial_size):
default = self._unwrap(self.default_value())
self.set_storage(w_self, [default] * initial_size)
-
+
@jit.unroll_safe
def _convert_storage_from(self, w_self, previous_strategy):
size = previous_strategy.size(w_self)
new_storage = [ self._unwrap(previous_strategy.fetch(w_self, i))
for i in range(size) ]
self.set_storage(w_self, new_storage)
-
+
def store(self, w_self, index0, wrapped_value):
self.check_index_store(w_self, index0)
if self._check_can_handle(wrapped_value):
@@ -448,21 +448,21 @@
self.get_storage(w_self)[index0] = unwrapped
else:
self._cannot_handle_store(w_self, index0, wrapped_value)
-
+
def fetch(self, w_self, index0):
self.check_index_fetch(w_self, index0)
unwrapped = self.get_storage(w_self)[index0]
return self._wrap(unwrapped)
-
+
def _wrap(self, value):
raise NotImplementedError("Abstract method")
-
+
def _unwrap(self, value):
raise NotImplementedError("Abstract method")
-
+
def size(self, w_self):
return len(self.get_storage(w_self))
-
+
@jit.unroll_safe
def insert(self, w_self, start, list_w):
# This is following Python's behaviour - insert automatically
@@ -475,27 +475,27 @@
else:
self._cannot_handle_insert(w_self, start + i, list_w[i:])
return
-
+
def delete(self, w_self, start, end):
self.check_index_range(w_self, start, end)
assert start >= 0 and end >= 0
del self.get_storage(w_self)[start : end]
-
+
class GenericStrategy(StrategyWithStorage):
# == Required:
# See StrategyWithStorage
-
+
def _wrap(self, value):
return value
def _unwrap(self, value):
return value
def _check_can_handle(self, wrapped_value):
return True
-
+
class WeakGenericStrategy(StrategyWithStorage):
# == Required:
# See StrategyWithStorage
-
+
def _wrap(self, value):
return value() or self.default_value()
def _unwrap(self, value):
@@ -503,7 +503,7 @@
return weakref.ref(value)
def _check_can_handle(self, wrapped_value):
return True
-
+
# ============== Mixins for index checking operations ==============
class SafeIndexingMixin(object):
@@ -535,37 +535,37 @@
# See StrategyWithStorage
# wrap(self, value) - Return a boxed object for the primitive value
# unwrap(self, value) - Return the unboxed primitive value of value
-
+
def _unwrap(self, value):
return self.unwrap(value)
def _wrap(self, value):
return self.wrap(value)
-
+
class SingleTypeStrategy(SpecializedStrategy):
# == Required Functions:
# See SpecializedStrategy
# contained_type - The wrapped type that can be stored in this strategy
-
+
def _check_can_handle(self, value):
return isinstance(value, self.contained_type)
-
+
class TaggingStrategy(SingleTypeStrategy):
"""This strategy uses a special tag value to represent a single additional
object."""
# == Required:
# See SingleTypeStrategy
# wrapped_tagged_value(self) - The tagged object
# unwrapped_tagged_value(self) - The unwrapped tag value representing the
tagged object
-
+
def _check_can_handle(self, value):
return value is self.wrapped_tagged_value() or \
(isinstance(value, self.contained_type) and \
self.unwrap(value) != self.unwrapped_tagged_value())
-
+
def _unwrap(self, value):
if value is self.wrapped_tagged_value():
return self.unwrapped_tagged_value()
return self.unwrap(value)
-
+
def _wrap(self, value):
if value == self.unwrapped_tagged_value():
return self.wrapped_tagged_value()
diff --git a/rpython/rlib/rstrategies/test/test_rstrategies.py
b/rpython/rlib/rstrategies/test/test_rstrategies.py
--- a/rpython/rlib/rstrategies/test/test_rstrategies.py
+++ b/rpython/rlib/rstrategies/test/test_rstrategies.py
@@ -69,7 +69,7 @@
class Factory(rs.StrategyFactory):
switching_log = []
-
+
def __init__(self, root_class):
self.decorate_strategies({
EmptyStrategy: [NilStrategy, IntegerStrategy,
IntegerOrNilStrategy, GenericStrategy],
@@ -79,15 +79,15 @@
IntegerOrNilStrategy: [GenericStrategy],
})
rs.StrategyFactory.__init__(self, root_class)
-
+
def instantiate_strategy(self, strategy_type, w_self=None, size=0):
return strategy_type(self, w_self, size)
-
- def set_strategy(self, w_list, strategy):
+
+ def set_strategy(self, w_list, strategy):
old_strategy = self.get_strategy(w_list)
self.switching_log.append((old_strategy, strategy))
super(Factory, self).set_strategy(w_list, strategy)
-
+
def clear_log(self):
del self.switching_log[:]
@@ -107,7 +107,7 @@
class WeakGenericStrategy(AbstractStrategy):
import_from_mixin(rs.WeakGenericStrategy)
def default_value(self): return w_nil
-
+
class IntegerStrategy(AbstractStrategy):
import_from_mixin(rs.SingleTypeStrategy)
contained_type = W_Integer
@@ -123,7 +123,7 @@
def default_value(self): return w_nil
def wrapped_tagged_value(self): return w_nil
def unwrapped_tagged_value(self): import sys; return sys.maxint
-
+
@rs.strategy(generalize=[], singleton=False)
class NonSingletonStrategy(GenericStrategy):
def __init__(self, factory, w_list=None, size=0):
@@ -214,22 +214,22 @@
py.test.raises(IndexError, s.fetch, l, 10)
py.test.raises(IndexError, s.delete, l, 0, 1)
py.test.raises(AssertionError, W_List, EmptyStrategy, 2) # Only size 0
possible.
-
+
def test_init_Nil():
do_test_initialization(NilStrategy)
def test_init_Generic():
do_test_initialization(GenericStrategy, is_safe=False)
-
+
def test_init_WeakGeneric():
do_test_initialization(WeakGenericStrategy)
-
+
def test_init_Integer():
do_test_initialization(IntegerStrategy, default_value=W_Integer(0))
-
+
def test_init_IntegerOrNil():
do_test_initialization(IntegerOrNilStrategy)
-
+
# === Test Simple store
def do_test_store(cls, stored_value=W_Object(), is_safe=True,
is_varsize=False):
@@ -256,13 +256,13 @@
def test_store_Generic():
do_test_store(GenericStrategy, is_safe=False)
-
+
def test_store_WeakGeneric():
do_test_store(WeakGenericStrategy, stored_value=w_nil)
-
+
def test_store_Integer():
do_test_store(IntegerStrategy, stored_value=W_Integer(100))
-
+
def test_store_IntegerOrNil():
do_test_store(IntegerOrNilStrategy, stored_value=W_Integer(100))
do_test_store(IntegerOrNilStrategy, stored_value=w_nil)
@@ -289,17 +289,17 @@
def test_insert_Generic():
do_test_insert(GenericStrategy, [W_Object() for _ in range(6)])
-
+
def test_insert_WeakGeneric():
do_test_insert(WeakGenericStrategy, [W_Object() for _ in range(6)])
-
+
def test_insert_Integer():
do_test_insert(IntegerStrategy, [W_Integer(x) for x in range(6)])
-
+
def test_insert_IntegerOrNil():
do_test_insert(IntegerOrNilStrategy, [w_nil]+[W_Integer(x) for x in
range(4)]+[w_nil])
do_test_insert(IntegerOrNilStrategy, [w_nil]*6)
-
+
# === Test Delete
def do_test_delete(cls, values, indexing_unsafe=False):
@@ -319,13 +319,13 @@
def test_delete_Generic():
do_test_delete(GenericStrategy, [W_Object() for _ in range(6)],
indexing_unsafe=True)
-
+
def test_delete_WeakGeneric():
do_test_delete(WeakGenericStrategy, [W_Object() for _ in range(6)])
-
+
def test_delete_Integer():
do_test_delete(IntegerStrategy, [W_Integer(x) for x in range(6)])
-
+
def test_delete_IntegerOrNil():
do_test_delete(IntegerOrNilStrategy, [w_nil]+[W_Integer(x) for x in
range(4)]+[w_nil])
do_test_delete(IntegerOrNilStrategy, [w_nil]*6)
@@ -342,7 +342,7 @@
obj = W_Object()
i = W_Integer(0)
nil = w_nil
-
+
assert_handles(EmptyStrategy, [], [nil, obj, i])
assert_handles(NilStrategy, [nil], [obj, i])
assert_handles(GenericStrategy, [nil, obj, i], [])
@@ -392,7 +392,7 @@
o = W_Object()
l = do_test_insert(NilStrategy, [w_nil, w_nil, o, o, w_nil, w_nil])
assert isinstance(l.strategy, GenericStrategy)
-
+
def test_transition_to_nonSingleton():
l = W_List(NilStrategy, 5)
factory.switch_strategy(l, NonSingletonStrategy)
@@ -467,12 +467,12 @@
v3 = [W_Object() for _ in range(l.size()) ]
assert v2 != v
assert v3 != v
-
+
l.store_all(v2)
assert l.fetch_all() == v2+v[4:]
l.store_all(v3)
assert l.fetch_all() == v3
-
+
py.test.raises(IndexError, l.store_all, [W_Object() for _ in range(8) ])
# === Test Weak Strategy
@@ -488,7 +488,7 @@
assert False, "The default convert_storage_from() should not be
called!"
def convert_storage_from_special(self, w_self, other):
s.copied += 1
-
+
monkeypatch.setattr(AbstractStrategy, "_convert_storage_from_NilStrategy",
convert_storage_from_special)
monkeypatch.setattr(AbstractStrategy, "_convert_storage_from",
convert_storage_from_default)
try:
@@ -507,7 +507,8 @@
assert factory.strategy_type_for([]) == EmptyStrategy
monkeypatch.setattr(GenericStrategy, '_check_can_handle', lambda self, o:
False)
try:
- py.test.raises(Exception, factory.strategy_type_for, [W_Object(),
W_Object()])
+ with py.test.raises(ValueError):
+ factory.strategy_type_for([W_Object(), W_Object()])
finally:
monkeypatch.undo()
@@ -549,4 +550,3 @@
'Created (EmptyStrategy) size 0 objects 1',
'Created (IntegerStrategy) size 3 objects 1',
'Switched (IntegerStrategy -> IntegerOrNilStrategy) size 3 objects 1
elements: W_Object']
-
\ No newline at end of file
diff --git a/rpython/rlib/rweakref.py b/rpython/rlib/rweakref.py
--- a/rpython/rlib/rweakref.py
+++ b/rpython/rlib/rweakref.py
@@ -2,10 +2,10 @@
Weakref support in RPython. Basic regular weakrefs without callbacks
are supported. This file contains the following additions:
a form of WeakKeyDictionary, and a limited version of WeakValueDictionary.
-LLType only for now!
"""
import weakref
+from rpython.annotator.model import UnionError
ref = weakref.ref # basic regular weakrefs are supported in RPython
@@ -191,9 +191,9 @@
class __extend__(pairtype(SomeWeakKeyDict, SomeWeakKeyDict)):
def union((s_wkd1, s_wkd2)):
if s_wkd1.keyclassdef is not s_wkd2.keyclassdef:
- raise UnionError(w_wkd1, s_wkd2, "not the same key class!")
+ raise UnionError(s_wkd1, s_wkd2, "not the same key class!")
if s_wkd1.valueclassdef is not s_wkd2.valueclassdef:
- raise UnionError(w_wkd1, s_wkd2, "not the same value class!")
+ raise UnionError(s_wkd1, s_wkd2, "not the same value class!")
return SomeWeakKeyDict(s_wkd1.keyclassdef, s_wkd1.valueclassdef)
class Entry(extregistry.ExtRegistryEntry):
diff --git a/rpython/rlib/test/test_rweakkeydict.py
b/rpython/rlib/test/test_rweakkeydict.py
--- a/rpython/rlib/test/test_rweakkeydict.py
+++ b/rpython/rlib/test/test_rweakkeydict.py
@@ -1,4 +1,5 @@
import py
+from rpython.annotator.model import UnionError
from rpython.rlib import rgc
from rpython.rlib.rweakref import RWeakKeyDictionary
from rpython.rtyper.test.test_llinterp import interpret
@@ -120,25 +121,34 @@
f(1)
interpret(f, [1])
[email protected](
+ reason="may fail with AssertionError, depending on annotation order")
+def test_rpython_merge_RWeakKeyDictionary3():
def g(x):
if x:
d = RWeakKeyDictionary(KX, VX)
else:
d = RWeakKeyDictionary(KY, VX)
d.set(KX(), VX())
- py.test.raises(Exception, interpret, g, [1])
+ with py.test.raises(UnionError):
+ interpret(g, [1])
+
[email protected](
+ reason="may fail with AssertionError, depending on annotation order")
+def test_rpython_merge_RWeakKeyDictionary4():
def g(x):
if x:
d = RWeakKeyDictionary(KX, VX)
else:
d = RWeakKeyDictionary(KX, VY)
d.set(KX(), VX())
- py.test.raises(Exception, interpret, g, [1])
+ with py.test.raises(UnionError):
+ interpret(g, [1])
[email protected](reason="not implemented, messy")
def test_rpython_free_values():
- import py; py.test.skip("XXX not implemented, messy")
class VXDel:
def __del__(self):
state.freed.append(1)
diff --git a/rpython/rlib/test/test_rweakvaldict.py
b/rpython/rlib/test/test_rweakvaldict.py
--- a/rpython/rlib/test/test_rweakvaldict.py
+++ b/rpython/rlib/test/test_rweakvaldict.py
@@ -1,4 +1,5 @@
import py
+from rpython.annotator.model import UnionError
from rpython.rlib import rgc
from rpython.rlib.rweakref import RWeakValueDictionary
from rpython.rtyper.test.test_llinterp import interpret
@@ -143,7 +144,9 @@
else:
d = RWeakValueDictionary(str, Y)
d.set("x", X())
- py.test.raises(Exception, interpret, g, [1])
+
+ with py.test.raises(UnionError):
+ interpret(g, [1])
def test_rpython_RWeakValueDictionary_or_None():
diff --git a/rpython/rtyper/extfunc.py b/rpython/rtyper/extfunc.py
--- a/rpython/rtyper/extfunc.py
+++ b/rpython/rtyper/extfunc.py
@@ -1,8 +1,8 @@
from rpython.rtyper import extregistry
from rpython.rtyper.extregistry import ExtRegistryEntry
from rpython.rtyper.lltypesystem.lltype import typeOf, FuncType, functionptr
-from rpython.annotator import model as annmodel
-from rpython.annotator.signature import annotation
+from rpython.annotator.model import unionof
+from rpython.annotator.signature import annotation, SignatureError
import py, sys
@@ -130,7 +130,7 @@
"Argument number mismatch"
for i, expected in enumerate(signature_args):
- arg = annmodel.unionof(args_s[i], expected)
+ arg = unionof(args_s[i], expected)
if not expected.contains(arg):
name = getattr(self, 'name', None)
if not name:
@@ -138,7 +138,7 @@
name = self.instance.__name__
except AttributeError:
name = '?'
- raise Exception("In call to external function %r:\n"
+ raise SignatureError("In call to external function %r:\n"
"arg %d must be %s,\n"
" got %s" % (
name, i+1, expected, args_s[i]))
diff --git a/rpython/rtyper/test/test_extfunc.py
b/rpython/rtyper/test/test_extfunc.py
--- a/rpython/rtyper/test/test_extfunc.py
+++ b/rpython/rtyper/test/test_extfunc.py
@@ -2,9 +2,10 @@
from rpython.rtyper.extfunc import ExtFuncEntry, register_external,\
is_external, lazy_register
-from rpython.annotator import model as annmodel
+from rpython.annotator.model import SomeInteger, SomeString, AnnotatorError
from rpython.annotator.annrpython import RPythonAnnotator
from rpython.annotator.policy import AnnotatorPolicy
+from rpython.annotator.signature import SignatureError
from rpython.rtyper.test.test_llinterp import interpret
class TestExtFuncEntry:
@@ -21,8 +22,8 @@
class BTestFuncEntry(ExtFuncEntry):
_about_ = b
name = 'b'
- signature_args = [annmodel.SomeInteger()]
- signature_result = annmodel.SomeInteger()
+ signature_args = [SomeInteger()]
+ signature_result = SomeInteger()
def f():
return b(2)
@@ -30,7 +31,7 @@
policy = AnnotatorPolicy()
a = RPythonAnnotator(policy=policy)
s = a.build_types(f, [])
- assert isinstance(s, annmodel.SomeInteger)
+ assert isinstance(s, SomeInteger)
res = interpret(f, [])
assert res == 42
@@ -45,8 +46,8 @@
class CTestFuncEntry(ExtFuncEntry):
_about_ = c
name = 'ccc'
- signature_args = [annmodel.SomeInteger()] * 2
- signature_result = annmodel.SomeInteger()
+ signature_args = [SomeInteger()] * 2
+ signature_result = SomeInteger()
def lltypeimpl(y, x):
return y + x
@@ -72,7 +73,7 @@
policy = AnnotatorPolicy()
a = RPythonAnnotator(policy=policy)
s = a.build_types(f, [])
- assert isinstance(s, annmodel.SomeInteger)
+ assert isinstance(s, SomeInteger)
def test_register_external_tuple_args(self):
"""
@@ -96,7 +97,7 @@
s = a.build_types(f, [])
# Not a very good assertion, but at least it means _something_
happened.
- assert isinstance(s, annmodel.SomeInteger)
+ assert isinstance(s, SomeInteger)
def test_register_external_return_goes_back(self):
"""
@@ -118,7 +119,7 @@
policy = AnnotatorPolicy()
a = RPythonAnnotator(policy=policy)
s = a.build_types(f, [])
- assert isinstance(s, annmodel.SomeInteger)
+ assert isinstance(s, SomeInteger)
def test_register_external_specialcase(self):
"""
@@ -135,10 +136,10 @@
policy = AnnotatorPolicy()
a = RPythonAnnotator(policy=policy)
s = a.build_types(f, [])
- assert isinstance(s, annmodel.SomeString)
+ assert isinstance(s, SomeString)
def test_str0(self):
- str0 = annmodel.SomeString(no_nul=True)
+ str0 = SomeString(no_nul=True)
def os_open(s):
pass
register_external(os_open, [str0], None)
@@ -152,25 +153,32 @@
a.translator.config.translation.check_str_without_nul=True
def g(s):
return os_open(s)
- py.test.raises(Exception, a.build_types, g, [str])
+ with py.test.raises(SignatureError):
+ a.build_types(g, [str])
a.build_types(g, [str0]) # Does not raise
- def test_list_of_str0(self):
- str0 = annmodel.SomeString(no_nul=True)
+ def test_list_of_str0_unchecked(self):
+ str0 = SomeString(no_nul=True)
+
def os_execve(l):
pass
+
register_external(os_execve, [[str0]], None)
+
def f(l):
return os_execve(l)
+
policy = AnnotatorPolicy()
a = RPythonAnnotator(policy=policy)
+ assert a.translator.config.translation.check_str_without_nul == False
a.build_types(f, [[str]]) # Does not raise
- assert a.translator.config.translation.check_str_without_nul == False
# Now enable the str0 check, and try again with a similar function
a.translator.config.translation.check_str_without_nul=True
+
def g(l):
return os_execve(l)
- py.test.raises(Exception, a.build_types, g, [[str]])
+
+ with py.test.raises(AnnotatorError):
+ # fails with TooLateForChange
+ a.build_types(g, [[str]])
a.build_types(g, [[str0]]) # Does not raise
-
-
_______________________________________________
pypy-commit mailing list
[email protected]
https://mail.python.org/mailman/listinfo/pypy-commit