Debian Codegraph @

rpython/annotator/model.py

raw symbols SCIP
1 """
2 This file defines the 'subset' SomeValue classes.
3
4 An instance of a SomeValue class stands for a Python object that has some
5 known properties, for example that is known to be a list of non-negative
6 integers. Each instance can be considered as an object that is only
7 'partially defined'. Another point of view is that each instance is a
8 generic element in some specific subset of the set of all objects.
9
10 """
11
12 # Old terminology still in use here and there:
13 # SomeValue means one of the SomeXxx classes in this file.
14 # Cell is an instance of one of these classes.
15 #
16 # Think about cells as potato-shaped circles in a diagram:
17 # ______________________________________________________
18 # / SomeObject() \
19 # / ___________________________ ______________ \
20 # | / SomeInteger(nonneg=False) \____ / SomeString() \ \
21 # | / __________________________ \ | | |
22 # | | / SomeInteger(nonneg=True) \ | | "hello" | |
23 # | | | 0 42 _________/ | \______________/ |
24 # | \ -3 \________________/ / |
25 # \ \ -5 _____/ /
26 # \ \________________________/ 3.1416 /
27 # \_____________________________________________________/
28 #
29
30 from __future__ import absolute_import
31
32 import inspect
33 import math
34 import weakref
35 from types import BuiltinFunctionType, MethodType
36 from collections import OrderedDict, defaultdict
37
38 import rpython
39 from rpython.tool import descriptor
40 from rpython.tool.pairtype import pair, extendabletype, doubledispatch
41 from rpython.rlib.rarithmetic import r_uint, base_int, r_singlefloat, r_longfloat
42
43
44 class State(object):
45 # A global attribute :-( Patch it with 'True' to enable checking of
46 # the no_nul attribute...
47 check_str_without_nul = False
48 allow_int_to_float = True
49 TLS = State()
50
51 class SomeObject(object):
52 """The set of all objects. Each instance stands
53 for an arbitrary object about which nothing is known."""
54 __metaclass__ = extendabletype
55 immutable = False
56 knowntype = object
57
58 def __init__(self):
59 assert type(self) is not SomeObject
60
61 def __eq__(self, other):
62 return (self.__class__ is other.__class__ and
63 self.__dict__ == other.__dict__)
64
65 def __ne__(self, other):
66 return not (self == other)
67
68 def __repr__(self):
69 try:
70 reprdict = TLS.reprdict
71 except AttributeError:
72 reprdict = TLS.reprdict = {}
73 if self in reprdict:
74 kwds = '...'
75 else:
76 reprdict[self] = True
77 try:
78 items = self.__dict__.items()
79 items.sort()
80 args = []
81 for k, v in items:
82 m = getattr(self, 'fmt_' + k, repr)
83 r = m(v)
84 if r is not None:
85 args.append('%s=%s' % (k, r))
86 kwds = ', '.join(args)
87 finally:
88 del reprdict[self]
89 return '%s(%s)' % (self.__class__.__name__, kwds)
90
91 def fmt_knowntype(self, t):
92 return t.__name__
93
94 def contains(self, other):
95 if self == other:
96 return True
97 try:
98 return union(self, other) == self
99 except UnionError:
100 return False
101
102 def is_constant(self):
103 d = self.__dict__
104 return 'const' in d or 'const_box' in d
105
106 def is_immutable_constant(self):
107 return self.immutable and 'const' in self.__dict__
108
109 # delegate accesses to 'const' to accesses to 'const_box.value',
110 # where const_box is a Constant. This is not a property, in order
111 # to allow 'self.const = xyz' to work as well.
112 class ConstAccessDelegator(object):
113 def __get__(self, obj, cls=None):
114 return obj.const_box.value
115 const = ConstAccessDelegator()
116 del ConstAccessDelegator
117
118 def can_be_none(self):
119 return True
120
121 def noneify(self):
122 raise UnionError(self, s_None)
123
124 def nonnoneify(self):
125 return self
126
127 @doubledispatch
128 def intersection(s_obj1, s_obj2):
129 """Return the intersection of two annotations, or an over-approximation thereof"""
130 raise NotImplementedError
131
132 @doubledispatch
133 def difference(s_obj1, s_obj2):
134 """Return the set difference of two annotations, or an over-approximation thereof"""
135 raise NotImplementedError
136
137
138 class SomeType(SomeObject):
139 "Stands for a type. We might not be sure which one it is."
140 knowntype = type
141 immutable = True
142
143 def can_be_none(self):
144 return False
145
146 class SomeTypeOf(SomeType):
147 """The type of a variable"""
148 def __init__(self, args_v):
149 self.is_type_of = args_v
150
151 def typeof(args_v):
152 if args_v:
153 result = SomeTypeOf(args_v)
154 if len(args_v) == 1:
155 s_arg = args_v[0].annotation
156 if isinstance(s_arg, SomeException) and len(s_arg.classdefs) == 1:
157 cdef, = s_arg.classdefs
158 result.const = cdef.classdesc.pyobj
159 return result
160 else:
161 return SomeType()
162
163
164 class SomeFloat(SomeObject):
165 "Stands for a float or an integer."
166 knowntype = float # if we don't know if it's a float or an int,
167 # pretend it's a float.
168 immutable = True
169
170 def __eq__(self, other):
171 if (type(self) is SomeFloat and type(other) is SomeFloat and
172 self.is_constant() and other.is_constant()):
173 # NaN unpleasantness.
174 if math.isnan(self.const) and math.isnan(other.const):
175 return True
176 # 0.0 vs -0.0 unpleasantness.
177 if not self.const and not other.const:
178 return math.copysign(1., self.const) == math.copysign(1., other.const)
179 #
180 return super(SomeFloat, self).__eq__(other)
181
182 def can_be_none(self):
183 return False
184
185
186 class SomeSingleFloat(SomeObject):
187 "Stands for an r_singlefloat."
188 # No operation supported, not even union with a regular float
189 knowntype = r_singlefloat
190 immutable = True
191
192 def can_be_none(self):
193 return False
194
195
196 class SomeLongFloat(SomeObject):
197 "Stands for an r_longfloat."
198 # No operation supported, not even union with a regular float
199 knowntype = r_longfloat
200 immutable = True
201
202 def can_be_none(self):
203 return False
204
205
206 class SomeInteger(SomeFloat):
207 "Stands for an object which is known to be an integer."
208 knowntype = int
209
210 # size is in multiples of C's sizeof(long)!
211 def __init__(self, nonneg=False, unsigned=None, knowntype=None):
212 assert (knowntype is None or knowntype is int or
213 issubclass(knowntype, base_int))
214 if knowntype is None:
215 if unsigned:
216 knowntype = r_uint
217 else:
218 knowntype = int
219 elif unsigned is not None:
220 raise TypeError('Conflicting specification for SomeInteger')
221 self.knowntype = knowntype
222 unsigned = self.knowntype(-1) > 0
223 self.nonneg = unsigned or nonneg
224 self.unsigned = unsigned # rpython.rlib.rarithmetic.r_uint
225
226
227 class SomeBool(SomeInteger):
228 "Stands for true or false."
229 knowntype = bool
230 nonneg = True
231 unsigned = False
232
233 def __init__(self):
234 pass
235
236 def set_knowntypedata(self, knowntypedata):
237 assert not hasattr(self, 'knowntypedata')
238 for key, value in knowntypedata.items():
239 if not value:
240 del knowntypedata[key]
241 if knowntypedata:
242 self.knowntypedata = knowntypedata
243
244
245 class SomeStringOrUnicode(SomeObject):
246 """Base class for shared implementation of SomeString,
247 SomeUnicodeString and SomeByteArray.
248
249 Cannot be an annotation."""
250
251 immutable = True
252 can_be_None = False
253 no_nul = False # No NUL character in the string.
254
255 def __init__(self, can_be_None=False, no_nul=False):
256 assert type(self) is not SomeStringOrUnicode
257 if can_be_None:
258 self.can_be_None = True
259 if no_nul:
260 assert self.immutable #'no_nul' cannot be used with SomeByteArray
261 self.no_nul = True
262
263 def can_be_none(self):
264 return self.can_be_None
265
266 def __eq__(self, other):
267 if self.__class__ is not other.__class__:
268 return False
269 d1 = self.__dict__
270 d2 = other.__dict__
271 if not TLS.check_str_without_nul:
272 d1 = d1.copy()
273 d1['no_nul'] = 0
274 d2 = d2.copy()
275 d2['no_nul'] = 0
276 return d1 == d2
277
278 def nonnoneify(self):
279 return self.__class__(can_be_None=False, no_nul=self.no_nul)
280
281 def nonnulify(self):
282 if self.can_be_None:
283 return self.__class__(can_be_None=True, no_nul=True)
284 else:
285 return self.__class__(no_nul=True)
286
287
288 class SomeString(SomeStringOrUnicode):
289 "Stands for an object which is known to be a string."
290 knowntype = str
291
292 def noneify(self):
293 return SomeString(can_be_None=True, no_nul=self.no_nul)
294
295
296 class SomeUnicodeString(SomeStringOrUnicode):
297 "Stands for an object which is known to be an unicode string"
298 knowntype = unicode
299
300 def noneify(self):
301 return SomeUnicodeString(can_be_None=True, no_nul=self.no_nul)
302
303
304 class SomeByteArray(SomeStringOrUnicode):
305 immutable = False
306 knowntype = bytearray
307
308
309 class SomeChar(SomeString):
310 "Stands for an object known to be a string of length 1."
311 can_be_None = False
312
313 def __init__(self, no_nul=False): # no 'can_be_None' argument here
314 if no_nul:
315 self.no_nul = True
316
317
318 class SomeUnicodeCodePoint(SomeUnicodeString):
319 "Stands for an object known to be a unicode codepoint."
320 can_be_None = False
321
322 def __init__(self, no_nul=False): # no 'can_be_None' argument here
323 if no_nul:
324 self.no_nul = True
325
326 SomeString.basestringclass = SomeString
327 SomeString.basecharclass = SomeChar
328 SomeUnicodeString.basestringclass = SomeUnicodeString
329 SomeUnicodeString.basecharclass = SomeUnicodeCodePoint
330
331
332 class SomeList(SomeObject):
333 "Stands for a homogenous list of any length."
334 knowntype = list
335
336 def __init__(self, listdef):
337 self.listdef = listdef
338
339 def __eq__(self, other):
340 if self.__class__ is not other.__class__:
341 return False
342 if not self.listdef.same_as(other.listdef):
343 return False
344 selfdic = self.__dict__.copy()
345 otherdic = other.__dict__.copy()
346 del selfdic['listdef']
347 del otherdic['listdef']
348 return selfdic == otherdic
349
350 def can_be_none(self):
351 return True
352
353 def noneify(self):
354 return SomeList(self.listdef)
355
356
357 class SomeTuple(SomeObject):
358 "Stands for a tuple of known length."
359 knowntype = tuple
360 immutable = True
361
362 def __init__(self, items):
363 self.items = tuple(items) # tuple of s_xxx elements
364 for i in items:
365 if not i.is_constant():
366 break
367 else:
368 self.const = tuple([i.const for i in items])
369
370 def can_be_none(self):
371 return False
372
373
374 class SomeDict(SomeObject):
375 "Stands for a dict."
376 knowntype = dict
377
378 def __init__(self, dictdef):
379 self.dictdef = dictdef
380
381 def __eq__(self, other):
382 if self.__class__ is not other.__class__:
383 return False
384 if not self.dictdef.same_as(other.dictdef):
385 return False
386 selfdic = self.__dict__.copy()
387 otherdic = other.__dict__.copy()
388 del selfdic['dictdef']
389 del otherdic['dictdef']
390 return selfdic == otherdic
391
392 def can_be_none(self):
393 return True
394
395 def fmt_const(self, const):
396 if len(const) < 20:
397 return repr(const)
398 else:
399 return '{...%s...}' % (len(const),)
400
401 def noneify(self):
402 return type(self)(self.dictdef)
403
404 class SomeOrderedDict(SomeDict):
405 knowntype = OrderedDict
406
407 def method_copy(dct):
408 return SomeOrderedDict(dct.dictdef)
409
410 def method_update(dct1, dct2):
411 if s_None.contains(dct2):
412 return SomeImpossibleValue()
413 assert isinstance(dct2, SomeOrderedDict), "OrderedDict.update(dict) not allowed"
414 dct1.dictdef.union(dct2.dictdef)
415
416 SomeDict = SomeOrderedDict # all dicts are ordered!
417
418
419 class SomeIterator(SomeObject):
420 "Stands for an iterator returning objects from a given container."
421 knowntype = type(iter([])) # arbitrarily chose seqiter as the type
422
423 def __init__(self, s_container, *variant):
424 self.variant = variant
425 self.s_container = s_container
426
427 def can_be_none(self):
428 return False
429
430
431 class SomeInstance(SomeObject):
432 "Stands for an instance of a (user-defined) class."
433
434 def __init__(self, classdef, can_be_None=False, flags={}):
435 self.classdef = classdef
436 self.knowntype = classdef.classdesc if classdef else None
437 self.can_be_None = can_be_None
438 self.flags = flags
439
440 def fmt_knowntype(self, kt):
441 return None
442
443 def fmt_classdef(self, cdef):
444 if cdef is None:
445 return 'object'
446 else:
447 return cdef.name
448
449 def fmt_flags(self, flags):
450 if flags:
451 return repr(flags)
452 else:
453 return None
454
455 def can_be_none(self):
456 return self.can_be_None
457
458 def nonnoneify(self):
459 return SomeInstance(self.classdef, can_be_None=False)
460
461 def noneify(self):
462 return SomeInstance(self.classdef, can_be_None=True)
463
464 @intersection.register(SomeInstance, SomeInstance)
465 def intersection_Instance(s_inst1, s_inst2):
466 can_be_None = s_inst1.can_be_None and s_inst2.can_be_None
467 if s_inst1.classdef.issubclass(s_inst2.classdef):
468 return SomeInstance(s_inst1.classdef, can_be_None=can_be_None)
469 elif s_inst2.classdef.issubclass(s_inst1.classdef):
470 return SomeInstance(s_inst2.classdef, can_be_None=can_be_None)
471 else:
472 return s_ImpossibleValue
473
474 @difference.register(SomeInstance, SomeInstance)
475 def difference_Instance_Instance(s_inst1, s_inst2):
476 if s_inst1.classdef.issubclass(s_inst2.classdef):
477 return s_ImpossibleValue
478 else:
479 return s_inst1
480
481
482 class SomeException(SomeObject):
483 """The set of exceptions obeying type(exc) in self.classes"""
484 def __init__(self, classdefs):
485 self.classdefs = classdefs
486
487 def can_be_none(self):
488 return False
489
490 def as_SomeInstance(self):
491 return unionof(*[SomeInstance(cdef) for cdef in self.classdefs])
492
493 @intersection.register(SomeException, SomeInstance)
494 def intersection_Exception_Instance(s_exc, s_inst):
495 classdefs = {c for c in s_exc.classdefs if c.issubclass(s_inst.classdef)}
496 if classdefs:
497 return SomeException(classdefs)
498 else:
499 return s_ImpossibleValue
500
501 @intersection.register(SomeInstance, SomeException)
502 def intersection_Exception_Instance(s_inst, s_exc):
503 return intersection(s_exc, s_inst)
504
505 @difference.register(SomeException, SomeInstance)
506 def difference_Exception_Instance(s_exc, s_inst):
507 classdefs = {c for c in s_exc.classdefs
508 if not c.issubclass(s_inst.classdef)}
509 if classdefs:
510 return SomeException(classdefs)
511 else:
512 return s_ImpossibleValue
513
514 class SomePBC(SomeObject):
515 """Stands for a global user instance, built prior to the analysis,
516 or a set of such instances."""
517 immutable = True
518
519 def __init__(self, descriptions, can_be_None=False, subset_of=None):
520 assert descriptions
521 # descriptions is a set of Desc instances
522 descriptions = set(descriptions)
523 self.descriptions = descriptions
524 self.can_be_None = can_be_None
525 self.subset_of = subset_of
526 self.simplify()
527 knowntype = reduce(commonbase, [x.knowntype for x in descriptions])
528 if knowntype == type(Exception):
529 knowntype = type
530 if knowntype != object:
531 self.knowntype = knowntype
532 if len(descriptions) == 1 and not can_be_None:
533 # hack for the convenience of direct callers to SomePBC():
534 # only if there is a single object in descriptions
535 desc, = descriptions
536 if desc.pyobj is not None:
537 self.const = desc.pyobj
538 elif len(descriptions) > 1:
539 from rpython.annotator.classdesc import ClassDesc
540 from rpython.annotator.description import MethodOfFrozenDesc
541 kind = self.getKind()
542 if kind is ClassDesc:
543 # a PBC of several classes: enforce them all to be
544 # built, without support for specialization. See
545 # rpython/test/test_rpbc.test_pbc_of_classes_not_all_used
546 for desc in descriptions:
547 desc.getuniqueclassdef()
548 elif kind is MethodOfFrozenDesc:
549 funcdescs = set(desc.funcdesc for desc in descriptions)
550 if len(funcdescs) > 1:
551 raise AnnotatorError(
552 "You can't mix a set of methods on a frozen PBC in "
553 "RPython that are different underlying functions")
554
555 def any_description(self):
556 return iter(self.descriptions).next()
557
558 def getKind(self):
559 "Return the common Desc class of all descriptions in this PBC."
560 kinds = set()
561 for x in self.descriptions:
562 assert type(x).__name__.endswith('Desc') # avoid import nightmares
563 kinds.add(x.__class__)
564 if len(kinds) > 1:
565 raise AnnotatorError("mixing several kinds of PBCs: %r" % kinds)
566 return kinds.pop()
567
568 def simplify(self):
569 # We check that the set only contains a single kind of Desc instance
570 kind = self.getKind()
571 # then we remove unnecessary entries in self.descriptions:
572 # some MethodDescs can be 'shadowed' by others
573 if len(self.descriptions) > 1:
574 kind.simplify_desc_set(self.descriptions)
575
576 def consider_call_site(self, args, s_result, call_op):
577 descs = list(self.descriptions)
578 self.getKind().consider_call_site(descs, args, s_result, call_op)
579
580 def can_be_none(self):
581 return self.can_be_None
582
583 def nonnoneify(self):
584 return SomePBC(self.descriptions, can_be_None=False,
585 subset_of=self.subset_of)
586
587 def noneify(self):
588 return SomePBC(self.descriptions, can_be_None=True,
589 subset_of=self.subset_of)
590
591 def fmt_descriptions(self, pbis):
592 if hasattr(self, 'const'):
593 return None
594 else:
595 return '{...%s...}' % (len(pbis),)
596
597 def fmt_knowntype(self, kt):
598 if self.is_constant():
599 return None
600 else:
601 return kt.__name__
602
603 class SomeNone(SomeObject):
604 knowntype = type(None)
605 const = None
606
607 def __init__(self):
608 pass
609
610 def is_constant(self):
611 return True
612
613 def is_immutable_constant(self):
614 return True
615
616 def nonnoneify(self):
617 return s_ImpossibleValue
618
619
620 class SomeConstantType(SomePBC):
621 can_be_None = False
622 subset_of = None
623 def __init__(self, x, bk):
624 self.descriptions = set([bk.getdesc(x)])
625 self.knowntype = type(x)
626 self.const = x
627
628
629 class SomeBuiltin(SomeObject):
630 "Stands for a built-in function or method with special-cased analysis."
631 knowntype = BuiltinFunctionType # == BuiltinMethodType
632 immutable = True
633
634 def __init__(self, analyser, s_self=None, methodname=None):
635 if isinstance(analyser, MethodType):
636 analyser = descriptor.InstanceMethod(
637 analyser.im_func,
638 analyser.im_self,
639 analyser.im_class)
640 self.analyser = analyser
641 self.s_self = s_self
642 self.methodname = methodname
643
644 def can_be_none(self):
645 return False
646
647
648 class SomeBuiltinMethod(SomeBuiltin):
649 """ Stands for a built-in method which has got special meaning
650 """
651 def __init__(self, analyser, s_self, methodname):
652 if isinstance(analyser, MethodType):
653 analyser = descriptor.InstanceMethod(
654 analyser.im_func,
655 analyser.im_self,
656 analyser.im_class)
657 self.analyser = analyser
658 self.s_self = s_self
659 self.methodname = methodname
660
661
662 class SomeImpossibleValue(SomeObject):
663 """The empty set. Instances are placeholders for objects that
664 will never show up at run-time, e.g. elements of an empty list."""
665 immutable = True
666 annotationcolor = (160, 160, 160)
667
668 def can_be_none(self):
669 return False
670
671
672 class SomeProperty(SomeObject):
673 # used for union error only
674 immutable = True
675 knowntype = type(property)
676
677 def __init__(self, prop):
678 self.fget = prop.fget
679 self.fset = prop.fset
680
681 def can_be_none(self):
682 return False
683
684
685 s_None = SomeNone()
686 s_Bool = SomeBool()
687 s_True = SomeBool()
688 s_True.const = True
689 s_False = SomeBool()
690 s_False.const = False
691 s_Int = SomeInteger()
692 s_ImpossibleValue = SomeImpossibleValue()
693 s_Str0 = SomeString(no_nul=True)
694 s_Unicode0 = SomeUnicodeString(no_nul=True)
695
696
697 # ____________________________________________________________
698 # weakrefs
699
700 class SomeWeakRef(SomeObject):
701 knowntype = weakref.ReferenceType
702 immutable = True
703
704 def __init__(self, classdef):
705 # 'classdef' is None for known-to-be-dead weakrefs.
706 self.classdef = classdef
707
708 def noneify(self):
709 return SomeWeakRef(self.classdef)
710
711 # ____________________________________________________________
712
713
714 class AnnotatorError(Exception):
715 def __init__(self, msg=None):
716 self.msg = msg
717 self.source = None
718
719 def __str__(self):
720 s = "\n\n%s" % self.msg
721 if self.source is not None:
722 s += "\n\n"
723 s += self.source
724
725 return s
726
727 class UnionError(AnnotatorError):
728 """Signals an suspicious attempt at taking the union of
729 deeply incompatible SomeXxx instances."""
730
731 def __init__(self, s_obj1, s_obj2, msg=None):
732 """
733 This exception expresses the fact that s_obj1 and s_obj2 cannot be unified.
734 The msg paramter is appended to a generic message. This can be used to
735 give the user a little more information.
736 """
737 s = ""
738 if msg is not None:
739 s += "%s\n\n" % msg
740 s += "Offending annotations:\n"
741 s += " %s\n %s" % (s_obj1, s_obj2)
742 self.s_obj1 = s_obj1
743 self.s_obj2 = s_obj2
744 self.msg = s
745 self.source = None
746
747 def __repr__(self):
748 return str(self)
749
750 def union(s1, s2):
751 """The join operation in the lattice of annotations.
752
753 It is the most precise SomeObject instance that contains both arguments.
754
755 union() is (supposed to be) idempotent, commutative, associative and has
756 no side-effects.
757 """
758 try:
759 TLS.no_side_effects_in_union += 1
760 except AttributeError:
761 TLS.no_side_effects_in_union = 1
762 try:
763 if s1 == s2:
764 # Most pair(...).union() methods deal incorrectly with that case
765 # when constants are involved.
766 return s1
767 return pair(s1, s2).union()
768 finally:
769 TLS.no_side_effects_in_union -= 1
770
771 def unionof(*somevalues):
772 "The most precise SomeValue instance that contains all the values."
773 try:
774 s1, s2 = somevalues
775 except ValueError:
776 s1 = s_ImpossibleValue
777 for s2 in somevalues:
778 if s1 != s2:
779 s1 = pair(s1, s2).union()
780 else:
781 # See comment in union() above
782 if s1 != s2:
783 s1 = pair(s1, s2).union()
784 return s1
785
786
787 # make knowntypedata dictionary
788
789 def add_knowntypedata(ktd, truth, vars, s_obj):
790 for v in vars:
791 ktd[truth][v] = s_obj
792
793
794 def merge_knowntypedata(ktd1, ktd2):
795 r = defaultdict(dict)
796 for truth, constraints in ktd1.items():
797 for v in constraints:
798 if truth in ktd2 and v in ktd2[truth]:
799 r[truth][v] = unionof(ktd1[truth][v], ktd2[truth][v])
800 return r
801
802
803 def not_const(s_obj):
804 if s_obj.is_constant() and not isinstance(s_obj, (SomePBC, SomeNone)):
805 new_s_obj = SomeObject.__new__(s_obj.__class__)
806 dic = new_s_obj.__dict__ = s_obj.__dict__.copy()
807 if 'const' in dic:
808 del new_s_obj.const
809 else:
810 del new_s_obj.const_box
811 s_obj = new_s_obj
812 return s_obj
813
814
815 # ____________________________________________________________
816 # internal
817
818 def commonbase(cls1, cls2): # XXX single inheritance only XXX hum
819 l1 = inspect.getmro(cls1)
820 l2 = inspect.getmro(cls2)
821 if l1[-1] != object:
822 l1 = l1 + (object,)
823 if l2[-1] != object:
824 l2 = l2 + (object,)
825 for x in l1:
826 if x in l2:
827 return x
828 assert 0, "couldn't get to commonbase of %r and %r" % (cls1, cls2)
829
830
831 class HarmlesslyBlocked(Exception):
832 """Raised by the unaryop/binaryop to signal a harmless kind of
833 BlockedInference: the current block is blocked, but not in a way
834 that gives 'Blocked block' errors at the end of annotation."""
835
836
837 def read_can_only_throw(opimpl, *args):
838 can_only_throw = getattr(opimpl, "can_only_throw", None)
839 if can_only_throw is None or isinstance(can_only_throw, list):
840 return can_only_throw
841 return can_only_throw(*args)
842
843 #
844 # safety check that no-one is trying to make annotation and translation
845 # faster by providing the -O option to Python.
846 import os
847 if "WINGDB_PYTHON" not in os.environ:
848 # ...but avoiding this boring check in the IDE
849 try:
850 assert False
851 except AssertionError:
852 pass # fine
853 else:
854 raise RuntimeError("The annotator relies on 'assert' statements from the\n"
855 "\tannotated program: you cannot run it with 'python -O'.")