-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_annrpython.py
More file actions
4771 lines (4155 loc) · 141 KB
/
Copy pathtest_annrpython.py
File metadata and controls
4771 lines (4155 loc) · 141 KB
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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import with_statement
import py.test
import sys
from collections import OrderedDict
from rpython.conftest import option
from rpython.annotator import model as annmodel
from rpython.annotator.model import AnnotatorError, UnionError
from rpython.annotator.annrpython import RPythonAnnotator as _RPythonAnnotator
from rpython.annotator.classdesc import NoSuchAttrError
from rpython.translator.translator import graphof as tgraphof
from rpython.annotator.policy import AnnotatorPolicy
from rpython.annotator.signature import Sig, SignatureError
from rpython.annotator.listdef import ListDef, ListChangeUnallowed
from rpython.annotator.dictdef import DictDef
from rpython.flowspace.model import *
from rpython.rlib.rarithmetic import r_uint, base_int, r_longlong, r_ulonglong
from rpython.rlib.rarithmetic import r_singlefloat
from rpython.rlib import objectmodel
from rpython.flowspace.flowcontext import FlowingError
from rpython.flowspace.operation import op
from rpython.translator.test import snippet
def graphof(a, func):
return tgraphof(a.translator, func)
def listitem(s_list):
assert isinstance(s_list, annmodel.SomeList)
return s_list.listdef.listitem.s_value
def somelist(s_type):
return annmodel.SomeList(ListDef(None, s_type))
def dictkey(s_dict):
assert isinstance(s_dict, annmodel.SomeDict)
return s_dict.dictdef.dictkey.s_value
def dictvalue(s_dict):
assert isinstance(s_dict, annmodel.SomeDict)
return s_dict.dictdef.dictvalue.s_value
def somedict(annotator, s_key, s_value):
return annmodel.SomeDict(DictDef(annotator.bookkeeper, s_key, s_value))
class TestAnnotateTestCase:
def teardown_method(self, meth):
assert annmodel.s_Bool == annmodel.SomeBool()
class RPythonAnnotator(_RPythonAnnotator):
def build_types(self, *args):
s = _RPythonAnnotator.build_types(self, *args)
self.validate()
if option.view:
self.translator.view()
return s
def test_simple_func(self):
"""
one test source:
def f(x):
return x+1
"""
x = Variable("x")
oper = op.add(x, Constant(1))
block = Block([x])
fun = FunctionGraph("f", block)
block.operations.append(oper)
block.closeblock(Link([oper.result], fun.returnblock))
a = self.RPythonAnnotator()
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
a.complete()
assert a.gettype(fun.getreturnvar()) == int
def test_while(self):
"""
one test source:
def f(i):
while i > 0:
i = i - 1
return i
"""
i1 = Variable("i1")
i2 = Variable("i2")
conditionop = op.gt(i1, Constant(0))
decop = op.add(i2, Constant(-1))
headerblock = Block([i1])
whileblock = Block([i2])
fun = FunctionGraph("f", headerblock)
headerblock.operations.append(conditionop)
headerblock.exitswitch = conditionop.result
headerblock.closeblock(Link([i1], fun.returnblock, False),
Link([i1], whileblock, True))
whileblock.operations.append(decop)
whileblock.closeblock(Link([decop.result], headerblock))
a = self.RPythonAnnotator()
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
a.complete()
assert a.gettype(fun.getreturnvar()) == int
def test_while_sum(self):
"""
one test source:
def f(i):
sum = 0
while i > 0:
sum = sum + i
i = i - 1
return sum
"""
i1 = Variable("i1")
i2 = Variable("i2")
i3 = Variable("i3")
sum2 = Variable("sum2")
sum3 = Variable("sum3")
conditionop = op.gt(i2, Constant(0))
decop = op.add(i3, Constant(-1))
addop = op.add(i3, sum3)
startblock = Block([i1])
headerblock = Block([i2, sum2])
whileblock = Block([i3, sum3])
fun = FunctionGraph("f", startblock)
startblock.closeblock(Link([i1, Constant(0)], headerblock))
headerblock.operations.append(conditionop)
headerblock.exitswitch = conditionop.result
headerblock.closeblock(Link([sum2], fun.returnblock, False),
Link([i2, sum2], whileblock, True))
whileblock.operations.append(addop)
whileblock.operations.append(decop)
whileblock.closeblock(Link([decop.result, addop.result], headerblock))
a = self.RPythonAnnotator()
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
a.complete()
assert a.gettype(fun.getreturnvar()) == int
def test_f_calls_g(self):
a = self.RPythonAnnotator()
s = a.build_types(f_calls_g, [int])
# result should be an integer
assert s.knowntype == int
def test_not_rpython(self):
def g(x):
""" NOT_RPYTHON """
return eval(x)
def f(x):
return g(str(x))
a = self.RPythonAnnotator()
with py.test.raises(ValueError):
a.build_types(f, [int])
def test_not_rpython_decorator(self):
from rpython.rlib.objectmodel import not_rpython
@not_rpython
def g(x):
return eval(x)
def f(x):
return g(str(x))
a = self.RPythonAnnotator()
with py.test.raises(ValueError):
a.build_types(f, [int])
def test_lists(self):
a = self.RPythonAnnotator()
end_cell = a.build_types(snippet.poor_man_rev_range, [int])
# result should be a list of integers
assert listitem(end_cell).knowntype == int
def test_factorial(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.factorial, [int])
# result should be an integer
assert s.knowntype == int
def test_factorial2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.factorial2, [int])
# result should be an integer
assert s.knowntype == int
def test_build_instance(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.build_instance, [])
# result should be a snippet.C instance
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
def test_set_attr(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.set_attr, [])
# result should be an integer
assert s.knowntype == int
def test_merge_setattr(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.merge_setattr, [int])
# result should be an integer
assert s.knowntype == int
def test_inheritance1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.inheritance1, [])
# result should be exactly:
assert s == annmodel.SomeTuple([
a.bookkeeper.immutablevalue(()),
annmodel.SomeInteger()
])
def test_poor_man_range(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.poor_man_range, [int])
# result should be a list of integers
assert listitem(s).knowntype == int
def test_staticmethod(self):
class X(object):
@staticmethod
def stat(value):
return value + 4
def f(v):
return X().stat(v)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeInteger)
def test_classmethod(self):
class X(object):
@classmethod
def meth(cls):
return None
def f():
return X().meth()
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [])
def test_methodcall1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet._methodcall1, [int])
# result should be a tuple of (C, positive_int)
assert s.knowntype == tuple
assert len(s.items) == 2
s0 = s.items[0]
assert isinstance(s0, annmodel.SomeInstance)
assert s0.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
assert s.items[1].knowntype == int
assert s.items[1].nonneg == True
def test_classes_methodcall1(self):
a = self.RPythonAnnotator()
a.build_types(snippet._methodcall1, [int])
# the user classes should have the following attributes:
getcdef = a.bookkeeper.getuniqueclassdef
assert getcdef(snippet.F).attrs.keys() == ['m']
assert getcdef(snippet.G).attrs.keys() == ['m2']
assert getcdef(snippet.H).attrs.keys() == ['attr']
assert getcdef(snippet.H).about_attribute('attr') == (
a.bookkeeper.immutablevalue(1))
def test_generaldict(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.generaldict, [str, int, str, int])
# result should be an integer
assert s.knowntype == int
def test_somebug1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet._somebug1, [int])
# result should be a built-in method
assert isinstance(s, annmodel.SomeBuiltin)
def test_with_init(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.with_init, [int])
# result should be an integer
assert s.knowntype == int
def test_with_more_init(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.with_more_init, [int, bool])
# the user classes should have the following attributes:
getcdef = a.bookkeeper.getuniqueclassdef
# XXX on which class should the attribute 'a' appear? We only
# ever flow WithInit.__init__ with a self which is an instance
# of WithMoreInit, so currently it appears on WithMoreInit.
assert getcdef(snippet.WithMoreInit).about_attribute('a') == (
annmodel.SomeInteger())
assert getcdef(snippet.WithMoreInit).about_attribute('b') == (
annmodel.SomeBool())
def test_global_instance(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.global_instance, [])
# currently this returns the constant 42.
# XXX not sure this is the best behavior...
assert s == a.bookkeeper.immutablevalue(42)
def test_call_five(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.call_five, [])
# returns should be a list of constants (= 5)
assert listitem(s) == a.bookkeeper.immutablevalue(5)
def test_call_five_six(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.call_five_six, [])
# returns should be a list of positive integers
assert listitem(s) == annmodel.SomeInteger(nonneg=True)
def test_constant_result(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.constant_result, [])
#a.translator.simplify()
# must return "yadda"
assert s == a.bookkeeper.immutablevalue("yadda")
graphs = a.translator.graphs
assert len(graphs) == 2
assert graphs[0].func is snippet.constant_result
assert graphs[1].func is snippet.forty_two
a.simplify()
#a.translator.view()
def test_flow_type_info(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_type_info, [int])
a.simplify()
assert s.knowntype == int
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_type_info, [str])
a.simplify()
assert s.knowntype == int
def test_flow_type_info_2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_type_info,
[annmodel.SomeInteger(nonneg=True)])
# this checks that isinstance(i, int) didn't lose the
# actually more precise information that i is non-negative
assert s == annmodel.SomeInteger(nonneg=True)
def test_flow_usertype_info(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_usertype_info, [snippet.WithInit])
#a.translator.view()
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithInit)
def test_flow_usertype_info2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_usertype_info, [snippet.WithMoreInit])
#a.translator.view()
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithMoreInit)
def test_mergefunctions(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.mergefunctions, [int])
# the test is mostly that the above line hasn't blown up
# but let's at least check *something*
assert isinstance(s, annmodel.SomePBC)
def test_func_calls_func_which_just_raises(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.funccallsex, [])
# the test is mostly that the above line hasn't blown up
# but let's at least check *something*
#self.assert_(isinstance(s, SomeCallable))
def test_tuple_unpack_from_const_tuple_with_different_types(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.func_arg_unpack, [])
assert isinstance(s, annmodel.SomeInteger)
assert s.const == 3
def test_star_unpack_list(self):
def g():
pass
def f(l):
return g(*l)
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [[int]])
def test_star_unpack_and_keywords(self):
def g(a, b, c=0, d=0):
return a + b + c + d
def f(a, b):
return g(a, *(b,), d=5)
a = self.RPythonAnnotator()
s_result = a.build_types(f, [int, int])
assert isinstance(s_result, annmodel.SomeInteger)
def test_pbc_attr_preserved_on_instance(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.preserve_pbc_attr_on_instance, [bool])
#a.simplify()
#a.translator.view()
assert s == annmodel.SomeInteger(nonneg=True)
#self.assertEquals(s.__class__, annmodel.SomeInteger)
def test_pbc_attr_preserved_on_instance_with_slots(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.preserve_pbc_attr_on_instance_with_slots,
[bool])
assert s == annmodel.SomeInteger(nonneg=True)
def test_is_and_knowntype_data(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.is_and_knowntype, [str])
#a.simplify()
#a.translator.view()
assert s == a.bookkeeper.immutablevalue(None)
def test_isinstance_and_knowntype_data(self):
a = self.RPythonAnnotator()
x = a.bookkeeper.immutablevalue(snippet.apbc)
s = a.build_types(snippet.isinstance_and_knowntype, [x])
#a.simplify()
#a.translator.view()
assert s == x
def test_somepbc_simplify(self):
a = self.RPythonAnnotator()
# this example used to trigger an AssertionError
a.build_types(snippet.somepbc_simplify, [])
def test_builtin_methods(self):
a = self.RPythonAnnotator()
iv = a.bookkeeper.immutablevalue
# this checks that some built-in methods are really supported by
# the annotator (it doesn't check that they operate property, though)
for example, methname, s_example in [
('', 'join', annmodel.SomeString()),
([], 'append', somelist(annmodel.s_Int)),
([], 'extend', somelist(annmodel.s_Int)),
([], 'reverse', somelist(annmodel.s_Int)),
([], 'insert', somelist(annmodel.s_Int)),
([], 'pop', somelist(annmodel.s_Int)),
]:
constmeth = getattr(example, methname)
s_constmeth = iv(constmeth)
assert isinstance(s_constmeth, annmodel.SomeBuiltin)
s_meth = s_example.getattr(iv(methname))
assert isinstance(s_constmeth, annmodel.SomeBuiltin)
def test_str_join(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return ["foo", "bar"]
def f(n):
g(0)
return ''.join(g(n))
s = a.build_types(f, [int])
assert s.knowntype == str
assert s.no_nul
def test_unicode_join(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return [u"foo", u"bar"]
def f(n):
g(0)
return u''.join(g(n))
s = a.build_types(f, [int])
assert s.knowntype == unicode
assert s.no_nul
def test_str_split(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return "test string"
def f(n):
if n:
return g(n).split(' ')
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeList)
s_item = s.listdef.listitem.s_value
assert s_item.no_nul
def test_unicode_split(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return u"test string"
def f(n):
if n:
return g(n).split(u' ')
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeList)
s_item = s.listdef.listitem.s_value
assert s_item.no_nul
def test_str_split_nul(self):
def f(n):
return n.split('\0')[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeString(no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeString)
assert not s.can_be_None
assert s.no_nul
def g(n):
return n.split('\0', 1)[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(g, [annmodel.SomeString(no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeString)
assert not s.can_be_None
assert not s.no_nul
def test_unicode_split_nul(self):
def f(n):
return n.split(u'\0')[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeUnicodeString(
no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeUnicodeString)
assert not s.can_be_None
assert s.no_nul
def g(n):
return n.split(u'\0', 1)[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(g, [annmodel.SomeUnicodeString(
no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeUnicodeString)
assert not s.can_be_None
assert not s.no_nul
def test_str_splitlines(self):
a = self.RPythonAnnotator()
def f(a_str):
return a_str.splitlines()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeList)
assert s.listdef.listitem.resized
def test_str_strip(self):
a = self.RPythonAnnotator()
def f(n, a_str):
if n == 0:
return a_str.strip(' ')
elif n == 1:
return a_str.rstrip(' ')
else:
return a_str.lstrip(' ')
s = a.build_types(f, [int, annmodel.SomeString(no_nul=True)])
assert s.no_nul
def test_unicode_strip(self):
a = self.RPythonAnnotator()
def f(n, a_str):
if n == 0:
return a_str.strip(u' ')
elif n == 1:
return a_str.rstrip(u' ')
else:
return a_str.lstrip(u' ')
s = a.build_types(f, [int, annmodel.SomeUnicodeString(no_nul=True)])
assert s.no_nul
def test_str_mul(self):
a = self.RPythonAnnotator()
def f(a_str):
return a_str * 3
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeString)
def test_str_isalpha(self):
def f(s):
return s.isalpha()
a = self.RPythonAnnotator()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeBool)
def test_simple_slicing(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.simple_slice, [somelist(annmodel.s_Int)])
assert isinstance(s, annmodel.SomeList)
def test_simple_iter_list(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.simple_iter, [somelist(annmodel.s_Int)])
assert isinstance(s, annmodel.SomeIterator)
def test_simple_iter_next(self):
def f(x):
i = iter(range(x))
return i.next()
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeInteger)
def test_simple_iter_dict(self):
a = self.RPythonAnnotator()
t = somedict(a, annmodel.SomeInteger(), annmodel.SomeInteger())
s = a.build_types(snippet.simple_iter, [t])
assert isinstance(s, annmodel.SomeIterator)
def test_simple_zip(self):
a = self.RPythonAnnotator()
x = somelist(annmodel.SomeInteger())
y = somelist(annmodel.SomeString())
s = a.build_types(snippet.simple_zip, [x,y])
assert s.knowntype == list
assert listitem(s).knowntype == tuple
assert listitem(s).items[0].knowntype == int
assert listitem(s).items[1].knowntype == str
def test_dict_copy(self):
a = self.RPythonAnnotator()
t = somedict(a, annmodel.SomeInteger(), annmodel.SomeInteger())
s = a.build_types(snippet.dict_copy, [t])
assert isinstance(dictkey(s), annmodel.SomeInteger)
assert isinstance(dictvalue(s), annmodel.SomeInteger)
def test_dict_update(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_update, [int])
assert isinstance(dictkey(s), annmodel.SomeInteger)
assert isinstance(dictvalue(s), annmodel.SomeInteger)
def test_dict_update_2(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return {3: 4}
def f(n):
g(0)
d = {}
d.update(g(n))
return d
s = a.build_types(f, [int])
assert dictkey(s).knowntype == int
def test_dict_keys(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_keys, [])
assert isinstance(listitem(s), annmodel.SomeString)
def test_dict_keys2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_keys2, [])
assert type(listitem(s)) is annmodel.SomeString
def test_dict_values(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_values, [])
assert isinstance(listitem(s), annmodel.SomeString)
def test_dict_values2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_values2, [])
assert type(listitem(s)) is annmodel.SomeString
def test_dict_items(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_items, [])
assert isinstance(listitem(s), annmodel.SomeTuple)
s_key, s_value = listitem(s).items
assert isinstance(s_key, annmodel.SomeString)
assert isinstance(s_value, annmodel.SomeInteger)
def test_dict_setdefault(self):
a = self.RPythonAnnotator()
def f():
d = {}
d.setdefault('a', 2)
d.setdefault('a', -3)
return d
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeDict)
assert isinstance(dictkey(s), annmodel.SomeString)
assert isinstance(dictvalue(s), annmodel.SomeInteger)
assert not dictvalue(s).nonneg
def test_dict_get(self):
def f1(i, j):
d = {i: ''}
return d.get(j)
a = self.RPythonAnnotator()
s = a.build_types(f1, [int, int])
assert isinstance(s, annmodel.SomeString)
assert s.can_be_None
def test_exception_deduction(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_exception_deduction_we_are_dumb(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_we_are_dumb, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_nested_exception_deduction(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.nested_exception_deduction, [])
assert isinstance(s, annmodel.SomeTuple)
assert isinstance(s.items[0], annmodel.SomeInstance)
assert isinstance(s.items[1], annmodel.SomeInstance)
assert s.items[0].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
assert s.items[1].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc2)
def test_exc_deduction_our_exc_plus_others(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exc_deduction_our_exc_plus_others, [])
assert isinstance(s, annmodel.SomeInteger)
def test_exc_deduction_our_excs_plus_others(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exc_deduction_our_excs_plus_others, [])
assert isinstance(s, annmodel.SomeInteger)
def test_complex_exception_deduction(self):
class InternalError(Exception):
def __init__(self, msg):
self.msg = msg
class AppError(Exception):
def __init__(self, msg):
self.msg = msg
def apperror(msg):
return AppError(msg)
def f(string):
if not string:
raise InternalError('Empty string')
return string, None
def cleanup():
pass
def g(string):
try:
try:
string, _ = f(string)
except ZeroDivisionError:
raise apperror('ZeroDivisionError')
try:
result, _ = f(string)
finally:
cleanup()
except InternalError as e:
raise apperror(e.msg)
return result
a = self.RPythonAnnotator()
s_result = a.build_types(g, [str])
assert isinstance(s_result, annmodel.SomeString)
def test_method_exception_specialization(self):
def f(l):
try:
return l.pop()
except Exception:
raise
a = self.RPythonAnnotator()
s = a.build_types(f, [[int]])
graph = graphof(a, f)
etype, evalue = graph.exceptblock.inputargs
assert evalue.annotation.classdefs == {
a.bookkeeper.getuniqueclassdef(IndexError)}
assert etype.annotation.const == IndexError
def test_operation_always_raising(self):
def operation_always_raising(n):
lst = []
try:
return lst[n]
except IndexError:
return 24
a = self.RPythonAnnotator()
s = a.build_types(operation_always_raising, [int])
assert s == a.bookkeeper.immutablevalue(24)
def test_propagation_of_fresh_instances_through_attrs(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.propagation_of_fresh_instances_through_attrs, [int])
assert s is not None
def test_propagation_of_fresh_instances_through_attrs_rec_0(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.make_r, [int])
Rdef = a.bookkeeper.getuniqueclassdef(snippet.R)
assert s.classdef == Rdef
assert Rdef.attrs['r'].s_value.classdef == Rdef
assert Rdef.attrs['n'].s_value.knowntype == int
assert Rdef.attrs['m'].s_value.knowntype == int
def test_propagation_of_fresh_instances_through_attrs_rec_eo(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.make_eo, [int])
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.B)
Even_def = a.bookkeeper.getuniqueclassdef(snippet.Even)
Odd_def = a.bookkeeper.getuniqueclassdef(snippet.Odd)
assert listitem(Even_def.attrs['x'].s_value).classdef == Odd_def
assert listitem(Even_def.attrs['y'].s_value).classdef == Even_def
assert listitem(Odd_def.attrs['x'].s_value).classdef == Even_def
assert listitem(Odd_def.attrs['y'].s_value).classdef == Odd_def
def test_flow_rev_numbers(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_rev_numbers, [int])
assert s.knowntype == int
assert not s.is_constant() # !
def test_methodcall_is_precise(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.methodcall_is_precise, [bool])
getcdef = a.bookkeeper.getuniqueclassdef
assert 'x' not in getcdef(snippet.CBase).attrs
assert (getcdef(snippet.CSub1).attrs['x'].s_value ==
a.bookkeeper.immutablevalue(42))
assert (getcdef(snippet.CSub2).attrs['x'].s_value ==
a.bookkeeper.immutablevalue('world'))
assert s == a.bookkeeper.immutablevalue(42)
def test_call_star_args(self):
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
s = a.build_types(snippet.call_star_args, [int])
assert s.knowntype == int
def test_call_star_args_multiple(self):
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
s = a.build_types(snippet.call_star_args_multiple, [int])
assert s.knowntype == int
def test_exception_deduction_with_raise1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_with_raise1, [bool])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_exception_deduction_with_raise2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_with_raise2, [bool])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_exception_deduction_with_raise3(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_with_raise3, [bool])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_type_is(self):
class B(object):
pass
class C(B):
pass
def f(x):
assert type(x) is C
return x
a = self.RPythonAnnotator()
s = a.build_types(f, [B])
assert s.classdef is a.bookkeeper.getuniqueclassdef(C)
@py.test.mark.xfail
def test_union_type_some_pbc(self):
class A(object):
name = "A"
def f(self):
return type(self)
class B(A):
name = "B"
def f(tp):
return tp
def main(n):
if n:
if n == 1:
inst = A()
else:
inst = B()
arg = inst.f()
else:
arg = B
return f(arg).name
a = self.RPythonAnnotator()
s = a.build_types(main, [int])
assert isinstance(s, annmodel.SomeString)
def test_ann_assert(self):
def assert_(x):
assert x,"XXX"
a = self.RPythonAnnotator()
s = a.build_types(assert_, [int])
assert s.const is None
def test_string_and_none(self):
def f(n):
if n:
return 'y'
else:
return 'n'
def g(n):
if n:
return 'y'
else:
return None
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.knowntype == str
assert not s.can_be_None
s = a.build_types(g, [bool])
assert s.knowntype == str
assert s.can_be_None
def test_implicit_exc(self):
def f(l):
try:
l[0]
except (KeyError, IndexError) as e:
return e
return None
a = self.RPythonAnnotator()
s = a.build_types(f, [somelist(annmodel.s_Int)])
assert s.classdef is a.bookkeeper.getuniqueclassdef(IndexError) # KeyError ignored because l is a list
def test_freeze_protocol(self):
class Stuff:
def __init__(self):
self.called = False
def _freeze_(self):
self.called = True
return True
myobj = Stuff()
a = self.RPythonAnnotator()
s = a.build_types(lambda: myobj, [])
assert myobj.called
assert isinstance(s, annmodel.SomePBC)
assert s.const == myobj
def test_cleanup_protocol(self):
class Stuff:
def __init__(self):
self.called = False
def _cleanup_(self):
self.called = True
myobj = Stuff()
a = self.RPythonAnnotator()
s = a.build_types(lambda: myobj, [])
assert myobj.called
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(Stuff)
def test_circular_mutable_getattr(self):
class C:
pass
c = C()
c.x = c
def f():
return c.x
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(C)
def test_circular_list_type(self):
def f(n):
lst = []
for i in range(n):
lst = [lst]
return lst
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert listitem(s) == s
def test_harmonic(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.harmonic, [int])
assert s.knowntype == float
# check that the list produced by range() is not mutated or resized
graph = graphof(a, snippet.harmonic)
all_vars = set().union(*[block.getvariables() for block in graph.iterblocks()])
print all_vars