4
from pypy import conftest
5
from pypy.tool.udir import udir
7
from pypy.annotation import model as annmodel
8
from pypy.annotation.annrpython import RPythonAnnotator as _RPythonAnnotator
9
from pypy.translator.translator import graphof as tgraphof
10
from pypy.annotation import policy
11
from pypy.annotation import specialize
12
from pypy.annotation.listdef import ListDef
13
from pypy.annotation.dictdef import DictDef
14
from pypy.objspace.flow.model import *
15
from pypy.rlib.rarithmetic import r_uint, base_int, r_longlong, r_ulonglong
16
from pypy.rlib import objectmodel
17
from pypy.objspace.flow import FlowObjSpace
19
from pypy.translator.test import snippet
22
return tgraphof(a.translator, func)
25
assert isinstance(s_list, annmodel.SomeList)
26
return s_list.listdef.listitem.s_value
28
def somelist(s_type=annmodel.SomeObject()):
29
return annmodel.SomeList(ListDef(None, s_type))
32
assert isinstance(s_dict, annmodel.SomeDict)
33
return s_dict.dictdef.dictkey.s_value
35
def dictvalue(s_dict):
36
assert isinstance(s_dict, annmodel.SomeDict)
37
return s_dict.dictdef.dictvalue.s_value
39
def somedict(s_key=annmodel.SomeObject(), s_value=annmodel.SomeObject()):
40
return annmodel.SomeDict(DictDef(None, s_key, s_value))
43
class TestAnnotateTestCase:
45
cls.space = FlowObjSpace()
47
def teardown_method(self, meth):
48
assert annmodel.s_Bool == annmodel.SomeBool()
50
class RPythonAnnotator(_RPythonAnnotator):
51
def build_types(self, *args):
52
s = _RPythonAnnotator.build_types(self, *args)
53
if conftest.option.view:
54
self.translator.view()
57
def make_fun(self, func):
61
except AttributeError:
64
funcgraph = self.space.build_flow(func)
65
funcgraph.source = inspect.getsource(func)
68
def test_simple_func(self):
75
result = Variable("result")
76
op = SpaceOperation("add", [x, Constant(1)], result)
78
fun = FunctionGraph("f", block)
79
block.operations.append(op)
80
block.closeblock(Link([result], fun.returnblock))
81
a = self.RPythonAnnotator()
82
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
84
assert a.gettype(fun.getreturnvar()) == int
97
conditionres = Variable("conditionres")
98
conditionop = SpaceOperation("gt", [i1, Constant(0)], conditionres)
99
decop = SpaceOperation("add", [i2, Constant(-1)], i3)
100
headerblock = Block([i1])
101
whileblock = Block([i2])
103
fun = FunctionGraph("f", headerblock)
104
headerblock.operations.append(conditionop)
105
headerblock.exitswitch = conditionres
106
headerblock.closeblock(Link([i1], fun.returnblock, False),
107
Link([i1], whileblock, True))
108
whileblock.operations.append(decop)
109
whileblock.closeblock(Link([i3], headerblock))
111
a = self.RPythonAnnotator()
112
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
114
assert a.gettype(fun.getreturnvar()) == int
116
def test_while_sum(self):
130
sum2 = Variable("sum2")
131
sum3 = Variable("sum3")
132
sum4 = Variable("sum4")
134
conditionres = Variable("conditionres")
135
conditionop = SpaceOperation("gt", [i2, Constant(0)], conditionres)
136
decop = SpaceOperation("add", [i3, Constant(-1)], i4)
137
addop = SpaceOperation("add", [i3, sum3], sum4)
138
startblock = Block([i1])
139
headerblock = Block([i2, sum2])
140
whileblock = Block([i3, sum3])
142
fun = FunctionGraph("f", startblock)
143
startblock.closeblock(Link([i1, Constant(0)], headerblock))
144
headerblock.operations.append(conditionop)
145
headerblock.exitswitch = conditionres
146
headerblock.closeblock(Link([sum2], fun.returnblock, False),
147
Link([i2, sum2], whileblock, True))
148
whileblock.operations.append(addop)
149
whileblock.operations.append(decop)
150
whileblock.closeblock(Link([i4, sum4], headerblock))
152
a = self.RPythonAnnotator()
153
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
155
assert a.gettype(fun.getreturnvar()) == int
157
def test_f_calls_g(self):
158
a = self.RPythonAnnotator()
159
s = a.build_types(f_calls_g, [int])
160
# result should be an integer
161
assert s.knowntype == int
163
def test_lists(self):
164
a = self.RPythonAnnotator()
165
end_cell = a.build_types(snippet.poor_man_rev_range, [int])
166
# result should be a list of integers
167
assert listitem(end_cell).knowntype == int
169
def test_factorial(self):
170
a = self.RPythonAnnotator()
171
s = a.build_types(snippet.factorial, [int])
172
# result should be an integer
173
assert s.knowntype == int
175
def test_factorial2(self):
176
a = self.RPythonAnnotator()
177
s = a.build_types(snippet.factorial2, [int])
178
# result should be an integer
179
assert s.knowntype == int
181
def test_build_instance(self):
182
a = self.RPythonAnnotator()
183
s = a.build_types(snippet.build_instance, [])
184
# result should be a snippet.C instance
185
assert isinstance(s, annmodel.SomeInstance)
186
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
188
def test_set_attr(self):
189
a = self.RPythonAnnotator()
190
s = a.build_types(snippet.set_attr, [])
191
# result should be an integer
192
assert s.knowntype == int
194
def test_merge_setattr(self):
195
a = self.RPythonAnnotator()
196
s = a.build_types(snippet.merge_setattr, [int])
197
# result should be an integer
198
assert s.knowntype == int
200
def test_inheritance1(self):
201
a = self.RPythonAnnotator()
202
s = a.build_types(snippet.inheritance1, [])
203
# result should be exactly:
204
assert s == annmodel.SomeTuple([
205
a.bookkeeper.immutablevalue(()),
206
annmodel.SomeInteger()
209
def test_inheritance2(self):
210
a = self.RPythonAnnotator()
211
s = a.build_types(snippet._inheritance_nonrunnable, [])
212
# result should be exactly:
213
assert s == annmodel.SomeTuple([
214
annmodel.SomeInteger(),
215
annmodel.SomeObject()
218
def test_poor_man_range(self):
219
a = self.RPythonAnnotator()
220
s = a.build_types(snippet.poor_man_range, [int])
221
# result should be a list of integers
222
assert listitem(s).knowntype == int
224
def test_methodcall1(self):
225
a = self.RPythonAnnotator()
226
s = a.build_types(snippet._methodcall1, [int])
227
# result should be a tuple of (C, positive_int)
228
assert s.knowntype == tuple
229
assert len(s.items) == 2
231
assert isinstance(s0, annmodel.SomeInstance)
232
assert s0.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
233
assert s.items[1].knowntype == int
234
assert s.items[1].nonneg == True
236
def test_classes_methodcall1(self):
237
a = self.RPythonAnnotator()
238
a.build_types(snippet._methodcall1, [int])
239
# the user classes should have the following attributes:
240
getcdef = a.bookkeeper.getuniqueclassdef
241
assert getcdef(snippet.F).attrs.keys() == ['m']
242
assert getcdef(snippet.G).attrs.keys() == ['m2']
243
assert getcdef(snippet.H).attrs.keys() == ['attr']
244
assert getcdef(snippet.H).about_attribute('attr') == (
245
a.bookkeeper.immutablevalue(1))
247
def DISABLED_test_knownkeysdict(self):
248
# disabled, SomeDict() is now a general {s_key: s_value} dict
249
a = self.RPythonAnnotator()
250
s = a.build_types(snippet.knownkeysdict, [int])
251
# result should be an integer
252
assert s.knowntype == int
254
def test_generaldict(self):
255
a = self.RPythonAnnotator()
256
s = a.build_types(snippet.generaldict, [str, int, str, int])
257
# result should be an integer
258
assert s.knowntype == int
260
def test_somebug1(self):
261
a = self.RPythonAnnotator()
262
s = a.build_types(snippet._somebug1, [int])
263
# result should be a built-in method
264
assert isinstance(s, annmodel.SomeBuiltin)
266
def test_with_init(self):
267
a = self.RPythonAnnotator()
268
s = a.build_types(snippet.with_init, [int])
269
# result should be an integer
270
assert s.knowntype == int
272
def test_with_more_init(self):
273
a = self.RPythonAnnotator()
274
s = a.build_types(snippet.with_more_init, [int, bool])
275
# the user classes should have the following attributes:
276
getcdef = a.bookkeeper.getuniqueclassdef
277
# XXX on which class should the attribute 'a' appear? We only
278
# ever flow WithInit.__init__ with a self which is an instance
279
# of WithMoreInit, so currently it appears on WithMoreInit.
280
assert getcdef(snippet.WithMoreInit).about_attribute('a') == (
281
annmodel.SomeInteger())
282
assert getcdef(snippet.WithMoreInit).about_attribute('b') == (
285
def test_global_instance(self):
286
a = self.RPythonAnnotator()
287
s = a.build_types(snippet.global_instance, [])
288
# currently this returns the constant 42.
289
# XXX not sure this is the best behavior...
290
assert s == a.bookkeeper.immutablevalue(42)
292
def test_call_five(self):
293
a = self.RPythonAnnotator()
294
s = a.build_types(snippet.call_five, [])
295
# returns should be a list of constants (= 5)
296
assert listitem(s) == a.bookkeeper.immutablevalue(5)
298
def test_call_five_six(self):
299
a = self.RPythonAnnotator()
300
s = a.build_types(snippet.call_five_six, [])
301
# returns should be a list of positive integers
302
assert listitem(s) == annmodel.SomeInteger(nonneg=True)
304
def test_constant_result(self):
305
a = self.RPythonAnnotator()
306
s = a.build_types(snippet.constant_result, [])
307
#a.translator.simplify()
308
# must return "yadda"
309
assert s == a.bookkeeper.immutablevalue("yadda")
310
graphs = a.translator.graphs
311
assert len(graphs) == 2
312
assert graphs[0].func is snippet.constant_result
313
assert graphs[1].func is snippet.forty_two
317
def test_flow_type_info(self):
318
a = self.RPythonAnnotator()
319
s = a.build_types(snippet.flow_type_info, [object])
322
assert s.knowntype == int
324
def test_flow_type_info_2(self):
325
a = self.RPythonAnnotator()
326
s = a.build_types(snippet.flow_type_info,
327
[annmodel.SomeInteger(nonneg=True)])
328
# this checks that isinstance(i, int) didn't lose the
329
# actually more precise information that i is non-negative
330
assert s == annmodel.SomeInteger(nonneg=True)
332
def test_flow_usertype_info(self):
333
a = self.RPythonAnnotator()
334
s = a.build_types(snippet.flow_usertype_info, [object])
336
assert isinstance(s, annmodel.SomeInstance)
337
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithInit)
339
def test_flow_usertype_info2(self):
340
a = self.RPythonAnnotator()
341
s = a.build_types(snippet.flow_usertype_info, [snippet.WithMoreInit])
343
assert isinstance(s, annmodel.SomeInstance)
344
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithMoreInit)
346
def test_flow_identity_info(self):
347
a = self.RPythonAnnotator()
348
s = a.build_types(snippet.flow_identity_info, [object, object])
351
assert s == a.bookkeeper.immutablevalue((None, None))
353
def test_mergefunctions(self):
354
a = self.RPythonAnnotator()
355
s = a.build_types(snippet.mergefunctions, [int])
356
# the test is mostly that the above line hasn't blown up
357
# but let's at least check *something*
358
assert isinstance(s, annmodel.SomePBC)
360
def test_func_calls_func_which_just_raises(self):
361
a = self.RPythonAnnotator()
362
s = a.build_types(snippet.funccallsex, [])
363
# the test is mostly that the above line hasn't blown up
364
# but let's at least check *something*
365
#self.assert_(isinstance(s, SomeCallable))
367
def test_tuple_unpack_from_const_tuple_with_different_types(self):
368
a = self.RPythonAnnotator()
369
s = a.build_types(snippet.func_arg_unpack, [])
370
assert isinstance(s, annmodel.SomeInteger)
373
def test_pbc_attr_preserved_on_instance(self):
374
a = self.RPythonAnnotator()
375
s = a.build_types(snippet.preserve_pbc_attr_on_instance, [bool])
378
assert s == annmodel.SomeInteger(nonneg=True)
379
#self.assertEquals(s.__class__, annmodel.SomeInteger)
381
def test_pbc_attr_preserved_on_instance_with_slots(self):
382
a = self.RPythonAnnotator()
383
s = a.build_types(snippet.preserve_pbc_attr_on_instance_with_slots,
385
assert s == annmodel.SomeInteger(nonneg=True)
387
def test_is_and_knowntype_data(self):
388
a = self.RPythonAnnotator()
389
s = a.build_types(snippet.is_and_knowntype, [str])
392
assert s == a.bookkeeper.immutablevalue(None)
394
def test_isinstance_and_knowntype_data(self):
395
a = self.RPythonAnnotator()
396
x = a.bookkeeper.immutablevalue(snippet.apbc)
397
s = a.build_types(snippet.isinstance_and_knowntype, [x])
402
def test_somepbc_simplify(self):
403
a = self.RPythonAnnotator()
404
# this example used to trigger an AssertionError
405
a.build_types(snippet.somepbc_simplify, [])
407
def test_builtin_methods(self):
408
a = self.RPythonAnnotator()
409
iv = a.bookkeeper.immutablevalue
410
# this checks that some built-in methods are really supported by
411
# the annotator (it doesn't check that they operate property, though)
412
for example, methname, s_example in [
413
('', 'join', annmodel.SomeString()),
414
([], 'append', somelist()),
415
([], 'extend', somelist()),
416
([], 'reverse', somelist()),
417
([], 'insert', somelist()),
418
([], 'pop', somelist()),
420
constmeth = getattr(example, methname)
421
s_constmeth = iv(constmeth)
422
assert isinstance(s_constmeth, annmodel.SomeBuiltin)
423
s_meth = s_example.getattr(iv(methname))
424
assert isinstance(s_constmeth, annmodel.SomeBuiltin)
426
def test_simple_slicing0(self):
427
a = self.RPythonAnnotator()
428
a.build_types(snippet.simple_slice, [list])
429
g = graphof(a, snippet.simple_slice)
430
for block in g.iterblocks():
431
for op in block.operations:
432
if op.opname == "newslice":
433
assert isinstance(a.binding(op.result),
436
def test_simple_slicing(self):
437
a = self.RPythonAnnotator()
438
s = a.build_types(snippet.simple_slice, [list])
439
assert isinstance(s, annmodel.SomeList)
441
def test_simple_iter_list(self):
442
a = self.RPythonAnnotator()
443
s = a.build_types(snippet.simple_iter, [list])
444
assert isinstance(s, annmodel.SomeIterator)
446
def test_simple_iter_next(self):
450
a = self.RPythonAnnotator()
451
s = a.build_types(f, [int])
452
assert isinstance(s, annmodel.SomeInteger)
454
def test_simple_iter_dict(self):
455
a = self.RPythonAnnotator()
456
t = somedict(annmodel.SomeInteger(), annmodel.SomeInteger())
457
s = a.build_types(snippet.simple_iter, [t])
458
assert isinstance(s, annmodel.SomeIterator)
460
def test_simple_zip(self):
461
a = self.RPythonAnnotator()
462
x = somelist(annmodel.SomeInteger())
463
y = somelist(annmodel.SomeString())
464
s = a.build_types(snippet.simple_zip, [x,y])
465
assert s.knowntype == list
466
assert listitem(s).knowntype == tuple
467
assert listitem(s).items[0].knowntype == int
468
assert listitem(s).items[1].knowntype == str
470
def test_dict_copy(self):
471
a = self.RPythonAnnotator()
472
t = somedict(annmodel.SomeInteger(), annmodel.SomeInteger())
473
s = a.build_types(snippet.dict_copy, [t])
474
assert isinstance(dictkey(s), annmodel.SomeInteger)
475
assert isinstance(dictvalue(s), annmodel.SomeInteger)
477
def test_dict_update(self):
478
a = self.RPythonAnnotator()
479
s = a.build_types(snippet.dict_update, [int])
480
assert isinstance(dictkey(s), annmodel.SomeInteger)
481
assert isinstance(dictvalue(s), annmodel.SomeInteger)
483
a = self.RPythonAnnotator()
484
s = a.build_types(snippet.dict_update, [str])
485
assert not isinstance(dictkey(s), annmodel.SomeString)
486
assert not isinstance(dictvalue(s), annmodel.SomeString)
488
def test_dict_keys(self):
489
a = self.RPythonAnnotator()
490
s = a.build_types(snippet.dict_keys, [])
491
assert isinstance(listitem(s), annmodel.SomeString)
493
def test_dict_keys2(self):
494
a = self.RPythonAnnotator()
495
s = a.build_types(snippet.dict_keys2, [])
496
assert not isinstance(listitem(s), annmodel.SomeString)
498
def test_dict_values(self):
499
a = self.RPythonAnnotator()
500
s = a.build_types(snippet.dict_values, [])
501
assert isinstance(listitem(s), annmodel.SomeString)
503
def test_dict_values2(self):
504
a = self.RPythonAnnotator()
505
s = a.build_types(snippet.dict_values2, [])
506
assert not isinstance(listitem(s), annmodel.SomeString)
508
def test_dict_items(self):
509
a = self.RPythonAnnotator()
510
s = a.build_types(snippet.dict_items, [])
511
assert isinstance(listitem(s), annmodel.SomeTuple)
512
s_key, s_value = listitem(s).items
513
assert isinstance(s_key, annmodel.SomeString)
514
assert isinstance(s_value, annmodel.SomeInteger)
516
def test_dict_setdefault(self):
517
a = self.RPythonAnnotator()
521
d.setdefault('a', -3)
523
s = a.build_types(f, [])
524
assert isinstance(s, annmodel.SomeDict)
525
assert isinstance(dictkey(s), annmodel.SomeString)
526
assert isinstance(dictvalue(s), annmodel.SomeInteger)
527
assert not dictvalue(s).nonneg
529
def test_exception_deduction(self):
530
a = self.RPythonAnnotator()
531
s = a.build_types(snippet.exception_deduction, [])
532
assert isinstance(s, annmodel.SomeInstance)
533
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
535
def test_exception_deduction_we_are_dumb(self):
536
a = self.RPythonAnnotator()
537
s = a.build_types(snippet.exception_deduction_we_are_dumb, [])
538
assert isinstance(s, annmodel.SomeInstance)
539
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
541
def test_nested_exception_deduction(self):
542
a = self.RPythonAnnotator()
543
s = a.build_types(snippet.nested_exception_deduction, [])
544
assert isinstance(s, annmodel.SomeTuple)
545
assert isinstance(s.items[0], annmodel.SomeInstance)
546
assert isinstance(s.items[1], annmodel.SomeInstance)
547
assert s.items[0].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
548
assert s.items[1].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc2)
550
def test_exc_deduction_our_exc_plus_others(self):
551
a = self.RPythonAnnotator()
552
s = a.build_types(snippet.exc_deduction_our_exc_plus_others, [])
553
assert isinstance(s, annmodel.SomeInteger)
555
def test_exc_deduction_our_excs_plus_others(self):
556
a = self.RPythonAnnotator()
557
s = a.build_types(snippet.exc_deduction_our_excs_plus_others, [])
558
assert isinstance(s, annmodel.SomeInteger)
560
def test_operation_always_raising(self):
561
def operation_always_raising(n):
567
a = self.RPythonAnnotator()
568
s = a.build_types(operation_always_raising, [int])
569
assert s == a.bookkeeper.immutablevalue(24)
571
def test_slice_union(self):
572
a = self.RPythonAnnotator()
573
s = a.build_types(snippet.slice_union, [int])
574
assert isinstance(s, annmodel.SomeSlice)
576
def test_bltin_code_frame_confusion(self):
577
a = self.RPythonAnnotator()
578
a.build_types(snippet.bltin_code_frame_confusion,[])
579
f_flowgraph = graphof(a, snippet.bltin_code_frame_f)
580
g_flowgraph = graphof(a, snippet.bltin_code_frame_g)
581
# annotator confused by original bltin code/frame setup, we just get SomeObject here
582
assert a.binding(f_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject
583
assert a.binding(g_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject
585
def test_bltin_code_frame_reorg(self):
586
a = self.RPythonAnnotator()
587
a.build_types(snippet.bltin_code_frame_reorg,[])
588
f_flowgraph = graphof(a, snippet.bltin_code_frame_f)
589
g_flowgraph = graphof(a, snippet.bltin_code_frame_g)
590
assert isinstance(a.binding(f_flowgraph.getreturnvar()),
591
annmodel.SomeInteger)
592
assert isinstance(a.binding(g_flowgraph.getreturnvar()),
595
def test_propagation_of_fresh_instances_through_attrs(self):
596
a = self.RPythonAnnotator()
597
s = a.build_types(snippet.propagation_of_fresh_instances_through_attrs, [int])
600
def test_propagation_of_fresh_instances_through_attrs_rec_0(self):
601
a = self.RPythonAnnotator()
602
s = a.build_types(snippet.make_r, [int])
603
Rdef = a.bookkeeper.getuniqueclassdef(snippet.R)
604
assert s.classdef == Rdef
605
assert Rdef.attrs['r'].s_value.classdef == Rdef
606
assert Rdef.attrs['n'].s_value.knowntype == int
607
assert Rdef.attrs['m'].s_value.knowntype == int
610
def test_propagation_of_fresh_instances_through_attrs_rec_eo(self):
611
a = self.RPythonAnnotator()
612
s = a.build_types(snippet.make_eo, [int])
613
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.B)
614
Even_def = a.bookkeeper.getuniqueclassdef(snippet.Even)
615
Odd_def = a.bookkeeper.getuniqueclassdef(snippet.Odd)
616
assert listitem(Even_def.attrs['x'].s_value).classdef == Odd_def
617
assert listitem(Even_def.attrs['y'].s_value).classdef == Even_def
618
assert listitem(Odd_def.attrs['x'].s_value).classdef == Even_def
619
assert listitem(Odd_def.attrs['y'].s_value).classdef == Odd_def
621
def test_flow_rev_numbers(self):
622
a = self.RPythonAnnotator()
623
s = a.build_types(snippet.flow_rev_numbers, [int])
624
assert s.knowntype == int
625
assert not s.is_constant() # !
627
def test_methodcall_is_precise(self):
628
a = self.RPythonAnnotator()
629
s = a.build_types(snippet.methodcall_is_precise, [bool])
630
getcdef = a.bookkeeper.getuniqueclassdef
631
assert 'x' not in getcdef(snippet.CBase).attrs
632
assert (getcdef(snippet.CSub1).attrs['x'].s_value ==
633
a.bookkeeper.immutablevalue(42))
634
assert (getcdef(snippet.CSub2).attrs['x'].s_value ==
635
a.bookkeeper.immutablevalue('world'))
636
assert s == a.bookkeeper.immutablevalue(42)
638
def test_call_star_args(self):
639
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
640
s = a.build_types(snippet.call_star_args, [int])
641
assert s.knowntype == int
643
def test_call_star_args_multiple(self):
644
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
645
s = a.build_types(snippet.call_star_args_multiple, [int])
646
assert s.knowntype == int
648
def test_class_spec(self):
649
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
650
s = a.build_types(snippet.class_spec, [])
651
assert s.items[0].knowntype == int
652
assert s.items[1].knowntype == str
654
def test_class_spec_confused(self):
655
x = snippet.PolyStk()
658
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
659
py.test.raises(Exception, a.build_types, f, [])
661
def test_exception_deduction_with_raise1(self):
662
a = self.RPythonAnnotator()
663
s = a.build_types(snippet.exception_deduction_with_raise1, [bool])
664
assert isinstance(s, annmodel.SomeInstance)
665
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
668
def test_exception_deduction_with_raise2(self):
669
a = self.RPythonAnnotator()
670
s = a.build_types(snippet.exception_deduction_with_raise2, [bool])
671
assert isinstance(s, annmodel.SomeInstance)
672
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
674
def test_exception_deduction_with_raise3(self):
675
a = self.RPythonAnnotator()
676
s = a.build_types(snippet.exception_deduction_with_raise3, [bool])
677
assert isinstance(s, annmodel.SomeInstance)
678
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
680
def test_type_is(self):
687
a = self.RPythonAnnotator()
688
s = a.build_types(f, [object])
689
assert s.classdef is a.bookkeeper.getuniqueclassdef(C)
691
def test_ann_assert(self):
694
a = self.RPythonAnnotator()
695
s = a.build_types(assert_, [int])
696
assert s.const is None
698
def test_string_and_none(self):
709
a = self.RPythonAnnotator()
710
s = a.build_types(f, [bool])
711
assert s.knowntype == str
712
assert not s.can_be_None
713
s = a.build_types(g, [bool])
714
assert s.knowntype == str
717
def test_implicit_exc(self):
721
except (KeyError, IndexError),e:
725
a = self.RPythonAnnotator()
726
s = a.build_types(f, [list])
727
assert s.classdef is a.bookkeeper.getuniqueclassdef(IndexError) # KeyError ignored because l is a list
729
def test_overrides(self):
734
excs.append(sys.exc_info)
735
record_exc._annspecialcase_ = "override:record_exc"
743
class MyAnnotatorPolicy(policy.AnnotatorPolicy):
745
def override__record_exc(pol, s_e):
746
return a.bookkeeper.immutablevalue(None)
748
a = self.RPythonAnnotator(policy=MyAnnotatorPolicy())
749
s = a.build_types(f, [])
750
assert s.const is None
752
def test_freeze_protocol(self):
754
def __init__(self, flag):
761
a = self.RPythonAnnotator()
762
s = a.build_types(lambda: myobj, [])
764
assert isinstance(s, annmodel.SomePBC)
765
assert s.const == myobj
767
a = self.RPythonAnnotator()
768
s = a.build_types(lambda: myobj, [])
770
assert isinstance(s, annmodel.SomeInstance)
771
assert s.classdef is a.bookkeeper.getuniqueclassdef(Stuff)
773
def test_circular_mutable_getattr(self):
780
a = self.RPythonAnnotator()
781
s = a.build_types(f, [])
782
assert isinstance(s, annmodel.SomeInstance)
783
assert s.classdef == a.bookkeeper.getuniqueclassdef(C)
785
def test_circular_list_type(self):
791
a = self.RPythonAnnotator()
792
s = a.build_types(f, [int])
793
assert listitem(s) == s
795
def test_harmonic(self):
796
a = self.RPythonAnnotator()
797
s = a.build_types(snippet.harmonic, [int])
798
assert s.knowntype == float
799
# check that the list produced by range() is not mutated or resized
800
for s_value in a.bindings.values():
801
if isinstance(s_value, annmodel.SomeList):
802
assert not s_value.listdef.listitem.resized
803
assert not s_value.listdef.listitem.mutated
804
assert s_value.listdef.listitem.range_step
808
return bool(a) or bool(b)
809
a = self.RPythonAnnotator()
810
s = a.build_types(f, [int,list])
811
assert s.knowntype == bool
813
def test_float(self):
816
a = self.RPythonAnnotator()
817
s = a.build_types(f, [int])
818
assert s.knowntype == float
820
def test_r_uint(self):
822
return n + constant_unsigned_five
823
a = self.RPythonAnnotator()
824
s = a.build_types(f, [r_uint])
825
assert s == annmodel.SomeInteger(nonneg = True, unsigned = True)
827
def test_pbc_getattr(self):
829
def __init__(self, v1, v2):
854
a = self.RPythonAnnotator()
855
s = a.build_types(g,[])
857
assert listitem(l1).knowntype == int
858
assert listitem(l2).knowntype == str
861
acc1 = a.bookkeeper.getdesc(c1).getattrfamily()
862
acc2 = a.bookkeeper.getdesc(c2).getattrfamily()
863
acc3 = a.bookkeeper.getdesc(c3).getattrfamily()
865
assert acc1 is acc2 is acc3
867
assert len(acc1.descs) == 3
868
assert dict.fromkeys(acc1.attrs) == {'v1': None, 'v2': None}
870
def test_single_pbc_getattr(self):
872
def __init__(self, v1, v2):
889
return l, f2(c1), f3(c2)
891
a = self.RPythonAnnotator()
892
s = a.build_types(g,[])
893
s_l, s_c1v2, s_c2v2 = s.items
894
assert listitem(s_l).knowntype == int
895
assert s_c1v2.const == "hello"
896
assert s_c2v2.const == 623
898
acc1 = a.bookkeeper.getdesc(c1).getattrfamily()
899
acc2 = a.bookkeeper.getdesc(c2).getattrfamily()
901
assert acc1.attrs.keys() == ['v1']
903
def test_simple_pbc_call(self):
918
a = self.RPythonAnnotator()
919
s = a.build_types(h, [])
921
fdesc1 = a.bookkeeper.getdesc(f1)
922
fdesc2 = a.bookkeeper.getdesc(f2)
923
fdesc3 = a.bookkeeper.getdesc(f3)
925
fam1 = fdesc1.getcallfamily()
926
fam2 = fdesc2.getcallfamily()
927
fam3 = fdesc3.getcallfamily()
929
assert fam1 is not fam2
930
assert fam1 is not fam3
937
assert fam1.calltables == {(2, (), False, False): [{fdesc1: gf1}], (1, (), False, False): [{fdesc1: gf1}]}
938
assert fam2.calltables == {(1, (), False, False): [{fdesc2: gf2, fdesc3: gf3}]}
940
def test_pbc_call_ins(self):
962
a = self.RPythonAnnotator()
963
s = a.build_types(f, [bool])
965
clsdef = a.bookkeeper.getuniqueclassdef
966
bookkeeper = a.bookkeeper
969
return bookkeeper.immutablevalue(bmeth).descriptions.keys()[0]
971
mdescA_m = getmdesc(A().m)
972
mdescC_m = getmdesc(C().m)
973
mdescB_n = getmdesc(B().n)
975
assert mdescA_m.name == 'm' == mdescC_m.name
976
assert mdescB_n.name == 'n'
978
famA_m = mdescA_m.getcallfamily()
979
famC_m = mdescC_m.getcallfamily()
980
famB_n = mdescB_n.getcallfamily()
982
assert famA_m is famC_m
983
assert famB_n is not famA_m
985
gfB_n = graphof(a, B.n.im_func)
986
gfA_m = graphof(a, A.m.im_func)
987
gfC_m = graphof(a, C.m.im_func)
989
assert famB_n.calltables == {(1, (), False, False): [{mdescB_n.funcdesc: gfB_n}] }
990
assert famA_m.calltables == {(1, (), False, False): [{mdescA_m.funcdesc: gfA_m, mdescC_m.funcdesc: gfC_m }] }
992
mdescCinit = getmdesc(C().__init__)
993
famCinit = mdescCinit.getcallfamily()
994
gfCinit = graphof(a, C.__init__.im_func)
996
assert famCinit.calltables == {(1, (), False, False): [{mdescCinit.funcdesc: gfCinit}] }
998
def test_isinstance_usigned(self):
1000
return isinstance(x, r_uint)
1004
a = self.RPythonAnnotator()
1005
s = a.build_types(g, [])
1006
assert s.const == True
1008
def test_isinstance_base_int(self):
1010
return isinstance(x, base_int)
1014
a = self.RPythonAnnotator()
1015
s = a.build_types(g, [int])
1016
assert s.const == True
1018
def test_alloc_like(self):
1029
assert isinstance(i, cls)
1031
alloc._annspecialcase_ = "specialize:arg(0)"
1038
a = self.RPythonAnnotator()
1039
s = a.build_types(f, [])
1040
C1df = a.bookkeeper.getuniqueclassdef(C1)
1041
C2df = a.bookkeeper.getuniqueclassdef(C2)
1043
assert s.items[0].classdef == C1df
1044
assert s.items[1].classdef == C2df
1046
allocdesc = a.bookkeeper.getdesc(alloc)
1047
s_C1 = a.bookkeeper.immutablevalue(C1)
1048
s_C2 = a.bookkeeper.immutablevalue(C2)
1049
graph1 = allocdesc.specialize([s_C1])
1050
graph2 = allocdesc.specialize([s_C2])
1051
assert a.binding(graph1.getreturnvar()).classdef == C1df
1052
assert a.binding(graph2.getreturnvar()).classdef == C2df
1053
assert graph1 in a.translator.graphs
1054
assert graph2 in a.translator.graphs
1056
def test_specialcase_args(self):
1063
def alloc(cls, cls2):
1065
assert isinstance(i, cls)
1067
assert isinstance(j, cls2)
1076
alloc._annspecialcase_ = "specialize:arg(0,1)"
1078
a = self.RPythonAnnotator()
1079
C1df = a.bookkeeper.getuniqueclassdef(C1)
1080
C2df = a.bookkeeper.getuniqueclassdef(C2)
1081
s = a.build_types(f, [])
1082
allocdesc = a.bookkeeper.getdesc(alloc)
1083
s_C1 = a.bookkeeper.immutablevalue(C1)
1084
s_C2 = a.bookkeeper.immutablevalue(C2)
1085
graph1 = allocdesc.specialize([s_C1, s_C2])
1086
graph2 = allocdesc.specialize([s_C2, s_C2])
1087
assert a.binding(graph1.getreturnvar()).classdef == C1df
1088
assert a.binding(graph2.getreturnvar()).classdef == C2df
1089
assert graph1 in a.translator.graphs
1090
assert graph2 in a.translator.graphs
1092
def test_assert_list_doesnt_lose_info(self):
1096
assert isinstance(l, list)
1101
a = self.RPythonAnnotator()
1102
s = a.build_types(f, [])
1103
s_item = listitem(s)
1104
assert isinstance(s_item, annmodel.SomeInstance)
1105
assert s_item.classdef is a.bookkeeper.getuniqueclassdef(T)
1107
def test_assert_type_is_list_doesnt_lose_info(self):
1111
assert type(l) is list
1116
a = self.RPythonAnnotator()
1117
s = a.build_types(f, [])
1118
s_item = listitem(s)
1119
assert isinstance(s_item, annmodel.SomeInstance)
1120
assert s_item.classdef is a.bookkeeper.getuniqueclassdef(T)
1123
def test_int_str_mul(self):
1126
a = self.RPythonAnnotator()
1127
s = a.build_types(f, [str,int,int])
1128
assert s.knowntype == str
1130
def test_list_tuple(self):
1144
a = self.RPythonAnnotator()
1145
s = a.build_types(f, [bool])
1146
assert listitem(s.items[0]) == annmodel.SomeImpossibleValue()
1147
assert listitem(s.items[1]).knowntype == int
1148
assert listitem(s.items[2]).knowntype == int
1150
def test_empty_list(self):
1160
a = self.RPythonAnnotator()
1161
s = a.build_types(f, [])
1162
assert s.const == False
1164
a = self.RPythonAnnotator()
1165
s = a.build_types(g, [])
1167
assert s.items[0].knowntype == bool and not s.items[0].is_constant()
1168
assert s.items[1].knowntype == bool and not s.items[1].is_constant()
1170
def test_empty_dict(self):
1180
a = self.RPythonAnnotator()
1181
s = a.build_types(f, [])
1182
assert s.const == False
1184
a = self.RPythonAnnotator()
1185
s = a.build_types(g, [])
1187
assert s.items[0].knowntype == bool and not s.items[0].is_constant()
1188
assert s.items[1].knowntype == bool and not s.items[1].is_constant()
1190
def test_call_two_funcs_but_one_can_only_raise(self):
1191
a = self.RPythonAnnotator()
1192
s = a.build_types(snippet.call_two_funcs_but_one_can_only_raise,
1194
assert s == a.bookkeeper.immutablevalue(None)
1196
def test_reraiseKeyError(self):
1202
a = self.RPythonAnnotator()
1203
a.build_types(f, [dict])
1205
et, ev = fg.exceptblock.inputargs
1206
t = annmodel.SomeObject()
1210
assert a.binding(et) == t
1211
assert isinstance(a.binding(ev), annmodel.SomeInstance) and a.binding(ev).classdef == a.bookkeeper.getuniqueclassdef(KeyError)
1213
def test_reraiseAnything(self):
1219
a = self.RPythonAnnotator()
1220
a.build_types(f, [dict])
1222
et, ev = fg.exceptblock.inputargs
1223
t = annmodel.SomeObject()
1226
t.const = KeyError # IndexError ignored because 'dic' is a dict
1227
assert a.binding(et) == t
1228
assert isinstance(a.binding(ev), annmodel.SomeInstance) and a.binding(ev).classdef == a.bookkeeper.getuniqueclassdef(KeyError)
1230
def test_exception_mixing(self):
1238
def __init__(self, x=0):
1255
a = self.RPythonAnnotator()
1256
a.build_types(f, [int, list])
1258
et, ev = fg.exceptblock.inputargs
1259
t = annmodel.SomeObject()
1262
assert a.binding(et) == t
1263
assert isinstance(a.binding(ev), annmodel.SomeInstance) and a.binding(ev).classdef == a.bookkeeper.getuniqueclassdef(Exception)
1265
def test_try_except_raise_finally1(self):
1268
class X(Exception): pass
1278
a = self.RPythonAnnotator()
1279
a.build_types(f, [])
1281
et, ev = fg.exceptblock.inputargs
1282
t = annmodel.SomeObject()
1285
assert a.binding(et) == t
1286
assert isinstance(a.binding(ev), annmodel.SomeInstance) and a.binding(ev).classdef == a.bookkeeper.getuniqueclassdef(Exception)
1288
def test_sys_attrs(self):
1292
a = self.RPythonAnnotator()
1296
s = a.build_types(f, [])
1299
assert s is not None
1305
a = self.RPythonAnnotator()
1306
s = a.build_types(f, [int])
1307
# result should be an integer
1308
assert s.knowntype == int
1310
def test_prime(self):
1311
a = self.RPythonAnnotator()
1312
s = a.build_types(snippet.prime, [int])
1313
assert s.knowntype == bool
1315
def test_and_is_true_coalesce(self):
1321
a = self.RPythonAnnotator()
1322
s = a.build_types(f, [int, str, a.bookkeeper.immutablevalue(1.0), a.bookkeeper.immutablevalue('d'), a.bookkeeper.immutablevalue('e')])
1323
assert s == annmodel.SomeTuple([annmodel.SomeChar(), a.bookkeeper.immutablevalue(1.0)])
1324
assert not [b for b in a.bindings.itervalues() if b.__class__ == annmodel.SomeObject]
1326
def test_is_true_coalesce2(self):
1327
def f(a,b,a1,b1,c,d,e):
1328
x = (a or b) and (a1 or b1)
1332
a = self.RPythonAnnotator()
1333
s = a.build_types(f, [int, str, float, list, a.bookkeeper.immutablevalue(1.0), a.bookkeeper.immutablevalue('d'), a.bookkeeper.immutablevalue('e')])
1334
assert s == annmodel.SomeTuple([annmodel.SomeChar(), a.bookkeeper.immutablevalue(1.0)])
1335
assert not [b for b in a.bindings.itervalues() if b.__class__ == annmodel.SomeObject]
1337
def test_is_true_coalesce_sanity(self):
1341
a = self.RPythonAnnotator()
1342
s = a.build_types(f, [int])
1343
assert s == a.bookkeeper.immutablevalue(None)
1345
def test_non_None_path(self):
1358
a = self.RPythonAnnotator()
1359
s = a.build_types(f, [bool])
1360
assert s.can_be_none() == False
1362
def test_can_be_None_path(self):
1370
return isinstance(c, C)
1371
a = self.RPythonAnnotator()
1372
s = a.build_types(f, [bool])
1373
assert not s.is_constant()
1375
def test_nonneg_cleverness(self):
1376
def f(a, b, c, d, e, f, g, h):
1388
return a, b, c, d, e, f, g, h
1389
a = self.RPythonAnnotator()
1390
s = a.build_types(f, [int]*8)
1391
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True)] * 8)
1393
def test_general_nonneg_cleverness(self):
1394
def f(a, b, c, d, e, f, g, h):
1406
return a, b, c, d, e, f, g, h
1407
a = self.RPythonAnnotator()
1408
s = a.build_types(f, [r_longlong]*8)
1409
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True, knowntype=r_longlong)] * 8)
1412
def test_more_nonneg_cleverness(self):
1414
assert 0 <= start <= stop
1416
a = self.RPythonAnnotator()
1417
s = a.build_types(f, [int, int])
1418
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True)] * 2)
1420
def test_more_general_nonneg_cleverness(self):
1422
assert 0 <= start <= stop
1424
a = self.RPythonAnnotator()
1425
s = a.build_types(f, [r_longlong, r_longlong])
1426
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True, knowntype=r_longlong)] * 2)
1428
def test_nonneg_cleverness_is_gentle_with_unsigned(self):
1438
a = self.RPythonAnnotator()
1439
s = a.build_types(f, [annmodel.SomeInteger(unsigned=True)])
1440
wg1 = graphof(a, witness1)
1441
wg2 = graphof(a, witness2)
1442
assert a.binding(wg1.getargs()[0]).unsigned is True
1443
assert a.binding(wg2.getargs()[0]).unsigned is True
1445
def test_general_nonneg_cleverness_is_gentle_with_unsigned(self):
1455
a = self.RPythonAnnotator()
1456
s = a.build_types(f, [annmodel.SomeInteger(knowntype=r_ulonglong)])
1457
wg1 = graphof(a, witness1)
1458
wg2 = graphof(a, witness2)
1459
assert a.binding(wg1.getargs()[0]).knowntype is r_ulonglong
1460
assert a.binding(wg2.getargs()[0]).knowntype is r_ulonglong
1462
def test_nonneg_cleverness_in_max(self):
1464
return max(x, 0) + max(0, x)
1465
a = self.RPythonAnnotator()
1466
s = a.build_types(f, [int])
1469
def test_attr_moving_into_parent(self):
1478
a = self.RPythonAnnotator()
1479
s = a.build_types(f, [])
1480
assert isinstance(s, annmodel.SomeInstance)
1481
assert not s.can_be_None
1482
assert s.classdef is a.bookkeeper.getuniqueclassdef(A)
1484
def test_class_attribute(self):
1492
a = self.RPythonAnnotator()
1493
s = a.build_types(f, [])
1494
assert s == a.bookkeeper.immutablevalue(42)
1496
def test_attr_recursive_getvalue(self):
1504
a = self.RPythonAnnotator()
1505
s = a.build_types(f, [])
1506
assert isinstance(s, annmodel.SomeInstance)
1507
assert s.can_be_None
1508
assert s.classdef is a.bookkeeper.getuniqueclassdef(A)
1510
def test_long_list_recursive_getvalue(self):
1513
for i in range(500):
1519
return (A().stuff, lst)[1]
1520
a = self.RPythonAnnotator()
1521
s = a.build_types(f, [])
1522
assert isinstance(s, annmodel.SomeList)
1523
s_item = s.listdef.listitem.s_value
1524
assert isinstance(s_item, annmodel.SomeInstance)
1526
def test_immutable_dict(self):
1531
a = self.RPythonAnnotator()
1532
s = a.build_types(f, [int])
1533
assert isinstance(s, annmodel.SomeString)
1535
def test_immutable_recursive_list(self):
1540
a = self.RPythonAnnotator()
1541
s = a.build_types(f, [])
1542
assert isinstance(s, annmodel.SomeList)
1543
s_item = s.listdef.listitem.s_value
1544
assert isinstance(s_item, annmodel.SomeList)
1545
assert s_item.listdef.same_as(s.listdef)
1547
def test_defaults_with_list_or_dict(self):
1555
return fn1([6, 7]), fn2({2: 3, 4: 5})
1556
a = self.RPythonAnnotator()
1557
s = a.build_types(f, [])
1558
assert isinstance(s, annmodel.SomeTuple)
1560
assert not s1.is_constant()
1561
assert not s2.is_constant()
1562
assert isinstance(s1.listdef.listitem. s_value, annmodel.SomeInteger)
1563
assert isinstance(s2.dictdef.dictkey. s_value, annmodel.SomeInteger)
1564
assert isinstance(s2.dictdef.dictvalue.s_value, annmodel.SomeInteger)
1566
def test_pbc_union(self):
1581
a = self.RPythonAnnotator()
1582
s = a.build_types(f, [int])
1583
assert s == a.bookkeeper.immutablevalue(12)
1587
return int(x) + int(s) + int(s, 16)
1588
a = self.RPythonAnnotator()
1589
s = a.build_types(f, [int, str])
1590
assert s.knowntype == int
1592
def test_listitem_merge_asymmetry_bug(self):
1596
k.l2 = [x] + k.l2 # this involves a side-effectful union and unification, with this order
1597
# of arguments some reflowing was missed
1603
for i in range(len(l)):
1605
def f(flag, k, x, i):
1612
a = self.RPythonAnnotator()
1613
a.build_types(f, [bool, K, int, int])
1614
g = graphof(a, witness)
1615
assert a.binding(g.getargs()[0]).knowntype == int
1617
# check RPython static semantics of isinstance(x,bool|int) as needed for wrap
1619
def test_isinstance_int_bool(self):
1621
if isinstance(x, int):
1622
if isinstance(x, bool):
1626
a = self.RPythonAnnotator()
1627
s = a.build_types(f, [bool])
1628
assert s.const == "bool"
1629
a = self.RPythonAnnotator()
1630
s = a.build_types(f, [int])
1631
assert s.const == "int"
1632
a = self.RPythonAnnotator()
1633
s = a.build_types(f, [float])
1634
assert s.const == "dontknow"
1636
def test_hidden_method(self):
1639
return ["should be hidden"]
1641
return self.method()
1645
class B(A): # note: it's a chain of subclasses
1653
return obj.indirect()
1654
a = self.RPythonAnnotator()
1655
s = a.build_types(f, [bool])
1656
assert s == annmodel.SomeString(can_be_None=True)
1658
def test_dont_see_AttributeError_clause(self):
1662
def createcompiler(self):
1664
return self.default_compiler
1665
except AttributeError:
1667
self.default_compiler = compiler
1670
stuff.default_compiler = 123
1672
return stuff.createcompiler()
1673
a = self.RPythonAnnotator()
1674
s = a.build_types(f, [])
1675
assert s == a.bookkeeper.immutablevalue(123)
1677
def test_class_attribute_is_an_instance_of_itself(self):
1682
A.hello = globalA = A()
1684
return (Base().hello, globalA)
1685
a = self.RPythonAnnotator()
1686
s = a.build_types(f, [])
1687
assert isinstance(s, annmodel.SomeTuple)
1688
assert isinstance(s.items[0], annmodel.SomeInstance)
1689
assert s.items[0].classdef is a.bookkeeper.getuniqueclassdef(A)
1690
assert s.items[0].can_be_None
1691
assert s.items[1] == a.bookkeeper.immutablevalue(A.hello)
1693
def test_dict_and_none(self):
1699
a = self.RPythonAnnotator()
1700
s = a.build_types(f, [int])
1701
assert s.knowntype == dict
1703
def test_const_list_and_none(self):
1710
a = self.RPythonAnnotator()
1711
s = a.build_types(f, [])
1712
assert s.knowntype == bool
1713
assert not s.is_constant()
1715
def test_const_dict_and_none(self):
1722
a = self.RPythonAnnotator()
1723
s = a.build_types(f, [])
1724
assert s.knowntype == bool
1725
assert not s.is_constant()
1727
def test_issubtype_and_const(self):
1744
return issubclass(t, A)
1750
a = self.RPythonAnnotator()
1751
s = a.build_types(f, [])
1752
assert s.knowntype == bool
1753
assert not s.is_constant()
1754
a = self.RPythonAnnotator()
1756
x = annmodel.SomeInteger()
1758
s = a.build_types(g, [x])
1759
assert s.const == False
1760
a = self.RPythonAnnotator()
1761
x = annmodel.SomeInteger()
1763
s = a.build_types(g, [x])
1764
assert s.const == True
1766
def test_reading_also_generalizes(self):
1769
return d['not-a-char'], d
1770
a = self.RPythonAnnotator()
1771
s = a.build_types(f1, [int])
1772
assert dictkey(s.items[1]).__class__ == annmodel.SomeString
1775
return d.get('not-a-char', i+1), d
1776
a = self.RPythonAnnotator()
1777
s = a.build_types(f2, [int])
1778
assert dictkey(s.items[1]).__class__ == annmodel.SomeString
1781
return 'not-a-char' in d, d
1782
a = self.RPythonAnnotator()
1783
s = a.build_types(f3, [int])
1784
assert dictkey(s.items[1]).__class__ == annmodel.SomeString
1786
lst = ['a', 'b', 'c']
1787
return 'not-a-char' in lst, lst
1788
a = self.RPythonAnnotator()
1789
s = a.build_types(f4, [])
1790
assert listitem(s.items[1]).__class__ == annmodel.SomeString
1792
lst = ['a', 'b', 'c']
1793
return lst.index('not-a-char'), lst
1794
a = self.RPythonAnnotator()
1795
s = a.build_types(f5, [])
1796
assert listitem(s.items[1]).__class__ == annmodel.SomeString
1798
def test_true_str_is_not_none(self):
1809
a = self.RPythonAnnotator()
1810
s = a.build_types(g, [int])
1811
assert s.knowntype == str
1812
assert not s.can_be_None
1814
def test_true_func_is_not_none(self):
1829
a = self.RPythonAnnotator()
1830
s = a.build_types(g, [int])
1831
assert not s.can_be_None
1833
def test_emulated_pbc_call_simple(self):
1836
from pypy.annotation import annrpython
1837
a = annrpython.RPythonAnnotator()
1838
from pypy.annotation import model as annmodel
1840
s_f = a.bookkeeper.immutablevalue(f)
1841
a.bookkeeper.emulate_pbc_call('f', s_f, [annmodel.SomeInteger(), annmodel.SomeInteger()])
1844
assert a.binding(graphof(a, f).getreturnvar()).knowntype == int
1845
fdesc = a.bookkeeper.getdesc(f)
1847
someint = annmodel.SomeInteger()
1849
assert (fdesc.get_s_signatures((2,(),False,False))
1850
== [([someint,someint],someint)])
1852
def test_emulated_pbc_call_callback(self):
1855
from pypy.annotation import annrpython
1856
a = annrpython.RPythonAnnotator()
1857
from pypy.annotation import model as annmodel
1860
def callb(ann, graph):
1861
memo.append(annmodel.SomeInteger() == ann.binding(graph.getreturnvar()))
1863
s_f = a.bookkeeper.immutablevalue(f)
1864
s = a.bookkeeper.emulate_pbc_call('f', s_f, [annmodel.SomeInteger(), annmodel.SomeInteger()],
1866
assert s == annmodel.SomeImpossibleValue()
1869
assert a.binding(graphof(a, f).getreturnvar()).knowntype == int
1870
assert len(memo) >= 1
1874
def test_iterator_union(self):
1876
return d.iteritems()
1881
a = self.RPythonAnnotator()
1882
s = a.build_types(f, [])
1883
assert isinstance(s, annmodel.SomeIterator)
1884
assert s.variant == ('items',)
1886
def test_non_none_and_none_with_isinstance(self):
1892
if isinstance(x, A):
1898
a = self.RPythonAnnotator()
1899
s = a.build_types(f, [])
1900
assert isinstance(s, annmodel.SomeInstance)
1901
assert s.classdef == a.bookkeeper.getuniqueclassdef(B)
1903
def test_type_is_no_improvement(self):
1914
a = self.RPythonAnnotator()
1915
s = a.build_types(f, [D])
1916
assert s == annmodel.SomeImpossibleValue()
1918
def test_is_constant_instance(self):
1921
prebuilt_instance = A()
1923
if x is prebuilt_instance:
1926
a = self.RPythonAnnotator()
1927
s = a.build_types(f, [A])
1928
assert s.is_constant()
1929
assert s.const is prebuilt_instance
1931
def test_call_memoized_function(self):
1934
def getorbuild(key):
1937
result = eval("a+2")
1939
result = eval("a+6")
1941
getorbuild._annspecialcase_ = "specialize:memo"
1948
return getorbuild(fr)
1950
a = self.RPythonAnnotator()
1951
s = a.build_types(f1, [int])
1952
assert s.knowntype == int
1954
def test_call_memoized_function_with_bools(self):
1957
def getorbuild(key, flag1, flag2):
1960
result = eval("a+2")
1962
result = eval("a+6")
1968
getorbuild._annspecialcase_ = "specialize:memo"
1975
return getorbuild(fr, i % 2 == 0, i % 3 == 0)
1977
a = self.RPythonAnnotator()
1978
s = a.build_types(f1, [int])
1979
assert s.knowntype == int
1981
def test_stored_bound_method(self):
1987
def __init__(self, func):
1996
a = self.RPythonAnnotator()
1997
s = a.build_types(g, [])
1998
assert s.is_constant()
1999
assert s.const == 42
2001
def test_stored_bound_method_2(self):
2012
def __init__(self, func):
2024
a = self.RPythonAnnotator()
2025
s = a.build_types(g, [int])
2026
assert s.knowntype == int
2027
assert not s.is_constant()
2029
def test_getorbuild_as_attr(self):
2030
from pypy.tool.cache import Cache
2031
class SpaceCache(Cache):
2032
def _build(self, callable):
2034
class CacheX(Cache):
2035
def _build(self, key):
2037
class CacheY(Cache):
2038
def _build(self, key):
2041
def __init__(self, x):
2046
def __init__(self, y):
2052
fromcache = SpaceCache().getorbuild
2054
return (fromcache(CacheX).getorbuild(X1),
2055
fromcache(CacheY).getorbuild(Y2))
2057
a = self.RPythonAnnotator()
2058
s = a.build_types(f, [])
2059
assert s.items[0].knowntype == int
2060
assert s.items[1].knowntype == str
2062
def test_constant_bound_method(self):
2064
def __init__(self, value):
2071
a = self.RPythonAnnotator()
2072
s = a.build_types(f, [])
2073
assert s.knowntype == int
2075
def test_annotate__del__(self):
2083
a = self.RPythonAnnotator()
2085
s = a.build_types(f, [])
2086
assert s.knowntype == int
2087
graph = tgraphof(t, A.__del__.im_func)
2088
assert graph.startblock in a.annotated
2090
def test_annotate__del__baseclass(self):
2101
a = self.RPythonAnnotator()
2103
s = a.build_types(f, [])
2104
assert s.knowntype == int
2105
graph = tgraphof(t, A.__del__.im_func)
2106
assert graph.startblock in a.annotated
2108
def test_annotate_type(self):
2118
return witness(get(i))
2120
a = self.RPythonAnnotator()
2121
s = a.build_types(f, [int])
2122
assert s.__class__ == annmodel.SomeObject
2123
assert s.knowntype == type
2125
def test_annotate_iter_empty_container(self):
2131
for z in d.iterkeys(): n += z
2132
for s in d.itervalues(): n += s
2133
for t, u in d.items(): n += t * u
2134
for t, u in d.iteritems(): n += t * u
2137
a = self.RPythonAnnotator()
2138
s = a.build_types(f, [])
2139
assert s.is_constant()
2142
def test_mixin(self):
2143
class Mixin(object):
2152
class A(Base, Mixin):
2155
class B(Base, Mixin):
2170
a = self.RPythonAnnotator()
2171
s = a.build_types(f, [])
2172
assert isinstance(s.items[0], annmodel.SomeInteger)
2173
assert isinstance(s.items[1], annmodel.SomeChar)
2174
assert isinstance(s.items[2], annmodel.SomeChar)
2176
def test___class___attribute(self):
2177
class Base(object): pass
2189
result = x.__class__, y.__class__
2193
a = self.RPythonAnnotator()
2194
s = a.build_types(f, [int])
2195
assert isinstance(s.items[0], annmodel.SomePBC)
2196
assert len(s.items[0].descriptions) == 4
2197
assert isinstance(s.items[1], annmodel.SomePBC)
2198
assert len(s.items[1].descriptions) == 1
2200
def test_slots(self):
2201
# check that the annotator ignores slots instead of being
2202
# confused by them showing up as 'member' objects in the class
2204
__slots__ = ('a', 'b')
2210
a = self.RPythonAnnotator()
2211
s = a.build_types(f, [int])
2212
assert s.knowntype == int
2214
def test_unboxed_value(self):
2217
class C(A, objectmodel.UnboxedValue):
2218
__slots__ = unboxedattrname = 'smallint'
2220
return C(n).smallint
2222
a = self.RPythonAnnotator()
2223
s = a.build_types(f, [int])
2224
assert s.knowntype == int
2227
def test_annotate_bool(self):
2230
a = self.RPythonAnnotator()
2231
s = a.build_types(f, [bool])
2232
assert s.knowntype == int
2237
a = self.RPythonAnnotator()
2238
s = a.build_types(f, [bool])
2239
assert s.knowntype == int
2243
a = self.RPythonAnnotator()
2244
s = a.build_types(f, [bool])
2245
assert s.knowntype == int
2249
a = self.RPythonAnnotator()
2250
s = a.build_types(f, [bool])
2251
assert s.knowntype == int
2255
a = self.RPythonAnnotator()
2256
s = a.build_types(f, [bool])
2257
assert s.knowntype == int
2262
a = self.RPythonAnnotator()
2263
s = a.build_types(f, [bool, int])
2264
assert s.knowntype == int
2266
a = self.RPythonAnnotator()
2267
s = a.build_types(f, [int, bool])
2268
assert s.knowntype == int
2272
def test_annotate_rarith(self):
2273
inttypes = [int, r_uint, r_longlong, r_ulonglong]
2274
for inttype in inttypes:
2278
a = self.RPythonAnnotator()
2279
s = a.build_types(f, [])
2280
assert isinstance(s, annmodel.SomeInteger)
2281
assert s.knowntype == inttype
2282
assert s.unsigned == (inttype(-1) > 0)
2284
for inttype in inttypes:
2287
a = self.RPythonAnnotator()
2288
s = a.build_types(f, [])
2289
assert isinstance(s, annmodel.SomeInteger)
2290
assert s.knowntype == inttype
2291
assert s.unsigned == (inttype(-1) > 0)
2293
for inttype in inttypes:
2296
a = self.RPythonAnnotator()
2297
s = a.build_types(f, [inttype])
2298
assert isinstance(s, annmodel.SomeInteger)
2299
assert s.knowntype == inttype
2300
assert s.unsigned == (inttype(-1) > 0)
2302
def test_annotate_rshift(self):
2305
a = self.RPythonAnnotator()
2306
s = a.build_types(f, [annmodel.SomeInteger(nonneg=True)])
2307
assert isinstance(s, annmodel.SomeInteger)
2310
def test_prebuilt_mutables(self):
2317
a1.d = {} # this tests confusion between the two '{}', which
2318
a2.d = {} # compare equal
2334
return len(d) + len(l)
2345
return readout(a1.d, a1.l) + readout(a2.d, a2.l)
2347
a = self.RPythonAnnotator()
2348
a.build_types(f, [])
2349
v1, v2 = graphof(a, readout).getargs()
2350
assert not a.bindings[v1].is_constant()
2351
assert not a.bindings[v2].is_constant()
2353
def test_helper_method_annotator(self):
2361
a = self.RPythonAnnotator()
2362
a.build_types(fun, [])
2363
a.annotate_helper_method(A, "helper", [])
2364
assert a.bookkeeper.getdesc(A.helper).getuniquegraph()
2366
def test_chr_out_of_bounds(self):
2374
return g(ord(v), max)
2376
a = self.RPythonAnnotator()
2377
s = a.build_types(fun, [int])
2378
assert isinstance(s, annmodel.SomeChar)
2380
def test_range_nonneg(self):
2386
a = self.RPythonAnnotator()
2387
s = a.build_types(fun, [int, int])
2388
assert isinstance(s, annmodel.SomeInteger)
2391
def test_reverse_range_nonneg(self):
2393
for i in range(n-1, -1, -1):
2397
a = self.RPythonAnnotator()
2398
s = a.build_types(fun, [int, int])
2399
assert isinstance(s, annmodel.SomeInteger)
2405
s_nonneg = annmodel.SomeInteger(nonneg=True)
2406
fun._annenforceargs_ = policy.Sig(int, s_nonneg)
2408
a = self.RPythonAnnotator()
2409
s = a.build_types(fun, [s_nonneg, s_nonneg])
2410
assert isinstance(s, annmodel.SomeInteger)
2412
py.test.raises(Exception, a.build_types, fun, [int, int])
2414
def test_sig_simpler(self):
2417
s_nonneg = annmodel.SomeInteger(nonneg=True)
2418
fun._annenforceargs_ = (int, s_nonneg)
2420
a = self.RPythonAnnotator()
2421
s = a.build_types(fun, [s_nonneg, s_nonneg])
2422
assert isinstance(s, annmodel.SomeInteger)
2424
py.test.raises(Exception, a.build_types, fun, [int, int])
2426
def test_sig_lambda(self):
2429
s_nonneg = annmodel.SomeInteger(nonneg=True)
2430
fun._annenforceargs_ = policy.Sig(lambda s1,s2: s1, lambda s1,s2: s1)
2431
# means: the 2nd argument's annotation becomes the 1st argument's
2434
a = self.RPythonAnnotator()
2435
s = a.build_types(fun, [int, s_nonneg])
2436
assert isinstance(s, annmodel.SomeInteger)
2438
py.test.raises(Exception, a.build_types, fun, [s_nonneg, int])
2440
def test_slots_check(self):
2451
for attrname, works in [('x', True),
2458
setattr(o, attrname, 12)
2460
a = self.RPythonAnnotator()
2462
a.build_types(fun, [int])
2464
from pypy.annotation.classdef import NoSuchAttrError
2465
py.test.raises(NoSuchAttrError, a.build_types, fun, [int])
2467
def test_slots_enforce_attrs(self):
2468
class Superbase(object):
2470
class Base(Superbase):
2477
if s is None: # known not to be None in this test
2485
a = self.RPythonAnnotator()
2486
s = a.build_types(fun, [str])
2487
assert s == annmodel.s_ImpossibleValue # but not blocked blocks
2489
def test_enforced_attrs_check(self):
2500
for attrname, works in [('x', True),
2507
setattr(o, attrname, 12)
2509
a = self.RPythonAnnotator()
2511
a.build_types(fun, [int])
2513
from pypy.annotation.classdef import NoSuchAttrError
2514
py.test.raises(NoSuchAttrError, a.build_types, fun, [int])
2516
def test_attrs_enforce_attrs(self):
2517
class Superbase(object):
2519
class Base(Superbase):
2526
if s is None: # known not to be None in this test
2534
a = self.RPythonAnnotator()
2535
s = a.build_types(fun, [str])
2536
assert s == annmodel.s_ImpossibleValue # but not blocked blocks
2539
def test_pbc_enforce_attrs(self):
2559
a = self.RPythonAnnotator()
2560
a.build_types(f, [bool])
2562
def test_enforce_settled(self):
2567
raise NotImplementedError
2585
a = self.RPythonAnnotator()
2586
s = a.build_types(fun, [bool])
2587
assert s.knowntype == int
2597
a = self.RPythonAnnotator()
2598
py.test.raises(Exception, a.build_types, fun, [bool])
2600
def test_float_cmp(self):
2609
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
2610
s = a.build_types(fun, [float, float])
2611
assert [s_item.knowntype for s_item in s.items] == [bool] * 6
2613
def test_empty_range(self):
2616
for i in range(len(lst)):
2622
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
2623
s = a.build_types(fun, [])
2626
def test_some_generic_function_call(self):
2646
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
2647
s = a.build_types(g, [annmodel.SomeGenericCallable(
2648
args=[annmodel.SomeFloat()], result=annmodel.SomeInteger()),
2649
annmodel.SomeFloat()])
2650
assert isinstance(s, annmodel.SomeInteger)
2651
assert not hasattr(s, 'const')
2653
def test_compare_int_bool(self):
2656
a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
2657
s = a.build_types(fun, [bool])
2658
assert isinstance(s, annmodel.SomeBool)
2660
def test_long_as_intermediate_value(self):
2661
from sys import maxint
2662
from pypy.rlib.rarithmetic import intmask
2668
return intmask(v * 10)
2669
P = policy.AnnotatorPolicy()
2670
P.allow_someobjects = False
2671
a = self.RPythonAnnotator(policy=P)
2672
s = a.build_types(fun, [bool])
2673
assert isinstance(s, annmodel.SomeInteger)
2675
def test_unionof_some_external_builtin(self):
2676
from pypy.rpython.ootypesystem.bltregistry import BasicExternal
2678
class A(BasicExternal):
2693
P = policy.AnnotatorPolicy()
2694
P.allow_someobjects = False
2695
a = self.RPythonAnnotator(policy=P)
2696
s = a.build_types(f, [bool])
2697
assert isinstance(s, annmodel.SomeExternalBuiltin)
2699
def test_instance_with_flags(self):
2700
from pypy.rlib.objectmodel import hint
2703
_virtualizable_ = True
2713
x = hint(x, access_directly=True)
2720
a = self.RPythonAnnotator()
2721
s = a.build_types(f, [a.bookkeeper.immutablevalue(0)])
2722
assert isinstance(s.items[0], annmodel.SomeInstance)
2723
assert s.items[0].flags == {'access_directly': True}
2724
assert isinstance(s.items[1], annmodel.SomePBC)
2725
assert len(s.items[1].descriptions) == 1
2726
assert s.items[1].descriptions.keys()[0].flags == {'access_directly':
2728
assert isinstance(s.items[2], annmodel.SomeInstance)
2729
assert s.items[2].flags == {'access_directly': True}
2731
a = self.RPythonAnnotator()
2732
s = a.build_types(f, [int])
2733
assert isinstance(s.items[0], annmodel.SomeInstance)
2734
assert s.items[0].flags == {}
2735
assert isinstance(s.items[1], annmodel.SomePBC)
2736
assert isinstance(s.items[2], annmodel.SomeInstance)
2737
assert s.items[2].flags == {}
2751
constant_unsigned_five = r_uint(5)