Debian Codegraph @

rpython/annotator/binaryop.py

raw symbols SCIP
1 """
2 Binary operations between SomeValues.
3 """
4 from collections import defaultdict
5
6 from rpython.tool.pairtype import pair, pairtype
7 from rpython.annotator.model import (
8 SomeObject, SomeInteger, SomeBool, s_Bool, SomeString, SomeChar, SomeList,
9 SomeDict, SomeUnicodeCodePoint, SomeUnicodeString, SomeException,
10 SomeTuple, SomeImpossibleValue, s_ImpossibleValue, SomeInstance,
11 SomeBuiltinMethod, SomeIterator, SomePBC, SomeNone, SomeFloat, s_None,
12 SomeByteArray, SomeWeakRef, SomeSingleFloat,
13 SomeLongFloat, SomeType, SomeTypeOf, SomeConstantType, unionof, UnionError,
14 union, read_can_only_throw, add_knowntypedata,
15 merge_knowntypedata,)
16 from rpython.annotator.bookkeeper import immutablevalue, getbookkeeper
17 from rpython.flowspace.model import Variable, Constant, const
18 from rpython.flowspace.operation import op
19 from rpython.rlib import rarithmetic
20 from rpython.annotator.model import AnnotatorError, TLS
21
22 BINARY_OPERATIONS = set([oper.opname for oper in op.__dict__.values()
23 if oper.dispatch == 2])
24
25
26 @op.is_.register(SomeObject, SomeObject)
27 def is__default(annotator, obj1, obj2):
28 r = SomeBool()
29 s_obj1 = annotator.annotation(obj1)
30 s_obj2 = annotator.annotation(obj2)
31 if s_obj2.is_constant():
32 if s_obj1.is_constant():
33 r.const = s_obj1.const is s_obj2.const
34 if s_obj2.const is None and not s_obj1.can_be_none():
35 r.const = False
36 elif s_obj1.is_constant():
37 if s_obj1.const is None and not s_obj2.can_be_none():
38 r.const = False
39 knowntypedata = defaultdict(dict)
40 bk = annotator.bookkeeper
41
42 def bind(src_obj, tgt_obj):
43 s_src = annotator.annotation(src_obj)
44 s_tgt = annotator.annotation(tgt_obj)
45 if hasattr(s_tgt, 'is_type_of') and s_src.is_constant():
46 add_knowntypedata(
47 knowntypedata, True,
48 s_tgt.is_type_of,
49 bk.valueoftype(s_src.const))
50 add_knowntypedata(knowntypedata, True, [tgt_obj], s_src)
51 s_nonnone = s_tgt
52 if (s_src.is_constant() and s_src.const is None and
53 s_tgt.can_be_none()):
54 s_nonnone = s_tgt.nonnoneify()
55 add_knowntypedata(knowntypedata, False, [tgt_obj], s_nonnone)
56
57 bind(obj2, obj1)
58 bind(obj1, obj2)
59 r.set_knowntypedata(knowntypedata)
60 return r
61
62 def _make_cmp_annotator_default(cmp_op):
63 @cmp_op.register(SomeObject, SomeObject)
64 def default_annotate(annotator, obj1, obj2):
65 s_1, s_2 = annotator.annotation(obj1), annotator.annotation(obj2)
66 if s_1.is_immutable_constant() and s_2.is_immutable_constant():
67 return immutablevalue(cmp_op.pyfunc(s_1.const, s_2.const))
68 else:
69 return s_Bool
70
71 for cmp_op in [op.lt, op.le, op.eq, op.ne, op.gt, op.ge]:
72 _make_cmp_annotator_default(cmp_op)
73
74 @op.getitem.register(SomeObject, SomeObject)
75 def getitem_default(ann, v_obj, v_index):
76 return s_ImpossibleValue
77
78 def _getitem_can_only_throw(s_c1, s_o2):
79 impl = op.getitem.get_specialization(s_c1, s_o2)
80 return read_can_only_throw(impl, s_c1, s_o2)
81
82 @op.getitem_idx.register(SomeObject, SomeObject)
83 def getitem_idx(ann, v_obj, v_index):
84 s_obj = ann.annotation(v_obj)
85 s_index = ann.annotation(v_index)
86 impl = op.getitem.get_specialization(s_obj, s_index)
87 return impl(ann, v_obj, v_index)
88 getitem_idx.can_only_throw = _getitem_can_only_throw
89
90 class __extend__(pairtype(SomeObject, SomeObject)):
91
92 def union((obj1, obj2)):
93 raise UnionError(obj1, obj2)
94
95 # inplace_xxx ---> xxx by default
96 def inplace_add((obj1, obj2)): return pair(obj1, obj2).add()
97 def inplace_sub((obj1, obj2)): return pair(obj1, obj2).sub()
98 def inplace_mul((obj1, obj2)): return pair(obj1, obj2).mul()
99 def inplace_truediv((obj1, obj2)): return pair(obj1, obj2).truediv()
100 def inplace_floordiv((obj1, obj2)): return pair(obj1, obj2).floordiv()
101 def inplace_div((obj1, obj2)): return pair(obj1, obj2).div()
102 def inplace_mod((obj1, obj2)): return pair(obj1, obj2).mod()
103 def inplace_lshift((obj1, obj2)): return pair(obj1, obj2).lshift()
104 def inplace_rshift((obj1, obj2)): return pair(obj1, obj2).rshift()
105 def inplace_and((obj1, obj2)): return pair(obj1, obj2).and_()
106 def inplace_or((obj1, obj2)): return pair(obj1, obj2).or_()
107 def inplace_xor((obj1, obj2)): return pair(obj1, obj2).xor()
108
109 for name, func in locals().items():
110 if name.startswith('inplace_'):
111 func.can_only_throw = []
112
113 inplace_div.can_only_throw = [ZeroDivisionError]
114 inplace_truediv.can_only_throw = [ZeroDivisionError]
115 inplace_floordiv.can_only_throw = [ZeroDivisionError]
116 inplace_mod.can_only_throw = [ZeroDivisionError]
117
118 def cmp((obj1, obj2)):
119 if obj1.is_immutable_constant() and obj2.is_immutable_constant():
120 return immutablevalue(cmp(obj1.const, obj2.const))
121 else:
122 return SomeInteger()
123
124 def divmod((obj1, obj2)):
125 return SomeTuple([pair(obj1, obj2).div(), pair(obj1, obj2).mod()])
126
127 def coerce((obj1, obj2)):
128 return pair(obj1, obj2).union() # reasonable enough
129
130 def add((obj1, obj2)):
131 return s_ImpossibleValue
132 sub = mul = truediv = floordiv = div = mod = add
133 lshift = rshift = and_ = or_ = xor = delitem = add
134
135 def setitem((obj1, obj2), _):
136 return s_ImpossibleValue
137
138 # approximation of an annotation intersection, the result should be the annotation obj or
139 # the intersection of obj and improvement
140 def improve((obj, improvement)):
141 if not improvement.contains(obj) and obj.contains(improvement):
142 return improvement
143 else:
144 return obj
145
146
147
148 class __extend__(pairtype(SomeType, SomeType),
149 pairtype(SomeType, SomeConstantType),
150 pairtype(SomeConstantType, SomeType),):
151
152 def union((obj1, obj2)):
153 result = SomeType()
154 if obj1.is_immutable_constant() and obj2.is_immutable_constant() and obj1.const == obj2.const:
155 result.const = obj1.const
156 return result
157
158 class __extend__(pairtype(SomeTypeOf, SomeTypeOf)):
159 def union((s_obj1, s_obj2)):
160 vars = list(set(s_obj1.is_type_of) | set(s_obj2.is_type_of))
161 result = SomeTypeOf(vars)
162 if (s_obj1.is_immutable_constant() and s_obj2.is_immutable_constant()
163 and s_obj1.const == s_obj2.const):
164 result.const = obj1.const
165 return result
166
167 # cloning a function with identical code, for the can_only_throw attribute
168 def _clone(f, can_only_throw = None):
169 newfunc = type(f)(f.__code__, f.__globals__, f.__name__,
170 f.__defaults__, f.__closure__)
171 if can_only_throw is not None:
172 newfunc.can_only_throw = can_only_throw
173 return newfunc
174
175 class __extend__(pairtype(SomeInteger, SomeInteger)):
176 # unsignedness is considered a rare and contagious disease
177
178 def union((int1, int2)):
179 if int1.unsigned == int2.unsigned:
180 knowntype = rarithmetic.compute_restype(int1.knowntype, int2.knowntype)
181 else:
182 t1 = int1.knowntype
183 if t1 is bool:
184 t1 = int
185 t2 = int2.knowntype
186 if t2 is bool:
187 t2 = int
188
189 if t2 is int:
190 if int2.nonneg == False:
191 raise UnionError(int1, int2, "RPython cannot prove that these " + \
192 "integers are of the same signedness")
193 knowntype = t1
194 elif t1 is int:
195 if int1.nonneg == False:
196 raise UnionError(int1, int2, "RPython cannot prove that these " + \
197 "integers are of the same signedness")
198 knowntype = t2
199 else:
200 raise UnionError(int1, int2)
201 return SomeInteger(nonneg=int1.nonneg and int2.nonneg,
202 knowntype=knowntype)
203
204 or_ = xor = add = mul = _clone(union, [])
205 add_ovf = mul_ovf = _clone(union, [OverflowError])
206 div = floordiv = mod = _clone(union, [ZeroDivisionError])
207 div_ovf= floordiv_ovf = mod_ovf = _clone(union, [ZeroDivisionError, OverflowError])
208
209 def truediv((int1, int2)):
210 return SomeFloat()
211 truediv.can_only_throw = [ZeroDivisionError]
212 truediv_ovf = _clone(truediv, [ZeroDivisionError, OverflowError])
213
214 inplace_div = div
215 inplace_truediv = truediv
216
217 def sub((int1, int2)):
218 knowntype = rarithmetic.compute_restype(int1.knowntype, int2.knowntype)
219 return SomeInteger(knowntype=knowntype)
220 sub.can_only_throw = []
221 sub_ovf = _clone(sub, [OverflowError])
222
223 def and_((int1, int2)):
224 knowntype = rarithmetic.compute_restype(int1.knowntype, int2.knowntype)
225 return SomeInteger(nonneg=int1.nonneg or int2.nonneg,
226 knowntype=knowntype)
227 and_.can_only_throw = []
228
229 def lshift((int1, int2)):
230 if isinstance(int1, SomeBool):
231 return SomeInteger()
232 else:
233 return SomeInteger(knowntype=int1.knowntype)
234 lshift.can_only_throw = []
235 lshift_ovf = _clone(lshift, [OverflowError])
236
237 def rshift((int1, int2)):
238 if isinstance(int1, SomeBool):
239 return SomeInteger(nonneg=True)
240 else:
241 return SomeInteger(nonneg=int1.nonneg, knowntype=int1.knowntype)
242 rshift.can_only_throw = []
243
244
245 def _make_cmp_annotator_int(cmp_op):
246 @cmp_op.register(SomeInteger, SomeInteger)
247 def _compare_helper(annotator, int1, int2):
248 r = SomeBool()
249 s_int1, s_int2 = annotator.annotation(int1), annotator.annotation(int2)
250 if s_int1.is_immutable_constant() and s_int2.is_immutable_constant():
251 r.const = cmp_op.pyfunc(s_int1.const, s_int2.const)
252 #
253 # The rest of the code propagates nonneg information between
254 # the two arguments.
255 #
256 # Doing the right thing when int1 or int2 change from signed
257 # to unsigned (r_uint) is almost impossible. See test_intcmp_bug.
258 # Instead, we only deduce constrains on the operands in the
259 # case where they are both signed. In other words, if y is
260 # nonneg then "assert x>=y" will let the annotator know that
261 # x is nonneg too, but it will not work if y is unsigned.
262 #
263 if not (rarithmetic.signedtype(s_int1.knowntype) and
264 rarithmetic.signedtype(s_int2.knowntype)):
265 return r
266 knowntypedata = defaultdict(dict)
267 def tointtype(s_int0):
268 if s_int0.knowntype is bool:
269 return int
270 return s_int0.knowntype
271 if s_int1.nonneg and isinstance(int2, Variable):
272 case = cmp_op.opname in ('lt', 'le', 'eq')
273 add_knowntypedata(knowntypedata, case, [int2],
274 SomeInteger(nonneg=True, knowntype=tointtype(s_int2)))
275 if s_int2.nonneg and isinstance(int1, Variable):
276 case = cmp_op.opname in ('gt', 'ge', 'eq')
277 add_knowntypedata(knowntypedata, case, [int1],
278 SomeInteger(nonneg=True, knowntype=tointtype(s_int1)))
279 r.set_knowntypedata(knowntypedata)
280 # a special case for 'x < 0' or 'x >= 0',
281 # where 0 is a flow graph Constant
282 # (in this case we are sure that it cannot become a r_uint later)
283 if (isinstance(int2, Constant) and
284 type(int2.value) is int and # filter out Symbolics
285 int2.value == 0):
286 if s_int1.nonneg:
287 if cmp_op.opname == 'lt':
288 r.const = False
289 if cmp_op.opname == 'ge':
290 r.const = True
291 return r
292
293 for cmp_op in [op.lt, op.le, op.eq, op.ne, op.gt, op.ge]:
294 _make_cmp_annotator_int(cmp_op)
295
296 class __extend__(pairtype(SomeBool, SomeBool)):
297
298 def union((boo1, boo2)):
299 s = SomeBool()
300 if getattr(boo1, 'const', -1) == getattr(boo2, 'const', -2):
301 s.const = boo1.const
302 if hasattr(boo1, 'knowntypedata') and \
303 hasattr(boo2, 'knowntypedata'):
304 ktd = merge_knowntypedata(boo1.knowntypedata, boo2.knowntypedata)
305 s.set_knowntypedata(ktd)
306 return s
307
308 def and_((boo1, boo2)):
309 s = SomeBool()
310 if boo1.is_constant():
311 if not boo1.const:
312 s.const = False
313 else:
314 return boo2
315 if boo2.is_constant():
316 if not boo2.const:
317 s.const = False
318 return s
319
320 def or_((boo1, boo2)):
321 s = SomeBool()
322 if boo1.is_constant():
323 if boo1.const:
324 s.const = True
325 else:
326 return boo2
327 if boo2.is_constant():
328 if boo2.const:
329 s.const = True
330 return s
331
332 def xor((boo1, boo2)):
333 s = SomeBool()
334 if boo1.is_constant() and boo2.is_constant():
335 s.const = boo1.const ^ boo2.const
336 return s
337
338 class __extend__(pairtype(SomeString, SomeString)):
339
340 def union((str1, str2)):
341 can_be_None = str1.can_be_None or str2.can_be_None
342 no_nul = str1.no_nul and str2.no_nul
343 return SomeString(can_be_None=can_be_None, no_nul=no_nul)
344
345 def add((str1, str2)):
346 # propagate const-ness to help getattr(obj, 'prefix' + const_name)
347 result = SomeString(no_nul=str1.no_nul and str2.no_nul)
348 if str1.is_immutable_constant() and str2.is_immutable_constant():
349 result.const = str1.const + str2.const
350 return result
351
352 class __extend__(pairtype(SomeByteArray, SomeByteArray)):
353 def union((b1, b2)):
354 can_be_None = b1.can_be_None or b2.can_be_None
355 return SomeByteArray(can_be_None=can_be_None)
356
357 def add((b1, b2)):
358 return SomeByteArray()
359
360 class __extend__(pairtype(SomeByteArray, SomeInteger)):
361 def getitem((s_b, s_i)):
362 return SomeInteger()
363
364 def setitem((s_b, s_i), s_i2):
365 assert isinstance(s_i2, SomeInteger)
366
367 class __extend__(pairtype(SomeString, SomeByteArray),
368 pairtype(SomeByteArray, SomeString),
369 pairtype(SomeChar, SomeByteArray),
370 pairtype(SomeByteArray, SomeChar)):
371 def add((b1, b2)):
372 return SomeByteArray()
373
374 class __extend__(pairtype(SomeChar, SomeChar)):
375
376 def union((chr1, chr2)):
377 no_nul = chr1.no_nul and chr2.no_nul
378 return SomeChar(no_nul=no_nul)
379
380
381 class __extend__(pairtype(SomeUnicodeCodePoint, SomeUnicodeCodePoint)):
382 def union((uchr1, uchr2)):
383 no_nul = uchr1.no_nul and uchr2.no_nul
384 return SomeUnicodeCodePoint(no_nul=no_nul)
385
386 class __extend__(pairtype(SomeString, SomeUnicodeString),
387 pairtype(SomeUnicodeString, SomeString)):
388 def mod((str, unistring)):
389 raise AnnotatorError(
390 "string formatting mixing strings and unicode not supported")
391
392
393 class __extend__(pairtype(SomeString, SomeTuple),
394 pairtype(SomeUnicodeString, SomeTuple)):
395 def mod((s_string, s_tuple)):
396 if not s_string.is_constant():
397 raise AnnotatorError("string formatting requires a constant "
398 "string/unicode on the left of '%'")
399 is_string = isinstance(s_string, SomeString)
400 is_unicode = isinstance(s_string, SomeUnicodeString)
401 assert is_string or is_unicode
402 for s_item in s_tuple.items:
403 if (is_unicode and isinstance(s_item, (SomeChar, SomeString)) or
404 is_string and isinstance(s_item, (SomeUnicodeCodePoint,
405 SomeUnicodeString))):
406 raise AnnotatorError(
407 "string formatting mixing strings and unicode not supported")
408 no_nul = s_string.no_nul
409 for s_item in s_tuple.items:
410 if isinstance(s_item, SomeFloat):
411 pass # or s_item is a subclass, like SomeInteger
412 elif (isinstance(s_item, SomeString) or
413 isinstance(s_item, SomeUnicodeString)) and s_item.no_nul:
414 pass
415 else:
416 no_nul = False
417 break
418 return s_string.__class__(no_nul=no_nul)
419
420
421 class __extend__(pairtype(SomeString, SomeObject),
422 pairtype(SomeUnicodeString, SomeObject)):
423
424 def mod((s_string, s_arg)):
425 assert not isinstance(s_arg, SomeTuple)
426 return pair(s_string, SomeTuple([s_arg])).mod()
427
428 class __extend__(pairtype(SomeFloat, SomeFloat)):
429
430 def union((flt1, flt2)):
431 if not TLS.allow_int_to_float:
432 # in this mode, if one of the two is actually the
433 # subclass SomeInteger, complain
434 if isinstance(flt1, SomeInteger) or isinstance(flt2, SomeInteger):
435 raise UnionError(flt1, flt2)
436 return SomeFloat()
437
438 add = sub = mul = union
439
440 def div((flt1, flt2)):
441 return SomeFloat()
442 div.can_only_throw = []
443 truediv = div
444
445 # repeat these in order to copy the 'can_only_throw' attribute
446 inplace_div = div
447 inplace_truediv = truediv
448
449
450 class __extend__(pairtype(SomeSingleFloat, SomeSingleFloat)):
451
452 def union((flt1, flt2)):
453 return SomeSingleFloat()
454
455
456 class __extend__(pairtype(SomeLongFloat, SomeLongFloat)):
457
458 def union((flt1, flt2)):
459 return SomeLongFloat()
460
461
462 class __extend__(pairtype(SomeList, SomeList)):
463
464 def union((lst1, lst2)):
465 return SomeList(lst1.listdef.union(lst2.listdef))
466
467 def add((lst1, lst2)):
468 bk = getbookkeeper()
469 return lst1.listdef.offspring(bk, lst2.listdef)
470
471 def eq((lst1, lst2)):
472 lst1.listdef.agree(getbookkeeper(), lst2.listdef)
473 return s_Bool
474 ne = eq
475
476
477 class __extend__(pairtype(SomeList, SomeObject)):
478
479 def inplace_add((lst1, obj2)):
480 lst1.method_extend(obj2)
481 return lst1
482 inplace_add.can_only_throw = []
483
484 def inplace_mul((lst1, obj2)):
485 lst1.listdef.resize()
486 return lst1
487 inplace_mul.can_only_throw = []
488
489 class __extend__(pairtype(SomeTuple, SomeTuple)):
490
491 def union((tup1, tup2)):
492 if len(tup1.items) != len(tup2.items):
493 raise UnionError(tup1, tup2, "RPython cannot unify tuples of "
494 "different length: %d versus %d" % \
495 (len(tup1.items), len(tup2.items)))
496 else:
497 unions = [unionof(x,y) for x,y in zip(tup1.items, tup2.items)]
498 return SomeTuple(items = unions)
499
500 def add((tup1, tup2)):
501 return SomeTuple(items = tup1.items + tup2.items)
502
503 def eq(tup1tup2):
504 tup1tup2.union()
505 return s_Bool
506 ne = eq
507
508 def lt((tup1, tup2)):
509 raise AnnotatorError("unsupported: (...) < (...)")
510 def le((tup1, tup2)):
511 raise AnnotatorError("unsupported: (...) <= (...)")
512 def gt((tup1, tup2)):
513 raise AnnotatorError("unsupported: (...) > (...)")
514 def ge((tup1, tup2)):
515 raise AnnotatorError("unsupported: (...) >= (...)")
516
517
518 class __extend__(pairtype(SomeDict, SomeDict)):
519
520 def union((dic1, dic2)):
521 assert dic1.__class__ == dic2.__class__
522 return dic1.__class__(dic1.dictdef.union(dic2.dictdef))
523
524 def ne((dic1, dic2)):
525 raise AnnotatorError("dict != dict not implemented")
526
527 def _dict_can_only_throw_keyerror(s_dct, *ignore):
528 if s_dct.dictdef.dictkey.custom_eq_hash:
529 return None # r_dict: can throw anything
530 return [KeyError]
531
532 def _dict_can_only_throw_nothing(s_dct, *ignore):
533 if s_dct.dictdef.dictkey.custom_eq_hash:
534 return None # r_dict: can throw anything
535 return [] # else: no possible exception
536
537 @op.getitem.register(SomeDict, SomeObject)
538 def getitem_SomeDict(annotator, v_dict, v_key):
539 s_dict = annotator.annotation(v_dict)
540 s_key = annotator.annotation(v_key)
541 s_dict.dictdef.generalize_key(s_key)
542 position = annotator.bookkeeper.position_key
543 return s_dict.dictdef.read_value(position)
544 getitem_SomeDict.can_only_throw = _dict_can_only_throw_keyerror
545
546
547 class __extend__(pairtype(SomeDict, SomeObject)):
548
549 def setitem((dic1, obj2), s_value):
550 dic1.dictdef.generalize_key(obj2)
551 dic1.dictdef.generalize_value(s_value)
552 setitem.can_only_throw = _dict_can_only_throw_nothing
553
554 def delitem((dic1, obj2)):
555 dic1.dictdef.generalize_key(obj2)
556 delitem.can_only_throw = _dict_can_only_throw_keyerror
557
558
559 class __extend__(pairtype(SomeTuple, SomeInteger)):
560
561 def getitem((tup1, int2)):
562 if int2.is_immutable_constant():
563 try:
564 return tup1.items[int2.const]
565 except IndexError:
566 return s_ImpossibleValue
567 else:
568 return unionof(*tup1.items)
569 getitem.can_only_throw = [IndexError]
570
571
572 class __extend__(pairtype(SomeList, SomeInteger)):
573
574 def mul((lst1, int2)):
575 bk = getbookkeeper()
576 return lst1.listdef.offspring(bk)
577
578 def getitem((lst1, int2)):
579 position = getbookkeeper().position_key
580 return lst1.listdef.read_item(position)
581 getitem.can_only_throw = []
582
583 def getitem_idx((lst1, int2)):
584 position = getbookkeeper().position_key
585 return lst1.listdef.read_item(position)
586 getitem_idx.can_only_throw = [IndexError]
587
588 def setitem((lst1, int2), s_value):
589 lst1.listdef.mutate()
590 lst1.listdef.generalize(s_value)
591 setitem.can_only_throw = [IndexError]
592
593 def delitem((lst1, int2)):
594 lst1.listdef.resize()
595 delitem.can_only_throw = [IndexError]
596
597 class __extend__(pairtype(SomeString, SomeInteger)):
598
599 def getitem((str1, int2)):
600 return SomeChar(no_nul=str1.no_nul)
601 getitem.can_only_throw = []
602
603 def getitem_idx((str1, int2)):
604 return SomeChar(no_nul=str1.no_nul)
605 getitem_idx.can_only_throw = [IndexError]
606
607 def mul((str1, int2)): # xxx do we want to support this
608 return SomeString(no_nul=str1.no_nul)
609
610 class __extend__(pairtype(SomeUnicodeString, SomeInteger)):
611 def getitem((str1, int2)):
612 return SomeUnicodeCodePoint(no_nul=str1.no_nul)
613 getitem.can_only_throw = []
614
615 def getitem_idx((str1, int2)):
616 return SomeUnicodeCodePoint(no_nul=str1.no_nul)
617 getitem_idx.can_only_throw = [IndexError]
618
619 def mul((str1, int2)): # xxx do we want to support this
620 return SomeUnicodeString(no_nul=str1.no_nul)
621
622 class __extend__(pairtype(SomeInteger, SomeString),
623 pairtype(SomeInteger, SomeUnicodeString)):
624
625 def mul((int1, str2)): # xxx do we want to support this
626 return str2.basestringclass(no_nul=str2.no_nul)
627
628 class __extend__(pairtype(SomeUnicodeCodePoint, SomeUnicodeString),
629 pairtype(SomeUnicodeString, SomeUnicodeCodePoint),
630 pairtype(SomeUnicodeString, SomeUnicodeString)):
631 def union((str1, str2)):
632 can_be_None = str1.can_be_None or str2.can_be_None
633 no_nul = str1.no_nul and str2.no_nul
634 return SomeUnicodeString(can_be_None=can_be_None, no_nul=no_nul)
635
636 def add((str1, str2)):
637 # propagate const-ness to help getattr(obj, 'prefix' + const_name)
638 result = SomeUnicodeString(no_nul=str1.no_nul and str2.no_nul)
639 if str1.is_immutable_constant() and str2.is_immutable_constant():
640 result.const = str1.const + str2.const
641 return result
642
643 for cmp_op in [op.lt, op.le, op.eq, op.ne, op.gt, op.ge]:
644 @cmp_op.register(SomeUnicodeString, SomeString)
645 @cmp_op.register(SomeUnicodeString, SomeChar)
646 @cmp_op.register(SomeString, SomeUnicodeString)
647 @cmp_op.register(SomeChar, SomeUnicodeString)
648 @cmp_op.register(SomeUnicodeCodePoint, SomeString)
649 @cmp_op.register(SomeUnicodeCodePoint, SomeChar)
650 @cmp_op.register(SomeString, SomeUnicodeCodePoint)
651 @cmp_op.register(SomeChar, SomeUnicodeCodePoint)
652 def cmp_str_unicode(annotator, v1, v2):
653 raise AnnotatorError(
654 "Comparing byte strings with unicode strings is not RPython")
655
656
657 class __extend__(pairtype(SomeInteger, SomeList)):
658
659 def mul((int1, lst2)):
660 bk = getbookkeeper()
661 return lst2.listdef.offspring(bk)
662
663
664 class __extend__(pairtype(SomeInstance, SomeInstance)):
665
666 def union((ins1, ins2)):
667 if ins1.classdef is None or ins2.classdef is None:
668 # special case only
669 basedef = None
670 else:
671 basedef = ins1.classdef.commonbase(ins2.classdef)
672 if basedef is None:
673 raise UnionError(ins1, ins2, "RPython cannot unify instances "
674 "with no common base class")
675 flags = ins1.flags
676 if flags:
677 flags = flags.copy()
678 for key, value in flags.items():
679 if key not in ins2.flags or ins2.flags[key] != value:
680 del flags[key]
681 return SomeInstance(basedef,
682 can_be_None=ins1.can_be_None or ins2.can_be_None,
683 flags=flags)
684
685 def improve((ins1, ins2)):
686 if ins1.classdef is None:
687 resdef = ins2.classdef
688 elif ins2.classdef is None:
689 resdef = ins1.classdef
690 else:
691 basedef = ins1.classdef.commonbase(ins2.classdef)
692 if basedef is ins1.classdef:
693 resdef = ins2.classdef
694 elif basedef is ins2.classdef:
695 resdef = ins1.classdef
696 else:
697 if ins1.can_be_None and ins2.can_be_None:
698 return s_None
699 else:
700 return s_ImpossibleValue
701 res = SomeInstance(resdef, can_be_None=ins1.can_be_None and ins2.can_be_None)
702 if ins1.contains(res) and ins2.contains(res):
703 return res # fine
704 else:
705 # this case can occur in the presence of 'const' attributes,
706 # which we should try to preserve. Fall-back...
707 thistype = pairtype(SomeInstance, SomeInstance)
708 return super(thistype, pair(ins1, ins2)).improve()
709
710 class __extend__(
711 pairtype(SomeException, SomeInstance),
712 pairtype(SomeException, SomeNone)):
713 def union((s_exc, s_inst)):
714 return union(s_exc.as_SomeInstance(), s_inst)
715
716 class __extend__(
717 pairtype(SomeInstance, SomeException),
718 pairtype(SomeNone, SomeException)):
719 def union((s_inst, s_exc)):
720 return union(s_exc.as_SomeInstance(), s_inst)
721
722 class __extend__(pairtype(SomeException, SomeException)):
723 def union((s_exc1, s_exc2)):
724 return SomeException(s_exc1.classdefs | s_exc2.classdefs)
725
726
727 @op.getitem.register_transform(SomeInstance, SomeObject)
728 def getitem_SomeInstance(annotator, v_ins, v_idx):
729 get_getitem = op.getattr(v_ins, const('__getitem__'))
730 return [get_getitem, op.simple_call(get_getitem.result, v_idx)]
731
732 @op.setitem.register_transform(SomeInstance, SomeObject)
733 def setitem_SomeInstance(annotator, v_ins, v_idx, v_value):
734 get_setitem = op.getattr(v_ins, const('__setitem__'))
735 return [get_setitem,
736 op.simple_call(get_setitem.result, v_idx, v_value)]
737
738 @op.delitem.register_transform(SomeInstance, SomeObject)
739 def delitem_SomeInstance(annotator, v_ins, v_idx):
740 get_delitem = op.getattr(v_ins, const('__delitem__'))
741 return [get_delitem,
742 op.simple_call(get_delitem.result, v_idx)]
743
744 @op.contains.register_transform(SomeInstance)
745 def contains_SomeInstance(annotator, v_ins, v_idx):
746 get_contains = op.getattr(v_ins, const('__contains__'))
747 return [get_contains, op.simple_call(get_contains.result, v_idx)]
748
749 class __extend__(pairtype(SomeIterator, SomeIterator)):
750
751 def union((iter1, iter2)):
752 s_cont = unionof(iter1.s_container, iter2.s_container)
753 if iter1.variant != iter2.variant:
754 raise UnionError(iter1, iter2,
755 "RPython cannot unify incompatible iterator variants")
756 return SomeIterator(s_cont, *iter1.variant)
757
758
759 class __extend__(pairtype(SomeBuiltinMethod, SomeBuiltinMethod)):
760 def union((bltn1, bltn2)):
761 if (bltn1.analyser != bltn2.analyser or
762 bltn1.methodname != bltn2.methodname):
763 raise UnionError(bltn1, bltn2)
764 s_self = unionof(bltn1.s_self, bltn2.s_self)
765 return SomeBuiltinMethod(bltn1.analyser, s_self,
766 methodname=bltn1.methodname)
767
768 @op.is_.register(SomePBC, SomePBC)
769 def is__PBC_PBC(annotator, pbc1, pbc2):
770 s = is__default(annotator, pbc1, pbc2)
771 if not s.is_constant():
772 s_pbc1 = annotator.annotation(pbc1)
773 s_pbc2 = annotator.annotation(pbc2)
774 if not s_pbc1.can_be_None or not s_pbc2.can_be_None:
775 for desc in s_pbc1.descriptions:
776 if desc in s_pbc2.descriptions:
777 break
778 else:
779 s.const = False # no common desc in the two sets
780 return s
781
782 class __extend__(pairtype(SomePBC, SomePBC)):
783 def union((pbc1, pbc2)):
784 d = pbc1.descriptions.copy()
785 d.update(pbc2.descriptions)
786 return SomePBC(d, can_be_None = pbc1.can_be_None or pbc2.can_be_None)
787
788 class __extend__(pairtype(SomeImpossibleValue, SomeObject)):
789 def union((imp1, obj2)):
790 return obj2
791
792 class __extend__(pairtype(SomeObject, SomeImpossibleValue)):
793 def union((obj1, imp2)):
794 return obj1
795
796 # mixing Nones with other objects
797
798 class __extend__(pairtype(SomeObject, SomeNone)):
799 def union((obj, none)):
800 return obj.noneify()
801
802 class __extend__(pairtype(SomeNone, SomeObject)):
803 def union((none, obj)):
804 return obj.noneify()
805
806 class __extend__(pairtype(SomeImpossibleValue, SomeNone)):
807 def union((imp1, none)):
808 return s_None
809
810 class __extend__(pairtype(SomeNone, SomeImpossibleValue)):
811 def union((none, imp2)):
812 return s_None
813
814
815 class __extend__(pairtype(SomePBC, SomeObject)):
816 def getitem((pbc, o)):
817 raise AnnotatorError("getitem on %r" % pbc)
818
819 def setitem((pbc, o), s_value):
820 raise AnnotatorError("setitem on %r" % pbc)
821
822 class __extend__(pairtype(SomeNone, SomeObject)):
823 def getitem((none, o)):
824 return s_ImpossibleValue
825 getitem.can_only_throw = []
826
827 def setitem((none, o), s_value):
828 return None
829
830 class __extend__(pairtype(SomePBC, SomeString)):
831 def add((pbc, o)):
832 raise AnnotatorError('add on %r' % pbc)
833
834 class __extend__(pairtype(SomeNone, SomeString)):
835 def add((none, o)):
836 return s_ImpossibleValue
837
838 class __extend__(pairtype(SomeString, SomePBC)):
839 def add((o, pbc)):
840 raise AnnotatorError('add on %r' % pbc)
841
842 class __extend__(pairtype(SomeString, SomeNone)):
843 def add((o, none)):
844 return s_ImpossibleValue
845
846 #_________________________________________
847 # weakrefs
848
849 class __extend__(pairtype(SomeWeakRef, SomeWeakRef)):
850 def union((s_wrf1, s_wrf2)):
851 if s_wrf1.classdef is None:
852 basedef = s_wrf2.classdef # s_wrf1 is known to be dead
853 elif s_wrf2.classdef is None:
854 basedef = s_wrf1.classdef # s_wrf2 is known to be dead
855 else:
856 basedef = s_wrf1.classdef.commonbase(s_wrf2.classdef)
857 if basedef is None: # no common base class! complain...
858 raise UnionError(s_wrf1, s_wrf2)
859 return SomeWeakRef(basedef)