Debian Codegraph @

rpython/rlib/test/test_objectmodel.py

raw symbols SCIP
1 from collections import OrderedDict
2 import pytest
3 from rpython.rlib.objectmodel import (
4 r_dict, UnboxedValue, Symbolic, compute_hash, compute_identity_hash,
5 compute_unique_id, current_object_addr_as_int, we_are_translated,
6 prepare_dict_update, reversed_dict, specialize, enforceargs, newlist_hint,
7 resizelist_hint, is_annotation_constant, always_inline, NOT_CONSTANT,
8 iterkeys_with_hash, iteritems_with_hash, contains_with_hash,
9 setitem_with_hash, getitem_with_hash, delitem_with_hash, import_from_mixin,
10 fetch_translated_config, try_inline, delitem_if_value_is, move_to_end,
11 never_allocate, dont_inline, list_get_physical_size,
12 dict_to_switch)
13 from rpython.translator.translator import TranslationContext, graphof
14 from rpython.rtyper.test.tool import BaseRtypingTest
15 from rpython.rtyper.test.test_llinterp import interpret, LLException, gengraph
16 from rpython.conftest import option
17
18 def strange_key_eq(key1, key2):
19 return key1[0] == key2[0] # only the 1st character is relevant
20 def strange_key_hash(key):
21 return ord(key[0])
22
23 def play_with_r_dict(d):
24 d['hello'] = 41
25 d['hello'] = 42
26 assert d['hi there'] == 42
27 try:
28 unexpected = d["dumb"]
29 except KeyError:
30 pass
31 else:
32 assert False, "should have raised, got %s" % unexpected
33 assert len(d) == 1
34 assert 'oops' not in d
35
36 count = 0
37 for x in d:
38 assert x == 'hello'
39 count += 1
40 assert count == 1
41
42 assert d.get('hola', -1) == 42
43 assert d.get('salut', -1) == -1
44 d1 = d.copy()
45 del d['hu!']
46 assert len(d) == 0
47 assert d1.keys() == ['hello']
48 d.update(d1)
49 assert d.values() == [42]
50 lst = d.items()
51 assert len(lst) == 1 and len(lst[0]) == 2
52 assert lst[0][0] == 'hello' and lst[0][1] == 42
53
54 count = 0
55 for x in d.iterkeys():
56 assert x == 'hello'
57 count += 1
58 assert count == 1
59
60 count = 0
61 for x in d.itervalues():
62 assert x == 42
63 count += 1
64 assert count == 1
65
66 count = 0
67 for x in d.iteritems():
68 assert len(x) == 2 and x[0] == 'hello' and x[1] == 42
69 count += 1
70 assert count == 1
71
72 d.clear()
73 assert d.keys() == []
74 return True # for the tests below
75
76
77 def test_recursive_r_dict_repr():
78 import operator
79 rdic = r_dict(operator.eq, hash)
80 rdic['x'] = rdic
81 assert str(rdic) == "r_dict({'x': r_dict({...})})"
82 assert repr(rdic) == "r_dict({'x': r_dict({...})})"
83
84 def func_r_dict():
85 # NB. this test function is also annotated/rtyped by the next tests
86 d = r_dict(strange_key_eq, strange_key_hash)
87 return play_with_r_dict(d)
88
89 class Strange:
90 def key_eq(strange, key1, key2):
91 return key1[0] == key2[0] # only the 1st character is relevant
92
93 def key_hash(strange, key):
94 return ord(key[0])
95
96 def func_r_dict_bm():
97 # NB. this test function is also annotated by the next tests
98 strange = Strange()
99 d = r_dict(strange.key_eq, strange.key_hash)
100 return play_with_r_dict(d)
101
102 def test_annotate_r_dict():
103 t = TranslationContext()
104 a = t.buildannotator()
105 a.build_types(func_r_dict, [])
106 #t.view()
107 graph = graphof(t, strange_key_eq)
108 assert a.binding(graph.getargs()[0]).knowntype == str
109 assert a.binding(graph.getargs()[1]).knowntype == str
110 graph = graphof(t, strange_key_hash)
111 assert a.binding(graph.getargs()[0]).knowntype == str
112
113 def test_annotate_r_dict_bm():
114 t = TranslationContext()
115 a = t.buildannotator()
116 a.build_types(func_r_dict_bm, [])
117 #t.view()
118 strange_key_eq = Strange.key_eq.im_func
119 strange_key_hash = Strange.key_hash.im_func
120
121 Strange_def = a.bookkeeper.getuniqueclassdef(Strange)
122
123 graph = graphof(t, strange_key_eq)
124 assert a.binding(graph.getargs()[0]).classdef == Strange_def
125 assert a.binding(graph.getargs()[1]).knowntype == str
126 assert a.binding(graph.getargs()[2]).knowntype == str
127 graph = graphof(t, strange_key_hash)
128 assert a.binding(graph.getargs()[0]).classdef == Strange_def
129 assert a.binding(graph.getargs()[1]).knowntype == str
130
131
132 def test_unboxed_value():
133 class Base(object):
134 __slots__ = ()
135
136 class C(Base, UnboxedValue):
137 __slots__ = 'smallint'
138
139 assert C(17).smallint == 17
140 assert C(17).get_untagged_value() == 17
141
142 class A(UnboxedValue):
143 __slots__ = ['value']
144
145 assert A(12098).value == 12098
146 assert A(12098).get_untagged_value() == 12098
147
148 def test_symbolic():
149 pytest.skip("xxx no test here")
150
151 def test_symbolic_raises():
152 s1 = Symbolic()
153 s2 = Symbolic()
154 pytest.raises(TypeError, "s1 < s2")
155 pytest.raises(TypeError, "hash(s1)")
156
157 def test_compute_hash():
158 from rpython.rlib.objectmodel import _hash_string, _hash_float, _hash_tuple
159 assert compute_hash("Hello") == _hash_string("Hello")
160 assert compute_hash(7) == 7
161 assert compute_hash(-3.5) == _hash_float(-3.5)
162 assert compute_hash(None) == 0
163 assert compute_hash(("world", None, 7)) == _hash_tuple(("world", None, 7))
164 #
165 class Foo(object):
166 def __hash__(self):
167 return 42
168 foo = Foo()
169 h = compute_hash(foo)
170 assert h == object.__hash__(foo)
171 assert compute_hash(None) == 0
172
173 def test_compute_hash_float():
174 from rpython.rlib.rfloat import INFINITY, NAN
175 assert compute_hash(INFINITY) == 314159
176 assert compute_hash(-INFINITY) == -271828
177 assert compute_hash(NAN) == 0
178
179 def test_compute_identity_hash():
180 class Foo(object):
181 def __hash__(self):
182 return 42
183 foo = Foo()
184 h = compute_identity_hash(foo)
185 assert h == object.__hash__(foo)
186
187 def test_compute_unique_id():
188 from rpython.rlib.rarithmetic import intmask
189 class Foo(object):
190 pass
191 foo = Foo()
192 x = compute_unique_id(foo)
193 assert type(x) is int
194 assert x == intmask(id(foo))
195
196 def test_current_object_addr_as_int():
197 from rpython.rlib.rarithmetic import intmask
198 class Foo(object):
199 pass
200 foo = Foo()
201 assert current_object_addr_as_int(foo) == intmask(id(foo))
202
203 class TestObjectModel(BaseRtypingTest):
204
205 def test_we_are_translated(self):
206 assert we_are_translated() is False
207
208 def fn():
209 return we_are_translated()
210 res = self.interpret(fn, [])
211 assert res is True
212
213 def test_rtype_r_dict(self):
214 res = self.interpret(func_r_dict, [])
215 assert res is True
216
217 def test_rtype_r_dict_bm(self):
218 res = self.interpret(func_r_dict_bm, [])
219 assert res is True
220
221 def test_rtype_constant_r_dicts(self):
222 d1 = r_dict(strange_key_eq, strange_key_hash)
223 d1['hello'] = 666
224 d2 = r_dict(strange_key_eq, strange_key_hash)
225 d2['hello'] = 777
226 d2['world'] = 888
227 def fn(i):
228 if i == 1:
229 d = d1
230 else:
231 d = d2
232 return len(d)
233 res = self.interpret(fn, [1])
234 assert res == 1
235 res = self.interpret(fn, [2])
236 assert res == 2
237
238 def test_rtype_r_dict_singlefrozen_func(self):
239 class FreezingClass(Strange):
240 def _freeze_(self):
241 return True
242 obj = FreezingClass()
243 def fn():
244 d = r_dict(obj.key_eq, obj.key_hash)
245 return play_with_r_dict(d)
246 assert self.interpret(fn, []) is True
247
248 def test_rtype_r_dict_singlefrozen_func_pbc(self):
249 class FreezingClass(Strange):
250 def _freeze_(self):
251 return True
252 obj = FreezingClass()
253 pbc_d = r_dict(obj.key_eq, obj.key_hash)
254 def fn():
255 return play_with_r_dict(pbc_d)
256 assert self.interpret(fn, []) is True
257
258 def test_rtype_r_dict_exceptions(self):
259 def raising_hash(obj):
260 if obj.startswith("bla"):
261 raise TypeError
262 return 1
263 def eq(obj1, obj2):
264 return obj1 is obj2
265 def f():
266 d1 = r_dict(eq, raising_hash)
267 d1['xxx'] = 1
268 try:
269 x = d1["blabla"]
270 except Exception:
271 return 42
272 return x
273 res = self.interpret(f, [])
274 assert res == 42
275
276 def f():
277 d1 = r_dict(eq, raising_hash)
278 d1['xxx'] = 1
279 try:
280 x = d1["blabla"]
281 except TypeError:
282 return 42
283 return x
284 res = self.interpret(f, [])
285 assert res == 42
286
287 def f():
288 d1 = r_dict(eq, raising_hash)
289 d1['xxx'] = 1
290 try:
291 d1["blabla"] = 2
292 except TypeError:
293 return 42
294 return 0
295 res = self.interpret(f, [])
296 assert res == 42
297
298 def test_access_in_try(self):
299 h = lambda x: 1
300 eq = lambda x, y: x == y
301
302 def f(d):
303 try:
304 return d[2]
305 except ZeroDivisionError:
306 return 42
307 return -1
308
309 def g(n):
310 d = r_dict(eq, h)
311 d[1] = n
312 d[2] = 2 * n
313 return f(d)
314
315 res = self.interpret(g, [3])
316 assert res == 6
317
318 def test_access_in_try_set(self):
319 h = lambda x: 1
320 eq = lambda x, y: x == y
321 def f(d):
322 try:
323 d[2] = 77
324 except ZeroDivisionError:
325 return 42
326 return -1
327 def g(n):
328 d = r_dict(eq, h)
329 d[1] = n
330 f(d)
331 return d[2]
332 res = self.interpret(g, [3])
333 assert res == 77
334
335 def test_r_dict_fast_functions(self):
336 def fn():
337 d1 = r_dict(strange_key_eq, strange_key_hash, simple_hash_eq=True)
338 return play_with_r_dict(d1)
339 res = self.interpret(fn, [])
340 assert res
341
342 def test_prepare_dict_update(self):
343 def g(n):
344 d = {}
345 prepare_dict_update(d, n)
346 return 42
347 res = self.interpret(g, [3])
348 assert res == 42 # "did not crash"
349
350 def test_prepare_dict_update_2(self):
351 def g(n):
352 d = OrderedDict()
353 prepare_dict_update(d, n)
354 return 42
355 res = self.interpret(g, [3])
356 assert res == 42 # "did not crash"
357
358 def test_reversed_dict(self):
359 d1 = {2: 3, 4: 5, 6: 7}
360 def g():
361 n1 = 0
362 for key in d1:
363 n1 = n1 * 10 + key
364 n2 = 0
365 for key in reversed_dict(d1):
366 n2 = n2 * 10 + key
367 return n1 * 10000 + n2
368 got = str(g())
369 assert len(got) == 7 and got[3] == '0' and got[:3] == got[6:3:-1]
370 got = str(self.interpret(g, []))
371 assert len(got) == 7 and got[3] == '0' and got[:3] == got[6:3:-1]
372
373 def test_compute_hash(self):
374 class Foo(object):
375 pass
376 def f(i):
377 assert compute_hash(i) == compute_hash(42)
378 assert compute_hash(i + 1.0) == compute_hash(43.0)
379 assert compute_hash("Hello" + str(i)) == compute_hash("Hello42")
380 if i == 42:
381 p = None
382 else:
383 p = Foo()
384 assert compute_hash(p) == compute_hash(None)
385 assert (compute_hash(("world", None, i, 7.5)) ==
386 compute_hash(("world", None, 42, 7.5)))
387 q = Foo()
388 assert compute_hash(q) == compute_identity_hash(q)
389 from rpython.rlib.rfloat import INFINITY, NAN
390 assert compute_hash(INFINITY) == 314159
391 assert compute_hash(-INFINITY) == -271828
392 assert compute_hash(NAN) == 0
393 return i * 2
394 res = self.interpret(f, [42])
395 assert res == 84
396
397 def test_isconstant(self):
398 @specialize.arg_or_var(0)
399 def f(arg):
400 if is_annotation_constant(arg):
401 return 1
402 return 10
403
404 def fn(arg):
405 return f(arg) + f(3)
406
407 assert self.interpret(fn, [15]) == 11
408
409 def test_rtype_keepalive(self):
410 from rpython.rlib import objectmodel
411 def f():
412 x = [1]
413 y = ['b']
414 objectmodel.keepalive_until_here(x, y)
415 return 1
416
417 res = self.interpret(f, [])
418 assert res == 1
419
420 def test_fetch_translated_config(self):
421 assert fetch_translated_config() is None
422 def f():
423 return fetch_translated_config().translation.continuation
424 res = self.interpret(f, [])
425 assert res is False
426
427
428 def test_specialize_decorator():
429 def f():
430 pass
431
432 specialize.memo()(f)
433
434 assert f._annspecialcase_ == 'specialize:memo'
435
436 specialize.arg(0)(f)
437
438 assert f._annspecialcase_ == 'specialize:arg(0)'
439
440 specialize.arg(1)(f)
441
442 assert f._annspecialcase_ == 'specialize:arg(1)'
443
444 def test_enforceargs_decorator():
445 @enforceargs(int, str, None)
446 def f(a, b, c):
447 return a, b, c
448 f.foo = 'foo'
449 assert f._annenforceargs_ == (int, str, None)
450 assert f.__name__ == 'f'
451 assert f.foo == 'foo'
452 assert f(1, 'hello', 42) == (1, 'hello', 42)
453 exc = pytest.raises(TypeError, "f(1, 2, 3)")
454 assert exc.value.message == "f argument 'b' must be of type <type 'str'>"
455 pytest.raises(TypeError, "f('hello', 'world', 3)")
456
457 def test_always_inline():
458 @always_inline
459 def f(a, b, c):
460 return a, b, c
461 assert f._always_inline_ is True
462
463 def test_try_inline():
464 @try_inline
465 def f(a, b, c):
466 return a, b, c
467 assert f._always_inline_ == "try"
468
469
470 def test_enforceargs_defaults():
471 @enforceargs(int, int)
472 def f(a, b=40):
473 return a + b
474 assert f(2) == 42
475
476 def test_enforceargs_keywords():
477 @enforceargs(b=int)
478 def f(a, b, c):
479 return a + b
480 assert f._annenforceargs_ == (None, int, None)
481
482 def test_enforceargs_int_float_promotion():
483 @enforceargs(float)
484 def f(x):
485 return x
486 # in RPython there is an implicit int->float promotion
487 assert f(42) == 42
488
489 def test_enforceargs_complex_types():
490 @enforceargs([int], {str: int})
491 def f(a, b):
492 return a, b
493 x = [0, 1, 2]
494 y = {'a': 1, 'b': 2}
495 assert f(x, y) == (x, y)
496 assert f([], {}) == ([], {})
497 assert f(None, None) == (None, None)
498 pytest.raises(TypeError, "f(['hello'], y)")
499 pytest.raises(TypeError, "f(x, {'a': 'hello'})")
500 pytest.raises(TypeError, "f(x, {0: 42})")
501
502 def test_enforceargs_no_typecheck():
503 @enforceargs(int, str, None, typecheck=False)
504 def f(a, b, c):
505 return a, b, c
506 assert f._annenforceargs_ == (int, str, None)
507 assert f(1, 2, 3) == (1, 2, 3) # no typecheck
508
509 def test_enforceargs_translates():
510 from rpython.rtyper.lltypesystem import lltype
511 @enforceargs(int, float)
512 def f(a, b):
513 return a, b
514 graph = getgraph(f, [int, int])
515 TYPES = [v.concretetype for v in graph.getargs()]
516 assert TYPES == [lltype.Signed, lltype.Float]
517
518 def test_enforceargs_not_constant():
519 from rpython.translator.translator import TranslationContext, graphof
520 @enforceargs(NOT_CONSTANT)
521 def f(a):
522 return a
523 def f42():
524 return f(42)
525 t = TranslationContext()
526 a = t.buildannotator()
527 s = a.build_types(f42, [])
528 assert not hasattr(s, 'const')
529
530
531 def getgraph(f, argtypes):
532 from rpython.translator.translator import TranslationContext, graphof
533 from rpython.translator.backendopt.all import backend_optimizations
534 t = TranslationContext()
535 a = t.buildannotator()
536 typer = t.buildrtyper()
537 a.build_types(f, argtypes)
538 typer.specialize()
539 backend_optimizations(t)
540 graph = graphof(t, f)
541 if option.view:
542 graph.show()
543 return graph
544
545
546 def test_newlist():
547 def f(z):
548 x = newlist_hint(sizehint=38)
549 if z < 0:
550 x.append(1)
551 return len(x)
552
553 graph = getgraph(f, [int])
554 for llop in graph.startblock.operations:
555 if llop.opname == 'malloc_varsize':
556 break
557 assert llop.args[2].value == 38
558
559 def test_newlist_nonconst():
560 def f(z):
561 x = newlist_hint(sizehint=z)
562 return len(x)
563
564 graph = getgraph(f, [int])
565 for llop in graph.startblock.operations:
566 if llop.opname == 'malloc_varsize':
567 break
568 assert llop.args[2] is graph.startblock.inputargs[0]
569
570 def test_resizelist_hint():
571 def f(z):
572 x = []
573 resizelist_hint(x, 39)
574 return len(x)
575
576 graph = getgraph(f, [int])
577 for _, op in graph.iterblockops():
578 if op.opname == 'direct_call':
579 break
580 call_name = op.args[0].value._obj.graph.name
581 assert call_name.startswith('_ll_list_resize_hint')
582 call_arg2 = op.args[2].value
583 assert call_arg2 == 39
584
585 def test_resizelist_hint_len():
586 def f(i):
587 l = [44]
588 resizelist_hint(l, i)
589 return len(l)
590
591 r = interpret(f, [29])
592 assert r == 1
593
594 def test_list_get_physical_size():
595 def f(z):
596 l = [z, z + 1]
597 if z:
598 l.append(z)
599 return list_get_physical_size(l)
600
601 r = interpret(f, [29])
602 assert r == 6
603
604 # now with fixed-sized list
605 def f(z):
606 l = [z, z + 1]
607 return list_get_physical_size(l)
608
609 r = interpret(f, [29])
610 assert r == 2
611
612 def test_iterkeys_with_hash():
613 def f(i):
614 d = {i + .0: 5, i + .5: 6}
615 total = 0
616 for k, h in iterkeys_with_hash(d):
617 total += k * h
618 total -= (i + 0.0) * compute_hash(i + 0.0)
619 total -= (i + 0.5) * compute_hash(i + 0.5)
620 return total
621
622 assert f(29) == 0.0
623 r = interpret(f, [29])
624 assert r == 0.0
625
626 def test_iteritems_with_hash():
627 def f(i):
628 d = {i + .0: 5, i + .5: 6}
629 total = 0
630 for k, v, h in iteritems_with_hash(d):
631 total += k * h * v
632 total -= (i + 0.0) * compute_hash(i + 0.0) * 5
633 total -= (i + 0.5) * compute_hash(i + 0.5) * 6
634 return total
635
636 assert f(29) == 0.0
637 r = interpret(f, [29])
638 assert r == 0.0
639
640 def test_contains_with_hash():
641 def f(i):
642 d = {i + .5: 5}
643 assert contains_with_hash(d, i + .5, compute_hash(i + .5))
644 assert not contains_with_hash(d, i + .3, compute_hash(i + .3))
645 return 0
646
647 f(29)
648 interpret(f, [29])
649
650 def test_setitem_with_hash():
651 def f(i):
652 d = {}
653 setitem_with_hash(d, i + .5, compute_hash(i + .5), 42)
654 setitem_with_hash(d, i + .6, compute_hash(i + .6), -612)
655 return d[i + .5]
656
657 assert f(29) == 42
658 res = interpret(f, [27])
659 assert res == 42
660
661 def test_getitem_with_hash():
662 def f(i):
663 d = {i + .5: 42, i + .6: -612}
664 return getitem_with_hash(d, i + .5, compute_hash(i + .5))
665
666 assert f(29) == 42
667 res = interpret(f, [27])
668 assert res == 42
669
670 def test_delitem_with_hash():
671 def f(i):
672 d = {i + .5: 42, i + .6: -612}
673 delitem_with_hash(d, i + .5, compute_hash(i + .5))
674 try:
675 delitem_with_hash(d, i + .5, compute_hash(i + .5))
676 except KeyError:
677 pass
678 else:
679 raise AssertionError
680 return 0
681
682 f(29)
683 interpret(f, [27])
684
685 def test_delitem_if_value_is():
686 class X:
687 pass
688 def f(i):
689 x42 = X()
690 x612 = X()
691 d = {i + .5: x42, i + .6: x612}
692 delitem_if_value_is(d, i + .5, x612)
693 assert (i + .5) in d
694 delitem_if_value_is(d, i + .5, x42)
695 assert (i + .5) not in d
696 delitem_if_value_is(d, i + .5, x612)
697 assert (i + .5) not in d
698 return 0
699
700 f(29)
701 interpret(f, [27])
702
703 def test_rdict_with_hash():
704 def f(i):
705 d = r_dict(strange_key_eq, strange_key_hash)
706 h = strange_key_hash("abc")
707 assert h == strange_key_hash("aXX") and strange_key_eq("abc", "aXX")
708 setitem_with_hash(d, "abc", h, i)
709 assert getitem_with_hash(d, "aXX", h) == i
710 try:
711 getitem_with_hash(d, "bYY", strange_key_hash("bYY"))
712 except KeyError:
713 pass
714 else:
715 raise AssertionError
716 return 0
717
718 assert f(29) == 0
719 interpret(f, [27])
720
721 def test_rordereddict_move_to_end():
722 d = OrderedDict()
723 d['key1'] = 'val1'
724 d['key2'] = 'val2'
725 d['key3'] = 'val3'
726 move_to_end(d, 'key1')
727 assert d.items() == [('key2', 'val2'), ('key3', 'val3'), ('key1', 'val1')]
728 move_to_end(d, 'key1', last=False)
729 assert d.items() == [('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]
730
731 def test_r_dict_move_to_end():
732 d = r_dict(strange_key_eq, strange_key_hash)
733 d['1key'] = 'val1'
734 d['2key'] = 'val2'
735 d['3key'] = 'val3'
736 # does not crash, we can't check that it actually moves to end on CPython
737 move_to_end(d, '1key')
738 move_to_end(d, '1key', last=False)
739
740 def test_import_from_mixin():
741 class M: # old-style
742 def f(self):
743 pass
744 class A: # old-style
745 import_from_mixin(M)
746 assert A.f.im_func is not M.f.im_func
747
748 class M(object):
749 def f(self):
750 pass
751 class A: # old-style
752 import_from_mixin(M)
753 assert A.f.im_func is not M.f.im_func
754
755 class M: # old-style
756 def f(self):
757 pass
758 class A(object):
759 import_from_mixin(M)
760 assert A.f.im_func is not M.f.im_func
761
762 class M(object):
763 def f(self):
764 pass
765 class A(object):
766 import_from_mixin(M)
767 assert A.f.im_func is not M.f.im_func
768
769 class MBase(object):
770 a = 42
771 b = 43
772 c = 1000
773 def f(self):
774 return "hi"
775 def g(self):
776 return self.c - 1
777
778 class M(MBase):
779 a = 84
780 def f(self):
781 return "there"
782
783 class A(object):
784 import_from_mixin(M)
785 c = 88
786
787 assert A.f.im_func is not M.f.im_func
788 assert A.f.im_func is not MBase.f.im_func
789 assert A.g.im_func is not MBase.g.im_func
790 assert A().f() == "there"
791 assert A.a == 84
792 assert A.b == 43
793 assert A.c == 88
794 assert A().g() == 87
795
796 try:
797 class B(object):
798 a = 63
799 import_from_mixin(M)
800 except Exception as e:
801 assert ("would overwrite the value already defined locally for 'a'"
802 in str(e))
803 else:
804 raise AssertionError("failed to detect overwritten attribute")
805
806 class M(object):
807 def __str__(self):
808 return "m!"
809 class A(object):
810 import_from_mixin(M)
811 class B(object):
812 import_from_mixin(M, special_methods=['__str__'])
813 assert str(A()).startswith('<')
814 assert str(B()) == "m!"
815
816 class M(object):
817 pass
818 class A(object):
819 def __init__(self):
820 self.foo = 42
821 class B(A):
822 import_from_mixin(M)
823 assert B().foo == 42
824
825 d = dict(__name__='foo')
826 exec("""class M(object):
827 @staticmethod
828 def f(): pass
829 """, d)
830 M = d['M']
831 class A(object):
832 import_from_mixin(M)
833 assert A.f is not M.f
834 assert A.f.__module__ != M.f.__module__
835
836
837 def test_import_from_mixin_immutable_fields():
838 class A(object):
839 _immutable_fields_ = ['a']
840
841 class B(object):
842 _immutable_fields_ = ['b']
843 import_from_mixin(A)
844
845 assert B._immutable_fields_ == ['b', 'a']
846 assert A._immutable_fields_ == ['a']
847
848 class B(object):
849 import_from_mixin(A)
850
851 assert B._immutable_fields_ == ['a']
852
853 class C(A):
854 _immutable_fields_ = ['c']
855
856 class B(object):
857 import_from_mixin(C)
858
859 assert B._immutable_fields_ == ['c', 'a']
860
861 class B(object):
862 _immutable_fields_ = ['b']
863 import_from_mixin(C)
864
865 assert B._immutable_fields_ == ['b', 'c', 'a']
866
867 class B(object):
868 _immutable_fields_ = ['b']
869
870 class BA(B):
871 import_from_mixin(C)
872
873 assert BA._immutable_fields_ == ['c', 'a']
874
875
876 def test_never_allocate():
877 from rpython.translator.c.test.test_genc import compile as c_compile
878 from rpython.memory.gctransform.transform import GCTransformError
879
880 @never_allocate
881 class MyClass(object):
882 def __init__(self, x):
883 self.x = x + 1
884
885 @dont_inline
886 def allocate_MyClass(x):
887 return MyClass(x)
888
889 def f(x):
890 # this fails because the allocation of MyClass can't be
891 # constant-folded (because it's inside a @dont_inline function)
892 return allocate_MyClass(x).x
893
894 def g(x):
895 # this works because MyClass is constant folded, so the GC transformer
896 # never sees a malloc(MyClass)
897 return MyClass(x).x
898
899 # test what happens if MyClass escapes
900 with pytest.raises(GCTransformError) as exc:
901 c_compile(f, [int])
902 assert '[function allocate_MyClass]' in str(exc)
903 assert 'was marked as @never_allocate' in str(exc)
904
905 # test that it works in the "normal" case
906 compiled_g = c_compile(g, [int])
907 assert compiled_g(41) == 42
908
909 def test_dict_to_switch():
910 d = dict_to_switch({1: "one", 2: "two"})
911 assert d(1) == "one"
912 assert d(2) == "two"
913 with pytest.raises(KeyError):
914 d(3)
915
916 d = dict_to_switch({"1": "one", "2": "two"})
917 assert d('1') == "one"
918 assert d('2') == "two"
919 with pytest.raises(KeyError):
920 d('3')
921 with pytest.raises(KeyError):
922 d('33454')
923
924 # various errors
925 with pytest.raises(AssertionError):
926 dict_to_switch({"abc": 1})
927 with pytest.raises(AssertionError):
928 dict_to_switch({(1, 2, 3): 1})
929
930 def test_dict_to_switch_translate():
931 from rpython.flowspace.model import summary
932 d = dict_to_switch({1: 17, 2: 19})
933 r = interpret(d, [1])
934 assert r == 17
935 r = interpret(d, [2])
936 assert r == 19
937 with pytest.raises(LLException):
938 interpret(d, [10])
939
940 d = dict_to_switch({'1': 17, '2': 19})
941 r = interpret(d, ['1'])
942 assert r == 17
943 r = interpret(d, ['2'])
944 assert r == 19
945 with pytest.raises(LLException):
946 interpret(d, ['a'])
947
948 d = dict_to_switch({'1': 17, '2': 19, '3': 1121, 'a': -12})
949 def f(i):
950 c = chr(i)
951 if not i:
952 c = 'abc'
953 try:
954 return d(c)
955 except KeyError:
956 return -1
957
958
959 t, typer, g = gengraph(f, [int])
960 lookupg = t.graphs[1]
961 assert summary(lookupg)['direct_call'] == 1 # should be char based
962
963 def test_dict_to_switch_default():
964 d = dict_to_switch({1: "one", 2: "two"}, default="three")
965 assert d(1) == "one"
966 assert d(2) == "two"
967 assert d(3) == "three"