Debian Codegraph @

rpython/rtyper/test/test_rclass.py

raw symbols SCIP
1 import sys
2
3 import py
4 import pytest
5
6 from rpython.flowspace.model import summary
7 from rpython.rlib.rarithmetic import r_longlong
8 from rpython.rtyper.lltypesystem.lltype import (typeOf, Signed, getRuntimeTypeInfo,
9 identityhash)
10 from rpython.rtyper.error import TyperError
11 from rpython.rtyper.rclass import (IR_IMMUTABLE, IR_IMMUTABLE_ARRAY,
12 IR_QUASIIMMUTABLE, IR_QUASIIMMUTABLE_ARRAY)
13 from rpython.rtyper.test.tool import BaseRtypingTest
14 from rpython.translator.translator import TranslationContext, graphof
15
16 from rpython.rtyper.annlowlevel import llstr, hlstr
17
18
19 class EmptyBase(object):
20 pass
21
22 class Random:
23 xyzzy = 12
24 yadda = 21
25
26 # for method calls
27 class A:
28 def f(self):
29 return self.g()
30
31 def g(self):
32 return 42
33
34 class B(A):
35 def g(self):
36 return 1
37
38 class C(B):
39 pass
40
41 class TestRclass(BaseRtypingTest):
42
43 def test_instanceattr(self):
44 def dummyfn():
45 x = EmptyBase()
46 x.a = 5
47 x.a += 1
48 return x.a
49 res = self.interpret(dummyfn, [])
50 assert res == 6
51
52 def test_simple(self):
53 def dummyfn():
54 x = EmptyBase()
55 return x
56 res = self.interpret(dummyfn, [])
57 assert self.is_of_instance_type(res)
58
59 def test_classattr(self):
60 def dummyfn():
61 x = Random()
62 return x.xyzzy
63 res = self.interpret(dummyfn, [])
64 assert res == 12
65
66 def test_classattr_both(self):
67 class A:
68 a = 1
69 class B(A):
70 a = 2
71 def pick(i):
72 if i == 0:
73 return A
74 else:
75 return B
76
77 def dummyfn(i):
78 C = pick(i)
79 i = C()
80 return C.a + i.a
81 res = self.interpret(dummyfn, [0])
82 assert res == 2
83 res = self.interpret(dummyfn, [1])
84 assert res == 4
85
86 def test_classattr_both2(self):
87 class Base(object):
88 a = 0
89 class A(Base):
90 a = 1
91 class B(Base):
92 a = 2
93 def pick(i):
94 if i == 0:
95 return A
96 else:
97 return B
98
99 def dummyfn(i):
100 C = pick(i)
101 i = C()
102 return C.a + i.a
103 res = self.interpret(dummyfn, [0])
104 assert res == 2
105 res = self.interpret(dummyfn, [1])
106 assert res == 4
107
108 def test_runtime_exception(self):
109 class MyExc(Exception):
110 pass
111 class Sub1(MyExc):
112 pass
113 class Sub2(MyExc):
114 pass
115 def pick(flag):
116 if flag:
117 return Sub1
118 else:
119 return Sub2
120 def g(flag):
121 ex = pick(flag)
122 raise ex()
123 def f(flag):
124 try:
125 g(flag)
126 except Sub1:
127 return 1
128 except Sub2:
129 return 2
130 else:
131 return 3
132 assert self.interpret(f, [True]) == 1
133 assert self.interpret(f, [False]) == 2
134
135 def test_classattr_as_defaults(self):
136 def dummyfn():
137 x = Random()
138 x.xyzzy += 1
139 return x.xyzzy
140 res = self.interpret(dummyfn, [])
141 assert res == 13
142
143 def test_overridden_classattr_as_defaults(self):
144 class W_Root(object):
145 pass
146 class W_Thunk(W_Root):
147 pass
148
149 THUNK_PLACEHOLDER = W_Thunk()
150 W_Root.w_thunkalias = None
151 W_Thunk.w_thunkalias = THUNK_PLACEHOLDER
152
153 def dummyfn(x):
154 if x == 1:
155 t = W_Thunk()
156 elif x == 2:
157 t = W_Thunk()
158 t.w_thunkalias = W_Thunk()
159 else:
160 t = W_Root()
161 return t.w_thunkalias is THUNK_PLACEHOLDER
162 res = self.interpret(dummyfn, [1])
163 assert res == True
164
165 def test_prebuilt_instance(self):
166 a = EmptyBase()
167 a.x = 5
168 def dummyfn():
169 a.x += 1
170 return a.x
171 self.interpret(dummyfn, [])
172
173 def test_recursive_prebuilt_instance(self):
174 a = EmptyBase()
175 b = EmptyBase()
176 a.x = 5
177 b.x = 6
178 a.peer = b
179 b.peer = a
180 def dummyfn():
181 return a.peer.peer.peer.x
182 res = self.interpret(dummyfn, [])
183 assert res == 6
184
185 def test_recursive_prebuilt_instance_classattr(self):
186 class Base:
187 def m(self):
188 return self.d.t.v
189 class T1(Base):
190 v = 3
191 class T2(Base):
192 v = 4
193 class D:
194 def _freeze_(self):
195 return True
196
197 t1 = T1()
198 t2 = T2()
199 T1.d = D()
200 T2.d = D()
201 T1.d.t = t1
202
203 def call_meth(obj):
204 return obj.m()
205 def fn():
206 return call_meth(t1) + call_meth(t2)
207 assert self.interpret(fn, []) == 6
208
209 def test_prebuilt_instances_with_void(self):
210 def marker():
211 return 42
212 a = EmptyBase()
213 a.nothing_special = marker
214 def dummyfn():
215 return a.nothing_special()
216 res = self.interpret(dummyfn, [])
217 assert res == 42
218
219 def test_simple_method_call(self):
220 def f(i):
221 if i:
222 a = A()
223 else:
224 a = B()
225 return a.f()
226 res = self.interpret(f, [True])
227 assert res == 42
228 res = self.interpret(f, [False])
229 assert res == 1
230
231 def test_isinstance(self):
232 def f(i):
233 if i == 0:
234 o = None
235 elif i == 1:
236 o = A()
237 elif i == 2:
238 o = B()
239 else:
240 o = C()
241 return 100*isinstance(o, A)+10*isinstance(o, B)+1*isinstance(o ,C)
242
243 res = self.interpret(f, [1])
244 assert res == 100
245 res = self.interpret(f, [2])
246 assert res == 110
247 res = self.interpret(f, [3])
248 assert res == 111
249
250 res = self.interpret(f, [0])
251 assert res == 0
252
253 def test_method_used_in_subclasses_only(self):
254 class A:
255 def meth(self):
256 return 123
257 class B(A):
258 pass
259 def f():
260 x = B()
261 return x.meth()
262 res = self.interpret(f, [])
263 assert res == 123
264
265 def test_method_both_A_and_B(self):
266 class A:
267 def meth(self):
268 return 123
269 class B(A):
270 pass
271 def f():
272 a = A()
273 b = B()
274 return a.meth() + b.meth()
275 res = self.interpret(f, [])
276 assert res == 246
277
278 def test_method_specialized_with_subclass(self):
279 class A:
280 def meth(self, n):
281 return -1
282 meth._annspecialcase_ = 'specialize:arg(1)'
283
284 class B(A):
285 pass
286
287 def f():
288 a = A()
289 b = B()
290 a.meth(1) # the self of this variant is annotated with A
291 b.meth(2) # the self of this variant is annotated with B
292 return 42
293
294 res = self.interpret(f, [])
295 assert res == 42
296
297 def test_issubclass_type(self):
298 class Abstract:
299 pass
300 class A(Abstract):
301 pass
302 class B(A):
303 pass
304 def f(i):
305 if i == 0:
306 c1 = A()
307 else:
308 c1 = B()
309 return issubclass(type(c1), B)
310 assert self.interpret(f, [0]) == False
311 assert self.interpret(f, [1]) == True
312
313 def g(i):
314 if i == 0:
315 c1 = A()
316 else:
317 c1 = B()
318 return issubclass(type(c1), A)
319 assert self.interpret(g, [0]) == True
320 assert self.interpret(g, [1]) == True
321
322 def test_staticmethod(self):
323 class A(object):
324 f = staticmethod(lambda x, y: x*y)
325 def f():
326 a = A()
327 return a.f(6, 7)
328 res = self.interpret(f, [])
329 assert res == 42
330
331 def test_staticmethod2(self):
332 class A(object):
333 f = staticmethod(lambda x, y: x*y)
334 class B(A):
335 f = staticmethod(lambda x, y: x+y)
336 def f():
337 b = B()
338 return b.f(6, 7)
339 res = self.interpret(f, [])
340 assert res == 13
341
342 def test_is(self):
343 class A: pass
344 class B(A): pass
345 class C: pass
346 def f(i):
347 a = A()
348 b = B()
349 c = C()
350 d = None
351 e = None
352 if i == 0:
353 d = a
354 elif i == 1:
355 d = b
356 elif i == 2:
357 e = c
358 return (0x0001*(a is b) | 0x0002*(a is c) | 0x0004*(a is d) |
359 0x0008*(a is e) | 0x0010*(b is c) | 0x0020*(b is d) |
360 0x0040*(b is e) | 0x0080*(c is d) | 0x0100*(c is e) |
361 0x0200*(d is e))
362 res = self.interpret(f, [0])
363 assert res == 0x0004
364 res = self.interpret(f, [1])
365 assert res == 0x0020
366 res = self.interpret(f, [2])
367 assert res == 0x0100
368 res = self.interpret(f, [3])
369 assert res == 0x0200
370
371 def test_eq(self):
372 class A: pass
373 class B(A): pass
374 class C: pass
375 def f(i):
376 a = A()
377 b = B()
378 c = C()
379 d = None
380 e = None
381 if i == 0:
382 d = a
383 elif i == 1:
384 d = b
385 elif i == 2:
386 e = c
387 return (0x0001*(a == b) | 0x0002*(a == c) | 0x0004*(a == d) |
388 0x0008*(a == e) | 0x0010*(b == c) | 0x0020*(b == d) |
389 0x0040*(b == e) | 0x0080*(c == d) | 0x0100*(c == e) |
390 0x0200*(d == e))
391 res = self.interpret(f, [0])
392 assert res == 0x0004
393 res = self.interpret(f, [1])
394 assert res == 0x0020
395 res = self.interpret(f, [2])
396 assert res == 0x0100
397 res = self.interpret(f, [3])
398 assert res == 0x0200
399
400 def test_istrue(self):
401 class A:
402 pass
403 def f(i):
404 if i == 0:
405 a = A()
406 else:
407 a = None
408 if a:
409 return 1
410 else:
411 return 2
412 res = self.interpret(f, [0])
413 assert res == 1
414 res = self.interpret(f, [1])
415 assert res == 2
416
417 def test_ne(self):
418 class A: pass
419 class B(A): pass
420 class C: pass
421 def f(i):
422 a = A()
423 b = B()
424 c = C()
425 d = None
426 e = None
427 if i == 0:
428 d = a
429 elif i == 1:
430 d = b
431 elif i == 2:
432 e = c
433 return (0x0001*(a != b) | 0x0002*(a != c) | 0x0004*(a != d) |
434 0x0008*(a != e) | 0x0010*(b != c) | 0x0020*(b != d) |
435 0x0040*(b != e) | 0x0080*(c != d) | 0x0100*(c != e) |
436 0x0200*(d != e))
437 res = self.interpret(f, [0])
438 assert res == ~0x0004 & 0x3ff
439 res = self.interpret(f, [1])
440 assert res == ~0x0020 & 0x3ff
441 res = self.interpret(f, [2])
442 assert res == ~0x0100 & 0x3ff
443 res = self.interpret(f, [3])
444 assert res == ~0x0200 & 0x3ff
445
446 def test_class___name__(self):
447 class ACLS(object): pass
448 class Bcls(ACLS): pass
449 class CCls(ACLS): pass
450 def nameof(cls):
451 return cls.__name__
452 nameof._annspecialcase_ = "specialize:memo"
453 def f(i):
454 if i == 1: x = ACLS()
455 elif i == 2: x = Bcls()
456 else: x = CCls()
457 return nameof(x.__class__)
458 res = self.interpret(f, [1])
459 assert ''.join(res.chars) == 'ACLS'
460 res = self.interpret(f, [2])
461 assert ''.join(res.chars) == 'Bcls'
462 res = self.interpret(f, [3])
463 assert ''.join(res.chars) == 'CCls'
464
465 def test_compute_identity_hash(self):
466 from rpython.rlib.objectmodel import compute_identity_hash
467 class C:
468 pass
469 class D(C):
470 pass
471 c = C()
472 d = D()
473 #
474 def f():
475 d2 = D()
476 return (compute_identity_hash(d2),
477 compute_identity_hash(c),
478 compute_identity_hash(d))
479
480 self.interpret(f, [])
481 # check does not crash
482
483 def test_circular_hash_initialization(self):
484 class B:
485 pass
486 class C(B):
487 pass
488 c1 = C()
489 c1.somedict = {c1: True, C(): False}
490 def f():
491 B().somedict = {} # force the attribute up
492 c1.somedict[c1] = 123
493 return len(c1.somedict)
494 res = self.interpret(f, [])
495 assert res == 2
496
497 def test_type(self):
498 class A:
499 pass
500 class B(A):
501 pass
502 def g(a):
503 return type(a)
504 def f(i):
505 if i > 0:
506 a = A()
507 elif i < 0:
508 a = B()
509 else:
510 a = None
511 return g(a) is A # should type(None) work? returns None for now
512 res = self.interpret(f, [1])
513 assert res is True
514 res = self.interpret(f, [-1])
515 assert res is False
516 res = self.interpret(f, [0])
517 assert res is False
518
519 def test_type_of_constant(self):
520 class A:
521 pass
522 a = A()
523
524 def f():
525 return type(a) is A
526
527 res = self.interpret(f, [])
528
529
530 def test_void_fnptr(self):
531 def g():
532 return 42
533 def f():
534 e = EmptyBase()
535 e.attr = g
536 return e.attr()
537 res = self.interpret(f, [])
538 assert res == 42
539
540 def test_getattr_on_classes(self):
541 class A:
542 def meth(self):
543 return self.value + 42
544 class B(A):
545 def meth(self):
546 shouldnt**be**seen
547 class C(B):
548 def meth(self):
549 return self.value - 1
550 def pick_class(i):
551 if i > 0:
552 return A
553 else:
554 return C
555 def f(i):
556 meth = pick_class(i).meth
557 x = C()
558 x.value = 12
559 return meth(x) # calls A.meth or C.meth, completely ignores B.meth
560 res = self.interpret(f, [1])
561 assert res == 54
562 res = self.interpret(f, [0])
563 assert res == 11
564
565 def test_constant_bound_method(self):
566 class C:
567 value = 1
568 def meth(self):
569 return self.value
570 meth = C().meth
571 def f():
572 return meth()
573 res = self.interpret(f, [])
574 assert res == 1
575
576 def test_mixin(self):
577 class Mixin(object):
578 _mixin_ = True
579
580 def m(self, v):
581 return v
582
583 class Base(object):
584 pass
585
586 class A(Base, Mixin):
587 pass
588
589 class B(Base, Mixin):
590 pass
591
592 class C(B):
593 pass
594
595 def f():
596 a = A()
597 v0 = a.m(2)
598 b = B()
599 v1 = b.m('x')
600 c = C()
601 v2 = c.m('y')
602 return v0, v1, v2
603
604 res = self.interpret(f, [])
605 assert typeOf(res.item0) == Signed
606
607 def test___class___attribute(self):
608 class Base(object): pass
609 class A(Base): pass
610 class B(Base): pass
611 class C(A): pass
612 def seelater():
613 C()
614 def f(n):
615 if n == 1:
616 x = A()
617 else:
618 x = B()
619 y = B()
620 result = x.__class__, y.__class__
621 seelater()
622 return result
623 def g():
624 cls1, cls2 = f(1)
625 return cls1 is A, cls2 is B
626
627 res = self.interpret(g, [])
628 assert res.item0
629 assert res.item1
630
631
632 def test_common_class_attribute(self):
633 class A:
634 def meth(self):
635 return self.x
636 class B(A):
637 x = 42
638 class C(A):
639 x = 43
640 def call_meth(a):
641 return a.meth()
642 def f():
643 b = B()
644 c = C()
645 return call_meth(b) + call_meth(c)
646 assert self.interpret(f, []) == 85
647
648 def test_default_attribute_non_primitive(self):
649 class A:
650 x = (1, 2)
651 def f():
652 a = A()
653 a.x = (3, 4)
654 return a.x[0]
655 assert self.interpret(f, []) == 3
656
657 def test_filter_unreachable_methods(self):
658 # this creates a family with 20 unreachable methods m(), all
659 # hidden by a 21st method m().
660 class Base:
661 pass
662 prev = Base
663 for i in range(20):
664 class Intermediate(prev):
665 def m(self, value=i):
666 return value
667 prev = Intermediate
668 class Final(prev):
669 def m(self):
670 return -7
671 def f():
672 return Final().m()
673 res = self.interpret(f, [])
674 assert res == -7
675
676 def test_instantiate_despite_abstract_methods(self):
677 class A:
678 pass
679 class B(A):
680 def foo(self):
681 return 42
682 def fn(n):
683 # Although the code below is a bit strange, there are
684 # subtle ways in which the same situation could occur.
685 # One is shown by test_specialize_methods().
686 if n < 10:
687 x = B()
688 else:
689 x = A()
690 if n < 7:
691 return x.foo()
692 else:
693 return 100
694 assert self.interpret(fn, [5]) == 42
695 assert self.interpret(fn, [15]) == 100
696
697 def test_specialize_methods(self):
698 from rpython.rlib.objectmodel import specialize
699 class A:
700 @specialize.arg(1)
701 def revealconst(self, T):
702 return 3 * T
703 revealconst.cls = 'A'
704 class B(A):
705 @specialize.arg(1)
706 def revealconst(self, T):
707 return 4 * T
708 revealconst.cls = 'B'
709
710 def fn():
711 a = A()
712 b = B()
713 return a.revealconst(1) + b.revealconst(2) + a.revealconst(3)
714 assert self.interpret(fn, []) == 3 + 8 + 9
715
716 def test_hash_of_none(self):
717 from rpython.rlib.objectmodel import compute_hash
718 class A:
719 pass
720 def fn(x):
721 if x:
722 obj = A()
723 else:
724 obj = None
725 return compute_hash(obj)
726 res = self.interpret(fn, [0])
727 assert res == 0
728
729 def test_hash_of_only_none(self):
730 from rpython.rlib.objectmodel import compute_hash
731 def fn():
732 obj = None
733 return compute_hash(obj)
734 res = self.interpret(fn, [])
735 assert res == 0
736
737
738 def test_immutable(self):
739 class I(object):
740 _immutable_ = True
741
742 def __init__(self, v):
743 self.v = v
744
745 i = I(3)
746 def f():
747 return i.v
748
749 t, typer, graph = self.gengraph(f, [], backendopt=True)
750 assert summary(graph) == {}
751
752 def test_immutable_fields(self):
753 class A(object):
754 _immutable_fields_ = ["x", "y[*]"]
755
756 def __init__(self, x, y):
757 self.x = x
758 self.y = y
759
760 def f():
761 return A(3, [])
762 t, typer, graph = self.gengraph(f, [])
763 A_TYPE = graph.getreturnvar().concretetype.TO
764 accessor = A_TYPE._hints["immutable_fields"]
765 assert accessor.fields == {"inst_x": IR_IMMUTABLE,
766 "inst_y": IR_IMMUTABLE_ARRAY}
767
768 def test_immutable_fields_subclass_1(self):
769 class A(object):
770 _immutable_fields_ = ["x"]
771 def __init__(self, x):
772 self.x = x
773 class B(A):
774 def __init__(self, x, y):
775 A.__init__(self, x)
776 self.y = y
777
778 def f():
779 return B(3, 5)
780 t, typer, graph = self.gengraph(f, [])
781 B_TYPE = graph.getreturnvar().concretetype.TO
782 accessor = B_TYPE._hints["immutable_fields"]
783 assert accessor.fields == {"inst_x": IR_IMMUTABLE}
784
785 def test_immutable_fields_subclass_2(self):
786 class A(object):
787 _immutable_fields_ = ["x"]
788 def __init__(self, x):
789 self.x = x
790 class B(A):
791 _immutable_fields_ = ["y"]
792 def __init__(self, x, y):
793 A.__init__(self, x)
794 self.y = y
795
796 def f():
797 return B(3, 5)
798 t, typer, graph = self.gengraph(f, [])
799 B_TYPE = graph.getreturnvar().concretetype.TO
800 accessor = B_TYPE._hints["immutable_fields"]
801 assert accessor.fields == {"inst_x": IR_IMMUTABLE,
802 "inst_y": IR_IMMUTABLE}
803
804 def test_immutable_fields_only_in_subclass(self):
805 class A(object):
806 def __init__(self, x):
807 self.x = x
808 class B(A):
809 _immutable_fields_ = ["y"]
810 def __init__(self, x, y):
811 A.__init__(self, x)
812 self.y = y
813
814 def f():
815 return B(3, 5)
816 t, typer, graph = self.gengraph(f, [])
817 B_TYPE = graph.getreturnvar().concretetype.TO
818 accessor = B_TYPE._hints["immutable_fields"]
819 assert accessor.fields == {"inst_y": IR_IMMUTABLE}
820
821 def test_immutable_forbidden_inheritance_1(self):
822 from rpython.rtyper.rclass import ImmutableConflictError
823 class A(object):
824 pass
825 class B(A):
826 _immutable_fields_ = ['v']
827 def f():
828 A().v = 123
829 B() # crash: class B says 'v' is immutable,
830 # but it is defined on parent class A
831 py.test.raises(ImmutableConflictError, self.gengraph, f, [])
832
833 def test_immutable_forbidden_inheritance_2(self):
834 from rpython.rtyper.rclass import ImmutableConflictError
835 class A(object):
836 pass
837 class B(A):
838 _immutable_ = True
839 def f():
840 A().v = 123
841 B() # crash: class B has _immutable_ = True
842 # but class A defines 'v' to be mutable
843 py.test.raises(ImmutableConflictError, self.gengraph, f, [])
844
845 def test_immutable_ok_inheritance_2(self):
846 class A(object):
847 _immutable_fields_ = ['v']
848 class B(A):
849 _immutable_ = True
850 def f():
851 A().v = 123
852 B().w = 456
853 return B()
854 t, typer, graph = self.gengraph(f, [])
855 B_TYPE = graph.getreturnvar().concretetype.TO
856 assert B_TYPE._hints["immutable"]
857 A_TYPE = B_TYPE.super
858 accessor = A_TYPE._hints["immutable_fields"]
859 assert accessor.fields == {"inst_v": IR_IMMUTABLE}
860
861 def test_immutable_subclass_1(self):
862 from rpython.rtyper.rclass import ImmutableConflictError
863 class A(object):
864 _immutable_ = True
865 class B(A):
866 pass
867 def f():
868 A()
869 B().v = 123
870 return B()
871 py.test.raises(ImmutableConflictError, self.gengraph, f, [])
872
873 def test_immutable_subclass_2(self):
874 class A(object):
875 pass
876 class B(A):
877 _immutable_ = True
878 def f():
879 A()
880 B().v = 123
881 return B()
882 t, typer, graph = self.gengraph(f, [])
883 B_TYPE = graph.getreturnvar().concretetype.TO
884 assert B_TYPE._hints["immutable"]
885
886 def test_immutable_subclass_void(self):
887 class A(object):
888 pass
889 class B(A):
890 _immutable_ = True
891 def myfunc():
892 pass
893 def f():
894 A().f = myfunc # it's ok to add Void attributes to A
895 B().v = 123 # even though only B is declared _immutable_
896 return B()
897 t, typer, graph = self.gengraph(f, [])
898 B_TYPE = graph.getreturnvar().concretetype.TO
899 assert B_TYPE._hints["immutable"]
900
901 def test_quasi_immutable(self):
902 class A(object):
903 _immutable_fields_ = ['x', 'y', 'a?', 'b?']
904 class B(A):
905 pass
906 def f():
907 a = A()
908 a.x = 42
909 a.a = 142
910 b = B()
911 b.x = 43
912 b.y = 41
913 b.a = 44
914 b.b = 45
915 return B()
916 t, typer, graph = self.gengraph(f, [])
917 B_TYPE = graph.getreturnvar().concretetype.TO
918 accessor = B_TYPE._hints["immutable_fields"]
919 assert accessor.fields == {"inst_y": IR_IMMUTABLE,
920 "inst_b": IR_QUASIIMMUTABLE}
921 found = []
922 for op in graph.startblock.operations:
923 if op.opname == 'jit_force_quasi_immutable':
924 found.append(op.args[1].value)
925 assert found == ['mutate_a', 'mutate_a', 'mutate_b']
926
927 def test_quasi_immutable_clashes_with_immutable(self):
928 class A(object):
929 _immutable_ = True
930 _immutable_fields_ = ['a?']
931 def f():
932 a = A()
933 a.x = 42
934 a.a = 142
935 return A()
936 with py.test.raises(TyperError):
937 self.gengraph(f, [])
938
939 def test_quasi_immutable_array(self):
940 class A(object):
941 _immutable_fields_ = ['c?[*]']
942 class B(A):
943 pass
944 def f():
945 a = A()
946 a.c = [3, 4, 5]
947 return A()
948 t, typer, graph = self.gengraph(f, [])
949 A_TYPE = graph.getreturnvar().concretetype.TO
950 accessor = A_TYPE._hints["immutable_fields"]
951 assert accessor.fields == {"inst_c": IR_QUASIIMMUTABLE_ARRAY}
952 found = []
953 for op in graph.startblock.operations:
954 if op.opname == 'jit_force_quasi_immutable':
955 found.append(op.args[1].value)
956 assert found == ['mutate_c']
957
958 def test_bad_type_for_immutable_field_1(self):
959 class A:
960 _immutable_fields_ = ['lst[*]']
961 def f(n):
962 a = A()
963 a.lst = n
964 return a.lst
965
966 with py.test.raises(TyperError):
967 self.gengraph(f, [int])
968
969 def test_bad_type_for_immutable_field_2(self):
970 from rpython.rtyper.lltypesystem import lltype
971 class A:
972 _immutable_fields_ = ['lst[*]']
973 ARRAY = lltype.GcArray(lltype.Signed)
974 def f(n):
975 a = A()
976 a.lst = lltype.malloc(ARRAY, n)
977 return a.lst
978
979 with py.test.raises(TyperError):
980 self.gengraph(f, [int])
981
982 def test_bad_type_for_immutable_field_3(self):
983 class A:
984 _immutable_fields_ = ['lst?[*]']
985 def f(n):
986 a = A()
987 a.lst = n
988 return a.lst
989
990 with py.test.raises(TyperError):
991 self.gengraph(f, [int])
992
993 def test_calling_object_init(self):
994 class A(object):
995 pass
996 class B(A):
997 def __init__(self):
998 A.__init__(self)
999 def f():
1000 B()
1001 self.gengraph(f, [])
1002
1003
1004 def test__del__(self):
1005 class A(object):
1006 def __init__(self):
1007 self.a = 2
1008 def __del__(self):
1009 self.a = 3
1010 def f():
1011 a = A()
1012 return a.a
1013 t = TranslationContext()
1014 t.buildannotator().build_types(f, [])
1015 t.buildrtyper().specialize()
1016 graph = graphof(t, f)
1017 TYPE = graph.startblock.operations[0].args[0].value
1018 RTTI = getRuntimeTypeInfo(TYPE)
1019 RTTI._obj.query_funcptr # should not raise
1020 destrptr = RTTI._obj.destructor_funcptr
1021 assert destrptr is not None
1022
1023 def test_del_inheritance(self):
1024 from rpython.rlib import rgc
1025 class State:
1026 pass
1027 s = State()
1028 s.a_dels = 0
1029 s.b_dels = 0
1030 class A(object):
1031 def __del__(self):
1032 s.a_dels += 1
1033 class B(A):
1034 def __del__(self):
1035 s.b_dels += 1
1036 class C(A):
1037 pass
1038 def f():
1039 A()
1040 B()
1041 C()
1042 A()
1043 B()
1044 C()
1045 rgc.collect()
1046 return s.a_dels * 10 + s.b_dels
1047 res = f()
1048 assert res == 42
1049 t = TranslationContext()
1050 t.buildannotator().build_types(f, [])
1051 t.buildrtyper().specialize()
1052 graph = graphof(t, f)
1053 TYPEA = graph.startblock.operations[0].args[0].value
1054 RTTIA = getRuntimeTypeInfo(TYPEA)
1055 TYPEB = graph.startblock.operations[3].args[0].value
1056 RTTIB = getRuntimeTypeInfo(TYPEB)
1057 TYPEC = graph.startblock.operations[6].args[0].value
1058 RTTIC = getRuntimeTypeInfo(TYPEC)
1059 queryptra = RTTIA._obj.query_funcptr # should not raise
1060 queryptrb = RTTIB._obj.query_funcptr # should not raise
1061 queryptrc = RTTIC._obj.query_funcptr # should not raise
1062 destrptra = RTTIA._obj.destructor_funcptr
1063 destrptrb = RTTIB._obj.destructor_funcptr
1064 destrptrc = RTTIC._obj.destructor_funcptr
1065 assert destrptra == destrptrc
1066 assert typeOf(destrptra).TO.ARGS[0] != typeOf(destrptrb).TO.ARGS[0]
1067 assert destrptra is not None
1068 assert destrptrb is not None
1069
1070 def test_del_forbidden(self):
1071 class A(object):
1072 def __del__(self):
1073 self.foo()
1074 def foo(self):
1075 self.bar()
1076 def bar(self):
1077 pass
1078 bar._dont_reach_me_in_del_ = True
1079 def f():
1080 a = A()
1081 a.foo()
1082 a.bar()
1083 t = TranslationContext()
1084 t.buildannotator().build_types(f, [])
1085 e = py.test.raises(TyperError, t.buildrtyper().specialize)
1086 print e.value
1087
1088 def test_instance_repr(self):
1089 from rpython.rlib.objectmodel import current_object_addr_as_int
1090 class FooBar(object):
1091 pass
1092 def f():
1093 x = FooBar()
1094 # on lltype, the RPython-level repr of an instance contains the
1095 # current object address
1096 return current_object_addr_as_int(x), str(x)
1097
1098 res = self.interpret(f, [])
1099 xid, xstr = self.ll_unpack_tuple(res, 2)
1100 xstr = self.ll_to_string(xstr)
1101 print xid, xstr
1102 assert 'FooBar' in xstr
1103 from rpython.rlib.rarithmetic import r_uint
1104 expected = hex(r_uint(xid)).lower().replace('l', '')
1105 assert expected in xstr
1106
1107 def test_hash_via_type(self):
1108 from rpython.annotator import model as annmodel
1109 from rpython.rtyper import extregistry
1110 from rpython.rtyper.annlowlevel import cast_object_to_ptr
1111 from rpython.rlib.objectmodel import compute_identity_hash
1112
1113 class Z(object):
1114 pass
1115
1116 def my_gethash(z):
1117 not_implemented
1118
1119 def ll_my_gethash(ptr):
1120 return identityhash(ptr) # from lltype
1121
1122 class MyGetHashEntry(extregistry.ExtRegistryEntry):
1123 _about_ = my_gethash
1124 def compute_result_annotation(self, s_instance):
1125 return annmodel.SomeInteger()
1126 def specialize_call(self, hop):
1127 [v_instance] = hop.inputargs(*hop.args_r)
1128 hop.exception_is_here()
1129 return hop.gendirectcall(ll_my_gethash, v_instance)
1130
1131 def f(n):
1132 z = Z()
1133 got = my_gethash(z)
1134 expected = compute_identity_hash(z)
1135 return got - expected
1136
1137 res = self.interpret(f, [5])
1138 assert res == 0
1139
1140 def test_order_of_fields(self):
1141 class A(object):
1142 pass
1143 def f(n):
1144 a = A()
1145 a.as_int = n
1146 a.as_char = chr(n)
1147 a.as_unichar = unichr(n)
1148 a.as_double = n + 0.5
1149 a.as_bool = bool(n)
1150 a.as_void = None
1151 a.as_longlong = r_longlong(n)
1152 a.as_reference = A()
1153 return a
1154
1155 res = self.interpret(f, [5])
1156 names = list(typeOf(res).TO._names)
1157 i = names.index('inst_as_int')
1158 c = names.index('inst_as_char')
1159 u = names.index('inst_as_unichar')
1160 d = names.index('inst_as_double')
1161 b = names.index('inst_as_bool')
1162 v = names.index('inst_as_void')
1163 l = names.index('inst_as_longlong')
1164 r = names.index('inst_as_reference')
1165 assert v == 1 # void fields are first
1166 assert sorted([c, b]) == [7, 8]
1167 if sys.maxint == 2147483647:
1168 assert sorted([u, i, r]) == [4, 5, 6] # 32-bit types
1169 assert sorted([d, l]) == [2, 3] # 64-bit types
1170 else:
1171 assert sorted([u]) == [6] # 32-bit types
1172 assert sorted([i, r, d, l]) == [2, 3, 4, 5] # 64-bit types
1173
1174
1175 def test_iter(self):
1176 class Iterable(object):
1177 def __init__(self):
1178 self.counter = 0
1179
1180 def __iter__(self):
1181 return self
1182
1183 def next(self):
1184 if self.counter == 5:
1185 raise StopIteration
1186 self.counter += 1
1187 return self.counter - 1
1188
1189 def f():
1190 i = Iterable()
1191 s = 0
1192 for elem in i:
1193 s += elem
1194 return s
1195
1196 assert self.interpret(f, []) == f()
1197
1198 def test_iter_2_kinds(self):
1199 class BaseIterable(object):
1200 def __init__(self):
1201 self.counter = 0
1202
1203 def __iter__(self):
1204 return self
1205
1206 def next(self):
1207 if self.counter >= 5:
1208 raise StopIteration
1209 self.counter += self.step
1210 return self.counter - 1
1211
1212 class Iterable(BaseIterable):
1213 step = 1
1214
1215 class OtherIter(BaseIterable):
1216 step = 2
1217
1218 def f(k):
1219 if k:
1220 i = Iterable()
1221 else:
1222 i = OtherIter()
1223 s = 0
1224 for elem in i:
1225 s += elem
1226 return s
1227
1228 assert self.interpret(f, [True]) == f(True)
1229 assert self.interpret(f, [False]) == f(False)
1230
1231 @pytest.mark.xfail # XXX next support in rpython is broken!
1232 def test_iter_bug_exception(self):
1233 class Iterable(object):
1234 def __iter__(self):
1235 return self
1236
1237 def next(self):
1238 raise TyperError
1239
1240 def f():
1241 i = Iterable()
1242 it = iter(i)
1243 try:
1244 next(it)
1245 except StopIteration:
1246 return -7
1247 except TypeError:
1248 return -9
1249 return 12
1250
1251 assert self.interpret(f, []) == f()
1252
1253 def test_indexing(self):
1254 class A(object):
1255 def __init__(self, data):
1256 self.data = data
1257
1258 def __getitem__(self, i):
1259 return self.data[i]
1260
1261 def __setitem__(self, i, v):
1262 self.data[i] = v
1263
1264 def __getslice__(self, start, stop):
1265 assert start >= 0
1266 assert stop >= 0
1267 return self.data[start:stop]
1268
1269 def __setslice__(self, start, stop, v):
1270 assert start >= 0
1271 assert stop >= 0
1272 i = 0
1273 for n in range(start, stop):
1274 self.data[n] = v[i]
1275 i += 1
1276
1277 def getitem(i):
1278 a = A("abcdefg")
1279 return a[i]
1280
1281 def setitem(i, v):
1282 a = A([0] * 5)
1283 a[i] = v
1284 return a[i]
1285
1286 def getslice(start, stop):
1287 a = A([1, 2, 3, 4, 5, 6])
1288 sum = 0
1289 for i in a[start:stop]:
1290 sum += i
1291 return sum
1292
1293 def setslice(start, stop, i):
1294 a = A([0] * stop)
1295 a[start:stop] = range(start, stop)
1296 return a[i]
1297
1298 assert self.interpret(getitem, [0]) == getitem(0)
1299 assert self.interpret(getitem, [1]) == getitem(1)
1300 assert self.interpret(setitem, [0, 5]) == setitem(0, 5)
1301 assert self.interpret(getslice, [0, 4]) == getslice(0, 4)
1302 assert self.interpret(getslice, [1, 4]) == getslice(1, 4)
1303 assert self.interpret(setslice, [4, 6, 5]) == setslice(4, 6, 5)
1304
1305 def test_len(self):
1306 class A(object):
1307 def __len__(self):
1308 return 5
1309
1310 def fn():
1311 a = A()
1312 return len(a)
1313
1314 assert self.interpret(fn, []) == fn()
1315
1316 def test_init_with_star_args(self):
1317 class Base(object):
1318 def __init__(self, a, b):
1319 self.a = a
1320 self.b = b
1321 class A(Base):
1322 def __init__(self, *args):
1323 Base.__init__(self, *args)
1324 self.c = -1
1325 cls = [Base, A]
1326
1327 def f(k, a, b):
1328 return cls[k](a, b).b
1329
1330 assert self.interpret(f, [1, 4, 7]) == 7
1331
1332 def test_flatten_convert_const(self):
1333 # check that we can convert_const() a chain of more than 1000
1334 # instances
1335 class A(object):
1336 def __init__(self, next):
1337 self.next = next
1338 a = None
1339 for i in range(1500):
1340 a = A(a)
1341 def f():
1342 return a.next.next.next.next is not None
1343 assert self.interpret(f, []) == True
1344
1345 def test_str_of_type(self):
1346 class A(object):
1347 pass
1348
1349 class B(A):
1350 pass
1351
1352 def f(i):
1353 if i:
1354 a = A()
1355 else:
1356 a = B()
1357 return str(type(a))
1358 assert "A" in hlstr(self.interpret(f, [1]))
1359 assert "B" in hlstr(self.interpret(f, [0]))
1360
1361 def g(i):
1362 if i:
1363 a = A()
1364 else:
1365 a = B()
1366 return str(a.__class__)
1367 assert "A" in hlstr(self.interpret(g, [1]))
1368 assert "B" in hlstr(self.interpret(g, [0]))