Source

pypy / pypy / translator / c / test / test_typed.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
from __future__ import with_statement

import math
import sys

import py

from pypy.rlib.rstackovf import StackOverflow
from pypy.rlib.objectmodel import compute_hash, current_object_addr_as_int
from pypy.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong, intmask, longlongmask
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.translator.test import snippet
from pypy.translator.c.test.test_genc import compile


class TestTypedTestCase(object):
    def getcompiled(self, func, argtypes):
        return compile(func, argtypes, backendopt=False)

    def get_wrapper(self, func):
        def wrapper(*args):
            try:
                return func(*args)
            except OverflowError:
                return -1
            except ZeroDivisionError:
                return -2
        return wrapper

    def test_set_attr(self):
        set_attr = self.getcompiled(snippet.set_attr, [])
        assert set_attr() == 2

    def test_inheritance2(self):
        def wrap():
            res = snippet.inheritance2()
            return res == ((-12, -12.0), (3, 12.3))
        fn = self.getcompiled(wrap, [])
        assert fn()

    def test_factorial2(self):
        factorial2 = self.getcompiled(snippet.factorial2, [int])
        assert factorial2(5) == 120

    def test_factorial(self):
        factorial = self.getcompiled(snippet.factorial, [int])
        assert factorial(5) == 120

    def test_simple_method(self):
        simple_method = self.getcompiled(snippet.simple_method, [int])
        assert simple_method(55) == 55

    def test_sieve_of_eratosthenes(self):
        sieve_of_eratosthenes = self.getcompiled(snippet.sieve_of_eratosthenes,
                                                 [])
        assert sieve_of_eratosthenes() == 1028

    def test_nested_whiles(self):
        nested_whiles = self.getcompiled(snippet.nested_whiles, [int, int])
        assert nested_whiles(5, 3) == '!!!!!'

    def test_call_unpack_56(self):
        def wrap():
            res = snippet.call_unpack_56()
            return res == (2, 5, 6)
        fn = self.getcompiled(wrap, [])
        assert fn()

    def test_class_defaultattr(self):
        class K:
            n = "hello"
        def class_defaultattr():
            k = K()
            k.n += " world"
            return k.n
        fn = self.getcompiled(class_defaultattr, [])
        assert fn() == "hello world"

    def test_tuple_repr(self):
        def tuple_repr(x, y):
            z = x, y
            while x:
                x = x - 1
            return z == (6, 'a')
        fn = self.getcompiled(tuple_repr, [int, str])
        assert fn(6, "a")
        assert not fn(6, "xyz")

    def test_classattribute(self):
        fn = self.getcompiled(snippet.classattribute, [int])
        assert fn(1) == 123
        assert fn(2) == 456
        assert fn(3) == 789
        assert fn(4) == 789
        assert fn(5) == 101112

    def test_type_conversion(self):
        # obfuscated test case specially for typer.insert_link_conversions()
        def type_conversion(n):
            if n > 3:
                while n > 0:
                    n = n - 1
                    if n == 5:
                        n += 3.1416
            return n
        fn = self.getcompiled(type_conversion, [int])
        assert fn(3) == 3
        assert fn(5) == 0
        assert abs(fn(7) + 0.8584) < 1E-5

    def test_do_try_raise_choose(self):
        fn = self.getcompiled(snippet.try_raise_choose, [int])
        result = []
        for n in [-1, 0, 1, 2]:
            result.append(fn(n))
        assert result == [-1, 0, 1, 2]

    def test_is_perfect_number(self):
        fn = self.getcompiled(snippet.is_perfect_number, [int])
        for i in range(1, 33):
            perfect = fn(i)
            assert perfect is (i in (6, 28))

    def test_prime(self):
        fn = self.getcompiled(snippet.prime, [int])
        result = [fn(i) for i in range(1, 21)]
        assert result == [False, True, True, False, True, False, True, False,
                          False, False, True, False, True, False, False, False,
                          True, False, True, False]

    def test_mutate_global(self):
        class Stuff:
            pass
        g1 = Stuff(); g1.value = 1
        g2 = Stuff(); g2.value = 2
        g3 = Stuff(); g3.value = 3
        g1.next = g3
        g2.next = g3
        g3.next = g3
        def do_things():
            g1.next = g1
            g2.next = g1
            g3.next = g2
            return g3.next.next.value
        fn = self.getcompiled(do_things, [])
        assert fn() == 1

    def test_float_ops(self):
        def f(x):
            return abs(math.pow(-x, 3) + 1)
        fn = self.getcompiled(f, [float])
        assert fn(-4.5) == 92.125
        assert fn(4.5) == 90.125

    def test_memoryerror(self):
        def g(i):
            return [0] * i
        
        def f(i):
            try:
                lst = g(i)
                lst[-1] = 5
                return lst[0]
            except MemoryError:
                return -1
        fn = self.getcompiled(f, [int])
        assert fn(1) == 5
        assert fn(2) == 0
        assert fn(sys.maxint // 2 + 1) == -1
        assert fn(sys.maxint) == -1

    def test_chr(self):
        def f(x):
            try:
                return 'Yes ' + chr(x)
            except ValueError:
                return 'No'
        fn = self.getcompiled(f, [int])
        assert fn(65) == 'Yes A'
        assert fn(256) == 'No'
        assert fn(-1) == 'No'

    def test_unichr(self):
        def f(x):
            try:
                return ord(unichr(x))
            except ValueError:
                return -42
        fn = self.getcompiled(f, [int])
        assert fn(65) == 65
        assert fn(-12) == -42
        assert fn(sys.maxint) == -42

    def test_UNICHR(self):
        from pypy.rlib.runicode import UNICHR
        def f(x):
            try:
                return ord(UNICHR(x))
            except ValueError:
                return -42
        fn = self.getcompiled(f, [int])
        assert fn(65) == 65
        assert fn(-12) == -42
        assert fn(sys.maxint) == -42

    def test_list_indexerror(self):
        def f(i):
            lst = [123, 456]
            try:
                lst[i] = 789
            except IndexError:
                return 42
            return lst[0]
        fn = self.getcompiled(f, [int])
        assert fn(1) == 123
        assert fn(2) == 42
        assert fn(-2) == 789
        assert fn(-3) == 42

    def test_long_long(self):
        def f(i):
            return 4 * i
        fn = self.getcompiled(f, [r_ulonglong])
        assert fn(r_ulonglong(2147483647)) == 4 * 2147483647

        def g(i):
            return 4 * i
        gn = self.getcompiled(g, [r_longlong])
        assert gn(r_longlong(2147483647)) == 4 * 2147483647

        def g(i):
            return i << 12
        gn = self.getcompiled(g, [r_longlong])
        assert gn(r_longlong(2147483647)) == 2147483647 << 12

        def g(i):
            return i >> 12
        gn = self.getcompiled(g, [r_longlong])
        assert gn(r_longlong(-2147483647)) == (-2147483647) >> 12

        def g(i):
            return i >> 12
        gn = self.getcompiled(g, [r_ulonglong])
        assert gn(r_ulonglong(2 ** 64 - 12345678)) == (2 ** 64 - 12345678) >> 12

    def test_specializing_int_functions(self):
        def f(i):
            return i + 1
        f._annspecialcase_ = "specialize:argtype(0)"
        def g(n):
            if n > 0:
                return intmask(f(r_longlong(0)))
            else:
                return f(0)

        fn = self.getcompiled(g, [int])
        assert fn(0) == 1
        assert fn(1) == 1

    def test_downcast_int(self):
        def f(i):
            return int(i)
        fn = self.getcompiled(f, [r_longlong])
        assert fn(r_longlong(0)) == 0

    def test_upcast_int(self):
        def f(v):
            v = rffi.cast(rffi.USHORT, v)
            return intmask(v)
        fn = self.getcompiled(f, [int])
        assert fn(0x1234CDEF) == 0xCDEF

    def test_function_ptr(self):
        def f1():
            return 1
        def f2():
            return 2
        def g(i):
            if i:
                f = f1
            else:
                f = f2
            return f()
        fn = self.getcompiled(g, [int])
        assert fn(0) == 2
        assert fn(1) == 1

    def test_call_five(self):
        # --  the result of call_five() isn't a real list, but an rlist
        #     that can't be converted to a PyListObject
        def wrapper():
            lst = snippet.call_five()
            return (len(lst), lst[0]) == (1, 5)
        call_five = self.getcompiled(wrapper, [])
        result = call_five()
        assert result

    def test_get_set_del_slice(self):
        def get_set_del_nonneg_slice(): # no neg slices for now!
            l = [ord('a'), ord('b'), ord('c'), ord('d'), ord('e'), ord('f'), ord('g'), ord('h'), ord('i'), ord('j')]
            del l[:1]
            bound = len(l) - 1
            if bound >= 0:
                del l[bound:]
            del l[2:4]
            #l[:1] = [3]
            #bound = len(l)-1
            #assert bound >= 0
            #l[bound:] = [9]    no setting slice into lists for now
            #l[2:4] = [8,11]
            l[0], l[-1], l[2], l[3] = 3, 9, 8, 11

            list_3_c = l[:2]
            list_9 = l[5:]
            list_11_h = l[3:5]
            return str((len(l), l[0], l[1], l[2], l[3], l[4], l[5],
                    len(list_3_c),  list_3_c[0],  list_3_c[1],
                    len(list_9),    list_9[0],
                    len(list_11_h), list_11_h[0], list_11_h[1]))
        fn = self.getcompiled(get_set_del_nonneg_slice, [])
        result = fn()
        assert result == str((6, 3, ord('c'), 8, 11, ord('h'), 9,
                              2, 3, ord('c'),
                              1, 9,
                              2, 11, ord('h')))

    def test_is(self):
        def testfn():
            l1 = []
            return l1 is l1
        fn = self.getcompiled(testfn, [])
        result = fn()
        assert result is True
        def testfn():
            l1 = []
            return l1 is None
        fn = self.getcompiled(testfn, [])
        result = fn()
        assert result is False

    def test_str_compare(self):
        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
            return s1[i] == s2[j]
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(6):
                res = fn(i, j)
                assert res is testfn(i, j)

        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
            return s1[i] != s2[j]
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(6):
                res = fn(i, j)
                assert res is testfn(i, j)

        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
            return s1[i] < s2[j]
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(6):
                res = fn(i, j)
                assert res is testfn(i, j)

        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
            return s1[i] <= s2[j]
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(6):
                res = fn(i, j)
                assert res is testfn(i, j)

        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
            return s1[i] > s2[j]
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(6):
                res = fn(i, j)
                assert res is testfn(i, j)

        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
            return s1[i] >= s2[j]
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(6):
                res = fn(i, j)
                assert res is testfn(i, j)

    def test_str_methods(self):
        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'ne', 'e', 'twos', 'foobar', 'fortytwo']
            return s1[i].startswith(s2[j])
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(9):
                res = fn(i, j)
                assert res is testfn(i, j)
        def testfn(i, j):
            s1 = ['one', 'two']
            s2 = ['one', 'two', 'o', 'on', 'ne', 'e', 'twos', 'foobar', 'fortytwo']
            return s1[i].endswith(s2[j])
        fn = self.getcompiled(testfn, [int, int])
        for i in range(2):
            for j in range(9):
                res = fn(i, j)
                assert res is testfn(i, j)

    def test_str_join(self):
        def testfn(i, j):
            s1 = ['', ',', ' and ']
            s2 = [[], ['foo'], ['bar', 'baz', 'bazz']]
            return s1[i].join(s2[j])
        fn = self.getcompiled(testfn, [int, int])
        for i in range(3):
            for j in range(3):
                res = fn(i, j)
                assert res == fn(i, j)

    def test_unichr_eq(self):
        l = list(u'Hello world')
        def f(i, j):
            return l[i] == l[j]
        fn = self.getcompiled(f, [int, int])
        for i in range(len(l)):
            for j in range(len(l)):
                res = fn(i, j)
                assert res == f(i, j)

    def test_unichr_ne(self):
        l = list(u'Hello world')
        def f(i, j):
            return l[i] != l[j]
        fn = self.getcompiled(f, [int, int])
        for i in range(len(l)):
            for j in range(len(l)):
                res = fn(i, j)
                assert res == f(i, j)

    def test_unichr_ord(self):
        l = list(u'Hello world')
        def f(i):
            return ord(l[i])
        fn = self.getcompiled(f, [int])
        for i in range(len(l)):
            res = fn(i)
            assert res == f(i)

    def test_unichr_unichr(self):
        l = list(u'Hello world')
        def f(i, j):
            return l[i] == unichr(j)
        fn = self.getcompiled(f, [int, int])
        for i in range(len(l)):
            for j in range(len(l)):
                res = fn(i, ord(l[j]))
                assert res == f(i, ord(l[j]))

    def test_int_overflow(self):
        fn = self.getcompiled(self.get_wrapper(snippet.add_func), [int])
        assert fn(sys.maxint) == -1

    def test_int_floordiv_ovf_zer(self):
        fn = self.getcompiled(self.get_wrapper(snippet.div_func), [int])
        assert fn(-1) == -1
        assert fn(0) == -2

    def test_int_mul_ovf(self):
        fn = self.getcompiled(self.get_wrapper(snippet.mul_func), [int, int])
        for y in range(-5, 5):
            for x in range(-5, 5):
                assert fn(x, y) == snippet.mul_func(x, y)
        n = sys.maxint / 4
        assert fn(n, 3) == snippet.mul_func(n, 3)
        assert fn(n, 4) == snippet.mul_func(n, 4)
        assert fn(n, 5) == -1

    def test_int_mod_ovf_zer(self):
        fn = self.getcompiled(self.get_wrapper(snippet.mod_func), [int])
        assert fn(-1) == -1
        assert fn(0) == -2

    def test_int_lshift_ovf(self):
        fn = self.getcompiled(self.get_wrapper(snippet.lshift_func), [int])
        assert fn(1) == -1

    def test_int_unary_ovf(self):
        def w(a, b):
            if not b:
                return snippet.unary_func(a)[0]
            else:
                return snippet.unary_func(a)[1]
        fn = self.getcompiled(self.get_wrapper(w), [int, int])
        for i in range(-3, 3):
            assert fn(i, 0) == -(i)
            assert fn(i, 1) == abs(i - 1)
        assert fn(-sys.maxint - 1, 0) == -1
        assert fn(-sys.maxint, 0) == -1

    # floats
    def test_float_operations(self):
        def func(x, y):
            z = x + y / 2.1 * x
            z = math.fmod(z, 60.0)
            z = math.pow(z, 2)
            z = -z
            return int(z)

        fn = self.getcompiled(func, [float, float])
        assert fn(5.0, 6.0) == func(5.0, 6.0)

    def test_rpbc_bound_method_static_call(self):
        class R:
            def meth(self):
                return 0
        r = R()
        m = r.meth
        def fn():
            return m()
        res = self.getcompiled(fn, [])()
        assert res == 0

    def test_constant_return_disagreement(self):
        class R:
            def meth(self):
                return 0
        r = R()
        def fn():
            return r.meth()
        res = self.getcompiled(fn, [])()
        assert res == 0

    def test_stringformatting(self):
        def fn(i):
            return "you said %d, you did" % i
        f = self.getcompiled(fn, [int])
        assert f(1) == fn(1)

    def test_int2str(self):
        def fn(i):
            return str(i)
        f = self.getcompiled(fn, [int])
        assert f(1) == fn(1)

    def test_float2str(self):
        def fn(i):
            return str(i)
        f = self.getcompiled(fn, [float])
        res = f(1.0)
        assert type(res) is str and float(res) == 1.0

    def test_uint_arith(self):
        def fn(i):
            try:
                return ~(i * (i + 1)) / (i - 1)
            except ZeroDivisionError:
                return r_uint(91872331)
        f = self.getcompiled(fn, [r_uint])
        for value in range(15):
            i = r_uint(value)
            assert f(i) == fn(i)

    def test_ord_returns_a_positive(self):
        def fn(i):
            return ord(chr(i))
        f = self.getcompiled(fn, [int])
        assert f(255) == 255

    def test_hash_preservation(self):
        class C:
            pass
        class D(C):
            pass
        c = C()
        d = D()
        compute_hash(d)     # force to be cached on 'd', but not on 'c'
        #
        def fn():
            d2 = D()
            return str((compute_hash(d2),
                        current_object_addr_as_int(d2),
                        compute_hash(c),
                        compute_hash(d),
                        compute_hash(("Hi", None, (7.5, 2, d)))))

        f = self.getcompiled(fn, [])
        res = f()

        # xxx the next line is too precise, checking the exact implementation
        res = [int(a) for a in res[1:-1].split(",")]
        if res[0] != res[1]:
            assert res[0] == -res[1] - 1
        assert res[2] != compute_hash(c)     # likely
        assert res[3] == compute_hash(d)
        assert res[4] == compute_hash(("Hi", None, (7.5, 2, d)))

    def test_list_basic_ops(self):
        def list_basic_ops(i, j):
            l = [1, 2, 3]
            l.insert(0, 42)
            del l[1]
            l.append(i)
            listlen = len(l)
            l.extend(l)
            del l[listlen:]
            l += [5, 6]
            l[1] = i
            return l[j]
        f = self.getcompiled(list_basic_ops, [int, int])
        for i in range(6):
            for j in range(6):
                assert f(i, j) == list_basic_ops(i, j)

    def test_range2list(self):
        def fn():
            r = range(10, 37, 4)
            r.reverse()
            return r[0]
        f = self.getcompiled(fn, [])
        assert f() == fn()

    def test_range_idx(self):
        def fn(idx):
            r = range(10, 37, 4)
            try:
                return r[idx]
            except IndexError:
                return -1
        f = self.getcompiled(fn, [int])
        assert f(0) == fn(0)
        assert f(-1) == fn(-1)
        assert f(42) == -1

    def test_range_step(self):
        def fn(step):
            r = range(10, 37, step)
            return r[-2]
        f = self.getcompiled(fn, [int])
        assert f(1) == fn(1)
        assert f(3) == fn(3)

    def test_range_iter(self):
        def fn(start, stop, step):
            res = 0
            if step == 0:
                if stop >= start:
                    r = range(start, stop, 1)
                else:
                    r = range(start, stop, -1)
            else:
                r = range(start, stop, step)
            for i in r:
                res = res * 51 + i
            return res
        f = self.getcompiled(fn, [int, int, int])
        for args in [2, 7, 0], [7, 2, 0], [10, 50, 7], [50, -10, -3]:
            assert f(*args) == intmask(fn(*args))

    def test_list_len_is_true(self):

        class X(object):
            pass
        class A(object):
            def __init__(self):
                self.l = []

            def append_to_list(self, e):
                self.l.append(e)

            def check_list_is_true(self):
                did_loop = 0
                while self.l:
                    did_loop = 1
                    if len(self.l):
                        break
                return did_loop

        a1 = A()
        def f():
            for ii in range(1):
                a1.append_to_list(X())
            return a1.check_list_is_true()
        fn = self.getcompiled(f, [])
        assert fn() == 1

    def test_recursion_detection(self):
        def g(n):
            try:
                return f(n)
            except StackOverflow:
                return -42
        
        def f(n):
            if n == 0:
                return 1
            else:
                return n * f(n - 1)
        fn = self.getcompiled(g, [int])
        assert fn(7) == 5040
        assert fn(7) == 5040    # detection must work several times, too
        assert fn(7) == 5040
        assert fn(-1) == -42

    def test_infinite_recursion(self):
        def f(x):
            if x:
                return 1 + f(x)
            return 1
        def g(x):
            try:
                f(x)
            except RuntimeError:
                return 42
            return 1
        fn = self.getcompiled(g, [int])
        assert fn(0) == 1
        assert fn(1) == 42

    def test_r_dict_exceptions(self):
        from pypy.rlib.objectmodel import r_dict

        def raising_hash(obj):
            if obj.startswith("bla"):
                raise TypeError
            return 1
        def eq(obj1, obj2):
            return obj1 is obj2
        def f():
            d1 = r_dict(eq, raising_hash)
            d1['xxx'] = 1
            try:
                x = d1["blabla"]
            except Exception:
                return 42
            return x
        fn = self.getcompiled(f, [])
        res = fn()
        assert res == 42

        def f():
            d1 = r_dict(eq, raising_hash)
            d1['xxx'] = 1
            try:
                x = d1["blabla"]
            except TypeError:
                return 42
            return x
        fn = self.getcompiled(f, [])
        res = fn()
        assert res == 42

        def f():
            d1 = r_dict(eq, raising_hash)
            d1['xxx'] = 1
            try:
                d1["blabla"] = 2
            except TypeError:
                return 42
            return 0
        fn = self.getcompiled(f, [])
        res = fn()
        assert res == 42

    def test_float(self):
        ex = ['', '    ', '0', '1', '-1.5', '1.5E2', '2.5e-1', ' 0 ', '?']
        def f(i):
            s = ex[i]
            try:
                return float(s)
            except ValueError:
                return -999.0

        fn = self.getcompiled(f, [int])

        for i in range(len(ex)):
            expected = f(i)
            res = fn(i)
            assert res == expected

    def test_swap(self):
        def func_swap():
            a = []
            b = range(10)
            while b:
                b.pop()
                a.extend(b)
                tmp = a
                a = b
                b = tmp
                del a[:]

        self.getcompiled(func_swap, [])

    def test_ovfcheck_float_to_int(self):
        from pypy.rlib.rarithmetic import ovfcheck_float_to_int

        def func(fl):
            try:
                return ovfcheck_float_to_int(fl)
            except OverflowError:
                return -666
        f = self.getcompiled(func, [float])
        assert f(-123.0) == -123

        for frac in [0.0, 0.01, 0.99]:
            # strange things happening for float to int on 64 bit:
            # int(float(i)) != i  because of rounding issues
            x = sys.maxint
            while int(x + frac) > sys.maxint:
                x -= 1
            assert f(x + frac) == int(x + frac)

            x = sys.maxint
            while int(x - frac) <= sys.maxint:
                x += 1
            assert f(x - frac) == -666

            x = -sys.maxint - 1
            while int(x - frac) < -sys.maxint - 1:
                x += 1
            assert f(x - frac) == int(x - frac)

            x = -sys.maxint - 1
            while int(x + frac) >= -sys.maxint- 1:
                x -= 1
            assert f(x + frac) == -666

    def test_context_manager(self):
        state = []
        class C:
            def __init__(self, name):
                self.name = name
            def __enter__(self):
                state.append('acquire')
                return self
            def __exit__(self, typ, value, tb):
                if typ is not None:
                    if value is None:
                        raise RuntimeError('test failed')
                    state.append('raised')
                else:
                    if value is not None:
                        raise RuntimeError('test failed')
                state.append('release')

        def func(n):
            del state[:]
            try:
                with C('hello') as c:
                    state.append(c.name)
                    if n == 1:
                        raise ValueError
                    elif n == 2:
                        raise TypeError
            except (ValueError, TypeError):
                pass
            return ', '.join(state)
        f = self.getcompiled(func, [int])
        res = f(0)
        assert res == 'acquire, hello, release'
        res = f(1)
        assert res == 'acquire, hello, raised, release'
        res = f(2)
        assert res == 'acquire, hello, raised, release'

    def test_longlongmask(self):
        def func(n):
            m = r_ulonglong(n)
            m *= 100000
            return longlongmask(m)
        f = self.getcompiled(func, [int])
        res = f(-2000000000)
        assert res == -200000000000000

    def test_int128(self):
        if not hasattr(rffi, '__INT128_T'):
            py.test.skip("no '__int128_t'")
        def func(n):
            x = rffi.cast(getattr(rffi, '__INT128_T'), n)
            x *= x
            x *= x
            x *= x
            x *= x
            return intmask(x >> 96)
        f = self.getcompiled(func, [int])
        res = f(217)
        assert res == 305123851

    def test_bool_2(self):
        def func(n):
            x = rffi.cast(lltype.Bool, n)
            return int(x)
        f = self.getcompiled(func, [int])
        res = f(2)
        assert res == 1     # and not 2