Debian Codegraph @

rpython/flowspace/operation.py

raw symbols SCIP
1 """
2 This module defines all the SpaceOperations used in rpython.flowspace.
3 """
4
5 import __builtin__
6 import __future__
7 import operator
8 import sys
9 import types
10 from rpython.tool.pairtype import pair, DoubleDispatchRegistry
11 from rpython.rlib.unroll import unrolling_iterable, _unroller
12 from rpython.tool.sourcetools import compile2
13 from rpython.flowspace.model import (Constant, WrapException, const, Variable,
14 SpaceOperation)
15 from rpython.flowspace.specialcase import register_flow_sc
16 from rpython.annotator.model import (
17 SomeTuple, AnnotatorError, read_can_only_throw)
18 from rpython.annotator.argument import ArgumentsForTranslation
19 from rpython.flowspace.specialcase import SPECIAL_CASES
20
21
22 NOT_REALLY_CONST = {
23 Constant(sys): {
24 Constant('maxint'): True,
25 Constant('maxunicode'): True,
26 Constant('api_version'): True,
27 Constant('exit'): True,
28 Constant('exc_info'): True,
29 Constant('getrefcount'): True,
30 Constant('getdefaultencoding'): True,
31 # this is an incomplete list of true constants.
32 # if we add much more, a dedicated class
33 # might be considered for special objects.
34 }
35 }
36
37 # built-ins that can always raise exceptions
38 builtins_exceptions = {
39 int: [ValueError],
40 float: [ValueError],
41 chr: [ValueError],
42 unichr: [ValueError],
43 unicode: [UnicodeDecodeError],
44 }
45
46
47 class _OpHolder(object):
48 pass
49 op = _OpHolder()
50
51 func2op = {}
52
53 class HLOperationMeta(type):
54 def __init__(cls, name, bases, attrdict):
55 type.__init__(cls, name, bases, attrdict)
56 if hasattr(cls, 'opname'):
57 setattr(op, cls.opname, cls)
58 if cls.dispatch == 1:
59 cls._registry = {}
60 cls._transform = {}
61 elif cls.dispatch == 2:
62 cls._registry = DoubleDispatchRegistry()
63 cls._transform = DoubleDispatchRegistry()
64
65
66 class HLOperation(SpaceOperation):
67 __metaclass__ = HLOperationMeta
68 pure = False
69 can_overflow = False
70 dispatch = None # number of arguments to dispatch on
71 # (None means special handling)
72
73 def __init__(self, *args):
74 self.args = list(args)
75 self.result = Variable()
76 self.offset = -1
77
78 def replace(self, mapping):
79 newargs = [arg.replace(mapping) for arg in self.args]
80 newresult = self.result.replace(mapping)
81 newop = type(self)(*newargs)
82 newop.result = newresult
83 newop.offset = self.offset
84 return newop
85
86 @classmethod
87 def make_sc(cls):
88 def sc_operator(ctx, *args_w):
89 return cls(*args_w).eval(ctx)
90 return sc_operator
91
92 def eval(self, ctx):
93 result = self.constfold()
94 if result is not None:
95 return result
96 return ctx.do_op(self)
97
98 def constfold(self):
99 return None
100
101 def consider(self, annotator):
102 args_s = [annotator.annotation(arg) for arg in self.args]
103 spec = type(self).get_specialization(*args_s)
104 return spec(annotator, *self.args)
105
106 def get_can_only_throw(self, annotator):
107 return None
108
109 def get_transformer(self, *args_s):
110 return lambda *args: None
111
112 def transform(self, annotator):
113 args_s = [annotator.annotation(arg) for arg in self.args]
114 transformer = self.get_transformer(*args_s)
115 return transformer(annotator, *self.args)
116
117 class PureOperation(HLOperation):
118 pure = True
119
120 def constfold(self):
121 args = []
122 if all(w_arg.foldable() for w_arg in self.args):
123 args = [w_arg.value for w_arg in self.args]
124 # All arguments are constants: call the operator now
125 try:
126 result = self.pyfunc(*args)
127 except Exception as e:
128 from rpython.flowspace.flowcontext import FlowingError
129 msg = "%s%r always raises %s: %s" % (
130 self.opname, tuple(args), type(e), e)
131 raise FlowingError(msg)
132 return self._pure_result(result)
133
134 def _pure_result(self, result):
135 # indented for history preservation
136
137 # don't try to constant-fold operations giving a 'long'
138 # result. The result is probably meant to be sent to
139 # an intmask(), but the 'long' constant confuses the
140 # annotator a lot.
141 if self.can_overflow and type(result) is long:
142 pass
143 # don't constant-fold getslice on lists, either
144 elif self.opname == 'getslice' and type(result) is list:
145 pass
146 # otherwise, fine
147 else:
148 try:
149 return const(result)
150 except WrapException:
151 # type cannot sanely appear in flow graph,
152 # store operation with variable result instead
153 pass
154
155 class PureOperation1(PureOperation):
156 pure = True
157
158 def constfold(self):
159 if len(self.args) != 1:
160 return PureOperation.constfold(self)
161 w_arg0, = self.args
162 if not w_arg0.foldable():
163 return
164 arg0 = w_arg0.value
165 # argument is constant: call the operator now
166 try:
167 result = self.pyfunc(arg0)
168 except Exception as e:
169 from rpython.flowspace.flowcontext import FlowingError
170 msg = "%s%r always raises %s: %s" % (
171 self.opname, (arg0, ), type(e), e)
172 raise FlowingError(msg)
173 return self._pure_result(result)
174
175 class PureOperation2(PureOperation):
176 pure = True
177
178 def constfold(self):
179 w_arg0, w_arg1 = self.args
180 if not w_arg0.foldable() or not w_arg1.foldable():
181 return
182 arg0 = w_arg0.value
183 arg1 = w_arg1.value
184 # argument is constant: call the operator now
185 try:
186 result = self.pyfunc(arg0, arg1)
187 except Exception as e:
188 from rpython.flowspace.flowcontext import FlowingError
189 msg = "%s%r always raises %s: %s" % (
190 self.opname, (arg0, arg1), type(e), e)
191 raise FlowingError(msg)
192 return self._pure_result(result)
193
194 class OverflowingOperation(PureOperation):
195 can_overflow = True
196
197 def ovfchecked(self):
198 ovf = self.ovf_variant(*self.args)
199 ovf.offset = self.offset
200 return ovf
201
202 class SingleDispatchMixin(object):
203 dispatch = 1
204
205 @classmethod
206 def register(cls, Some_cls):
207 def decorator(func):
208 cls._registry[Some_cls] = func
209 return func
210 return decorator
211
212 @classmethod
213 def _dispatch(cls, Some_cls):
214 for c in Some_cls.__mro__:
215 try:
216 return cls._registry[c]
217 except KeyError:
218 pass
219 raise AnnotatorError("Unknown operation")
220
221 def get_can_only_throw(self, annotator):
222 args_s = [annotator.annotation(v) for v in self.args]
223 spec = type(self).get_specialization(*args_s)
224 return read_can_only_throw(spec, args_s[0])
225
226 @classmethod
227 def get_specialization(cls, s_arg, *_ignored):
228 try:
229 impl = getattr(s_arg, cls.opname)
230
231 def specialized(annotator, arg, *other_args):
232 return impl(*[annotator.annotation(x) for x in other_args])
233 try:
234 specialized.can_only_throw = impl.can_only_throw
235 except AttributeError:
236 pass
237 return specialized
238 except AttributeError:
239 return cls._dispatch(type(s_arg))
240
241 @classmethod
242 def register_transform(cls, Some_cls):
243 def decorator(func):
244 cls._transform[Some_cls] = func
245 return func
246 return decorator
247
248 @classmethod
249 def get_transformer(cls, s_arg, *_ignored):
250 for c in type(s_arg).__mro__:
251 try:
252 return cls._transform[c]
253 except KeyError:
254 pass
255 return lambda *args: None
256
257
258 class DoubleDispatchMixin(object):
259 dispatch = 2
260
261 @classmethod
262 def register(cls, Some1, Some2):
263 def decorator(func):
264 cls._registry[Some1, Some2] = func
265 return func
266 return decorator
267
268 @classmethod
269 def get_specialization(cls, s_arg1, s_arg2, *_ignored):
270 try:
271 impl = getattr(pair(s_arg1, s_arg2), cls.opname)
272
273 def specialized(annotator, arg1, arg2, *other_args):
274 return impl(*[annotator.annotation(x) for x in other_args])
275 try:
276 specialized.can_only_throw = impl.can_only_throw
277 except AttributeError:
278 pass
279 return specialized
280 except AttributeError:
281 return cls._registry[type(s_arg1), type(s_arg2)]
282
283 def get_can_only_throw(self, annotator):
284 args_s = [annotator.annotation(v) for v in self.args]
285 spec = type(self).get_specialization(*args_s)
286 return read_can_only_throw(spec, args_s[0], args_s[1])
287
288 @classmethod
289 def register_transform(cls, Some1, Some2):
290 def decorator(func):
291 cls._transform[Some1, Some2] = func
292 return func
293 return decorator
294
295 @classmethod
296 def get_transformer(cls, s_arg1, s_arg2, *_ignored):
297 try:
298 return cls._transform[type(s_arg1), type(s_arg2)]
299 except KeyError:
300 return lambda *args: None
301
302
303 def add_operator(name, arity, dispatch=None, pyfunc=None, pure=False, ovf=False):
304 operator_func = getattr(operator, name, None)
305 if dispatch == 1:
306 bases = [SingleDispatchMixin]
307 elif dispatch == 2:
308 bases = [DoubleDispatchMixin]
309 else:
310 bases = []
311 if ovf:
312 assert pure
313 base_cls = OverflowingOperation
314 elif pure:
315 if arity == 1:
316 base_cls = PureOperation1
317 elif arity == 2:
318 base_cls = PureOperation2
319 else:
320 base_cls = PureOperation
321 else:
322 base_cls = HLOperation
323 bases.append(base_cls)
324 cls = HLOperationMeta(name, tuple(bases), {'opname': name, 'arity': arity,
325 'canraise': [],
326 'dispatch': dispatch})
327 if pyfunc is not None:
328 func2op[pyfunc] = cls
329 if operator_func:
330 func2op[operator_func] = cls
331 if pyfunc is not None:
332 cls.pyfunc = staticmethod(pyfunc)
333 elif operator_func is not None:
334 cls.pyfunc = staticmethod(operator_func)
335 if ovf:
336 from rpython.rlib.rarithmetic import ovfcheck
337 ovf_func = lambda *args: ovfcheck(cls.pyfunc(*args))
338 add_operator(name + '_ovf', arity, dispatch, pyfunc=ovf_func)
339 cls.ovf_variant = getattr(op, name + '_ovf')
340
341 # ____________________________________________________________
342
343 def new_style_type(x):
344 """Simulate a situation where every class is new-style"""
345 return getattr(x, '__class__', type(x))
346
347 def do_int(x):
348 return x.__int__()
349
350 def do_index(x):
351 return x.__index__()
352
353 def do_float(x):
354 return x.__float__()
355
356 def do_long(x):
357 return x.__long__()
358
359 def inplace_add(x, y):
360 x += y
361 return x
362
363 def inplace_sub(x, y):
364 x -= y
365 return x
366
367 def inplace_mul(x, y):
368 x *= y
369 return x
370
371 exec(compile2("""
372 def inplace_truediv(x, y):
373 x /= y
374 return x
375 """, flags=__future__.CO_FUTURE_DIVISION, dont_inherit=1))
376 # makes an INPLACE_TRUE_DIVIDE
377
378 def inplace_floordiv(x, y):
379 x //= y
380 return x
381
382 exec(compile2("""
383 def inplace_div(x, y):
384 x /= y
385 return x
386 """, flags=0, dont_inherit=1)) # makes an INPLACE_DIVIDE
387
388 def inplace_mod(x, y):
389 x %= y
390 return x
391
392 def inplace_pow(x, y):
393 x **= y
394 return x
395
396 def inplace_lshift(x, y):
397 x <<= y
398 return x
399
400 def inplace_rshift(x, y):
401 x >>= y
402 return x
403
404 def inplace_and(x, y):
405 x &= y
406 return x
407
408 def inplace_or(x, y):
409 x |= y
410 return x
411
412 def inplace_xor(x, y):
413 x ^= y
414 return x
415
416 def next(x):
417 return x.next()
418
419 def get(x, y, z=None):
420 return x.__get__(y, z)
421
422 def set(x, y, z):
423 x.__set__(y, z)
424
425 def delete(x, y):
426 x.__delete__(y)
427
428 def userdel(x):
429 x.__del__()
430
431 # slicing: operator.{get,set,del}slice() don't support b=None or c=None
432 def do_getslice(a, b, c):
433 return a[b:c]
434
435 def do_setslice(a, b, c, d):
436 a[b:c] = d
437
438 def do_delslice(a, b, c):
439 del a[b:c]
440
441 def unsupported(*args):
442 raise ValueError("this is not supported")
443
444
445 add_operator('is_', 2, dispatch=2, pure=True)
446 add_operator('id', 1, dispatch=1, pyfunc=id)
447 add_operator('type', 1, dispatch=1, pyfunc=new_style_type, pure=True)
448 add_operator('issubtype', 2, dispatch=1, pyfunc=issubclass, pure=True) # not for old-style classes
449 add_operator('isinstance', 2, dispatch=1, pyfunc=isinstance, pure=True)
450 add_operator('repr', 1, dispatch=1, pyfunc=repr, pure=True)
451 add_operator('str', 1, dispatch=1, pyfunc=str, pure=True)
452 add_operator('format', 2, pyfunc=unsupported)
453 add_operator('len', 1, dispatch=1, pyfunc=len, pure=True)
454 add_operator('hash', 1, dispatch=1, pyfunc=hash)
455 add_operator('setattr', 3, dispatch=1, pyfunc=setattr)
456 add_operator('delattr', 2, dispatch=1, pyfunc=delattr)
457 add_operator('getitem', 2, dispatch=2, pure=True)
458 add_operator('getitem_idx', 2, dispatch=2, pure=True)
459 add_operator('setitem', 3, dispatch=2)
460 add_operator('delitem', 2, dispatch=2)
461 add_operator('getslice', 3, dispatch=1, pyfunc=do_getslice, pure=True)
462 add_operator('setslice', 4, dispatch=1, pyfunc=do_setslice)
463 add_operator('delslice', 3, dispatch=1, pyfunc=do_delslice)
464 add_operator('trunc', 1, pyfunc=unsupported)
465 add_operator('pos', 1, dispatch=1, pure=True)
466 add_operator('neg', 1, dispatch=1, pure=True, ovf=True)
467 add_operator('bool', 1, dispatch=1, pyfunc=bool, pure=True)
468 op.is_true = op.nonzero = op.bool # for llinterp
469 add_operator('abs', 1, dispatch=1, pyfunc=abs, pure=True, ovf=True)
470 add_operator('hex', 1, dispatch=1, pyfunc=hex, pure=True)
471 add_operator('oct', 1, dispatch=1, pyfunc=oct, pure=True)
472 add_operator('bin', 1, dispatch=1, pyfunc=bin, pure=True)
473 add_operator('ord', 1, dispatch=1, pyfunc=ord, pure=True)
474 add_operator('invert', 1, dispatch=1, pure=True)
475 add_operator('add', 2, dispatch=2, pure=True, ovf=True)
476 add_operator('sub', 2, dispatch=2, pure=True, ovf=True)
477 add_operator('mul', 2, dispatch=2, pure=True, ovf=True)
478 add_operator('truediv', 2, dispatch=2, pure=True)
479 add_operator('floordiv', 2, dispatch=2, pure=True, ovf=True)
480 add_operator('div', 2, dispatch=2, pure=True, ovf=True)
481 add_operator('mod', 2, dispatch=2, pure=True, ovf=True)
482 add_operator('divmod', 2, pyfunc=divmod, pure=True)
483 add_operator('lshift', 2, dispatch=2, pure=True, ovf=True)
484 add_operator('rshift', 2, dispatch=2, pure=True)
485 add_operator('and_', 2, dispatch=2, pure=True)
486 add_operator('or_', 2, dispatch=2, pure=True)
487 add_operator('xor', 2, dispatch=2, pure=True)
488 add_operator('int', 1, dispatch=1, pyfunc=do_int, pure=True)
489 add_operator('index', 1, pyfunc=do_index, pure=True)
490 add_operator('float', 1, dispatch=1, pyfunc=do_float, pure=True)
491 add_operator('long', 1, dispatch=1, pyfunc=do_long, pure=True)
492 add_operator('inplace_add', 2, dispatch=2, pyfunc=inplace_add)
493 add_operator('inplace_sub', 2, dispatch=2, pyfunc=inplace_sub)
494 add_operator('inplace_mul', 2, dispatch=2, pyfunc=inplace_mul)
495 add_operator('inplace_truediv', 2, dispatch=2, pyfunc=inplace_truediv)
496 add_operator('inplace_floordiv', 2, dispatch=2, pyfunc=inplace_floordiv)
497 add_operator('inplace_div', 2, dispatch=2, pyfunc=inplace_div)
498 add_operator('inplace_mod', 2, dispatch=2, pyfunc=inplace_mod)
499 add_operator('inplace_pow', 2, pyfunc=inplace_pow)
500 add_operator('inplace_lshift', 2, dispatch=2, pyfunc=inplace_lshift)
501 add_operator('inplace_rshift', 2, dispatch=2, pyfunc=inplace_rshift)
502 add_operator('inplace_and', 2, dispatch=2, pyfunc=inplace_and)
503 add_operator('inplace_or', 2, dispatch=2, pyfunc=inplace_or)
504 add_operator('inplace_xor', 2, dispatch=2, pyfunc=inplace_xor)
505 add_operator('lt', 2, dispatch=2, pure=True)
506 add_operator('le', 2, dispatch=2, pure=True)
507 add_operator('eq', 2, dispatch=2, pure=True)
508 add_operator('ne', 2, dispatch=2, pure=True)
509 add_operator('gt', 2, dispatch=2, pure=True)
510 add_operator('ge', 2, dispatch=2, pure=True)
511 add_operator('cmp', 2, dispatch=2, pyfunc=cmp, pure=True) # rich cmps preferred
512 add_operator('coerce', 2, dispatch=2, pyfunc=coerce, pure=True)
513 add_operator('contains', 2, pure=True)
514 add_operator('get', 3, pyfunc=get, pure=True)
515 add_operator('set', 3, pyfunc=set)
516 add_operator('delete', 2, pyfunc=delete)
517 add_operator('userdel', 1, pyfunc=userdel)
518 add_operator('buffer', 1, pyfunc=buffer, pure=True) # see buffer.py
519 add_operator('yield_', 1)
520 add_operator('newslice', 3)
521 add_operator('hint', None, dispatch=1)
522
523 class Contains(SingleDispatchMixin, PureOperation):
524 opname = 'contains'
525 arity = 2
526 pyfunc = staticmethod(operator.contains)
527
528 # XXX "contains" clashes with SomeObject method
529 @classmethod
530 def get_specialization(cls, s_seq, s_elem):
531 return cls._dispatch(type(s_seq))
532
533
534 class NewDict(HLOperation):
535 opname = 'newdict'
536 canraise = []
537
538 def consider(self, annotator):
539 return annotator.bookkeeper.newdict()
540
541
542 class NewTuple(PureOperation):
543 opname = 'newtuple'
544 pyfunc = staticmethod(lambda *args: args)
545 canraise = []
546
547 def consider(self, annotator):
548 return SomeTuple(items=[annotator.annotation(arg) for arg in self.args])
549
550
551 class NewList(HLOperation):
552 opname = 'newlist'
553 canraise = []
554
555 def consider(self, annotator):
556 return annotator.bookkeeper.newlist(
557 *[annotator.annotation(arg) for arg in self.args])
558
559
560 class NewSlice(HLOperation):
561 opname = 'newslice'
562 canraise = []
563
564 def consider(self, annotator):
565 raise AnnotatorError("Cannot use extended slicing in rpython")
566
567
568 class Pow(PureOperation):
569 opname = 'pow'
570 arity = 3
571 can_overflow = False
572 canraise = []
573 pyfunc = pow
574
575 def __init__(self, w_base, w_exponent, w_mod=const(None)):
576 self.args = [w_base, w_exponent, w_mod]
577 self.result = Variable()
578 self.offset = -1
579
580
581 class Iter(SingleDispatchMixin, HLOperation):
582 opname = 'iter'
583 arity = 1
584 can_overflow = False
585 canraise = []
586 pyfunc = staticmethod(iter)
587
588 def constfold(self):
589 w_iterable, = self.args
590 if isinstance(w_iterable, Constant):
591 iterable = w_iterable.value
592 if isinstance(iterable, unrolling_iterable):
593 return const(iterable.get_unroller())
594
595 class Next(SingleDispatchMixin, HLOperation):
596 opname = 'next'
597 arity = 1
598 can_overflow = False
599 canraise = [StopIteration, RuntimeError]
600 pyfunc = staticmethod(next)
601
602 def eval(self, ctx):
603 w_iter, = self.args
604 if isinstance(w_iter, Constant):
605 it = w_iter.value
606 if isinstance(it, _unroller):
607 try:
608 v, next_unroller = it.step()
609 except IndexError:
610 from rpython.flowspace.flowcontext import Raise
611 raise Raise(const(StopIteration()))
612 else:
613 ctx.replace_in_stack(it, next_unroller)
614 return const(v)
615 return HLOperation.eval(self, ctx)
616
617 class GetAttr(SingleDispatchMixin, HLOperation):
618 opname = 'getattr'
619 arity = 2
620 can_overflow = False
621 canraise = []
622 pyfunc = staticmethod(getattr)
623
624 def constfold(self):
625 from rpython.flowspace.flowcontext import FlowingError
626 if len(self.args) == 3:
627 raise FlowingError(
628 "getattr() with three arguments not supported: %s" % (self,))
629 w_obj, w_name = self.args
630 # handling special things like sys
631 if (w_obj in NOT_REALLY_CONST and
632 w_name not in NOT_REALLY_CONST[w_obj]):
633 return
634 if w_obj.foldable() and w_name.foldable():
635 obj, name = w_obj.value, w_name.value
636 try:
637 result = getattr(obj, name)
638 except Exception as e:
639 etype = e.__class__
640 msg = "getattr(%s, %s) always raises %s: %s" % (
641 obj, name, etype, e)
642 raise FlowingError(msg)
643 try:
644 return const(result)
645 except WrapException:
646 pass
647
648 class CallOp(HLOperation):
649 @property
650 def canraise(self):
651 w_callable = self.args[0]
652 if isinstance(w_callable, Constant):
653 c = w_callable.value
654 if (isinstance(c, (types.BuiltinFunctionType,
655 types.BuiltinMethodType,
656 types.ClassType,
657 types.TypeType)) and
658 c.__module__ in ['__builtin__', 'exceptions']):
659 return builtins_exceptions.get(c, [])
660 # *any* exception for non-builtins
661 return [Exception]
662
663 class SimpleCall(SingleDispatchMixin, CallOp):
664 opname = 'simple_call'
665
666 def eval(self, ctx):
667 w_callable, args_w = self.args[0], self.args[1:]
668 if isinstance(w_callable, Constant):
669 fn = w_callable.value
670 try:
671 sc = SPECIAL_CASES[fn] # TypeError if 'fn' not hashable
672 except (KeyError, TypeError):
673 pass
674 else:
675 return sc(ctx, *args_w)
676 return ctx.do_op(self)
677
678 def build_args(self, args_s):
679 return ArgumentsForTranslation(list(args_s))
680
681
682 class CallArgs(SingleDispatchMixin, CallOp):
683 opname = 'call_args'
684
685 def eval(self, ctx):
686 w_callable = self.args[0]
687 if isinstance(w_callable, Constant):
688 fn = w_callable.value
689 try:
690 sc = SPECIAL_CASES[fn] # TypeError if 'fn' not hashable
691 except (KeyError, TypeError):
692 pass
693 else:
694 from rpython.flowspace.flowcontext import FlowingError
695 raise FlowingError(
696 "should not call %r with keyword arguments" % (fn,))
697 return ctx.do_op(self)
698
699 def build_args(self, args_s):
700 return ArgumentsForTranslation.fromshape(args_s[0].const,
701 list(args_s[1:]))
702
703
704 # Other functions that get directly translated to SpaceOperators
705 func2op[type] = op.type
706 func2op[operator.truth] = op.bool
707 func2op[pow] = op.pow
708 func2op[operator.pow] = op.pow
709 func2op[__builtin__.iter] = op.iter
710 func2op[getattr] = op.getattr
711 func2op[__builtin__.next] = op.next
712
713 for fn, oper in func2op.items():
714 register_flow_sc(fn)(oper.make_sc())
715
716
717 op_appendices = {
718 OverflowError: 'ovf',
719 IndexError: 'idx',
720 KeyError: 'key',
721 ZeroDivisionError: 'zer',
722 ValueError: 'val',
723 }
724
725 # specifying IndexError, and KeyError beyond Exception,
726 # allows the annotator to be more precise, see test_reraiseAnything/KeyError in
727 # the annotator tests
728 op.getitem.canraise = [IndexError, KeyError, Exception]
729 op.getitem_idx.canraise = [IndexError, KeyError, Exception]
730 op.setitem.canraise = [IndexError, KeyError, Exception]
731 op.delitem.canraise = [IndexError, KeyError, Exception]
732 op.contains.canraise = [Exception] # from an r_dict
733
734 def _add_exceptions(names, exc):
735 for name in names.split():
736 oper = getattr(op, name)
737 lis = oper.canraise
738 if exc in lis:
739 raise ValueError("your list is causing duplication!")
740 lis.append(exc)
741 assert exc in op_appendices
742
743 def _add_except_ovf(names):
744 # duplicate exceptions and add OverflowError
745 for name in names.split():
746 oper = getattr(op, name)
747 oper_ovf = getattr(op, name + '_ovf')
748 oper_ovf.canraise = list(oper.canraise)
749 oper_ovf.canraise.append(OverflowError)
750
751 _add_exceptions("""div mod divmod truediv floordiv pow
752 inplace_div inplace_mod inplace_truediv
753 inplace_floordiv inplace_pow""", ZeroDivisionError)
754 _add_exceptions("""pow inplace_pow lshift inplace_lshift rshift
755 inplace_rshift""", ValueError)
756 _add_exceptions("""truediv divmod
757 inplace_add inplace_sub inplace_mul inplace_truediv
758 inplace_floordiv inplace_div inplace_mod inplace_pow
759 inplace_lshift""", OverflowError) # without a _ovf version
760 _add_except_ovf("""neg abs add sub mul
761 floordiv div mod lshift""") # with a _ovf version
762 _add_exceptions("""pow""",
763 OverflowError) # for the float case
764 del _add_exceptions, _add_except_ovf