Debian Codegraph @

rpython/rtyper/test/test_llinterp.py

raw symbols SCIP
1 from __future__ import with_statement
2 import py
3 import sys
4 from rpython.rtyper.lltypesystem.lltype import typeOf, Void, malloc, free
5 from rpython.rtyper.llinterp import LLInterpreter, LLException, log
6 from rpython.rtyper.rmodel import inputconst
7 from rpython.rtyper.annlowlevel import hlstr, llhelper
8 from rpython.rtyper.exceptiondata import UnknownException
9 from rpython.translator.translator import TranslationContext, graphof
10 from rpython.rtyper.lltypesystem import lltype
11 from rpython.annotator import model as annmodel
12 from rpython.rtyper.llannotation import lltype_to_annotation
13 from rpython.rlib.rarithmetic import r_uint, ovfcheck
14 from rpython.tool import leakfinder
15 from rpython.conftest import option
16 from rpython.rtyper.rtyper import llinterp_backend
17
18 # switch on logging of interp to show more info on failing tests
19 def setup_module(mod):
20 log.output_disabled = False
21 def teardown_module(mod):
22 log.output_disabled = True
23
24
25 def gengraph(func, argtypes=[], viewbefore='auto', policy=None,
26 backendopt=False, config=None, **extraconfigopts):
27 t = TranslationContext(config=config)
28 t.config.set(**extraconfigopts)
29 a = t.buildannotator(policy=policy)
30 a.build_types(func, argtypes, main_entry_point=True)
31 a.validate()
32 if viewbefore == 'auto':
33 viewbefore = getattr(option, 'view', False)
34 if viewbefore:
35 a.simplify()
36 t.view()
37 global typer # we need it for find_exception
38 typer = t.buildrtyper()
39 typer.backend = llinterp_backend
40 typer.specialize()
41 #t.view()
42 t.checkgraphs()
43 if backendopt:
44 from rpython.translator.backendopt.all import backend_optimizations
45 backend_optimizations(t)
46 t.checkgraphs()
47 if viewbefore:
48 t.view()
49 desc = t.annotator.bookkeeper.getdesc(func)
50 graph = desc.specialize(argtypes)
51 return t, typer, graph
52
53 _lastinterpreted = []
54 _tcache = {}
55 def clear_tcache():
56 del _lastinterpreted[:]
57 _tcache.clear()
58
59 def get_interpreter(func, values, view='auto', viewbefore='auto', policy=None,
60 backendopt=False, config=None, **extraconfigopts):
61 extra_key = [(key, value) for key, value in extraconfigopts.iteritems()]
62 extra_key.sort()
63 extra_key = tuple(extra_key)
64 key = ((func,) + tuple([typeOf(x) for x in values]) +
65 (backendopt, extra_key))
66 try:
67 (t, interp, graph) = _tcache[key]
68 except KeyError:
69 def annotation(x):
70 T = typeOf(x)
71 return lltype_to_annotation(T)
72
73 if policy is None:
74 from rpython.annotator.policy import AnnotatorPolicy
75 policy = AnnotatorPolicy()
76
77 t, typer, graph = gengraph(func, [annotation(x) for x in values],
78 viewbefore, policy, backendopt=backendopt,
79 config=config, **extraconfigopts)
80 interp = LLInterpreter(typer)
81 _tcache[key] = (t, interp, graph)
82 # keep the cache small
83 _lastinterpreted.append(key)
84 if len(_lastinterpreted) >= 4:
85 del _tcache[_lastinterpreted.pop(0)]
86 if view == 'auto':
87 view = getattr(option, 'view', False)
88 if view:
89 t.view()
90 return interp, graph
91
92 def interpret(func, values, view='auto', viewbefore='auto', policy=None,
93 backendopt=False, config=None, malloc_check=True, **kwargs):
94 interp, graph = get_interpreter(func, values, view, viewbefore, policy,
95 backendopt=backendopt, config=config,
96 **kwargs)
97 if not malloc_check:
98 result = interp.eval_graph(graph, values)
99 else:
100 prev = leakfinder.start_tracking_allocations()
101 try:
102 result = interp.eval_graph(graph, values)
103 finally:
104 leaks = leakfinder.stop_tracking_allocations(False, prev)
105 if leaks:
106 raise leakfinder.MallocMismatch(leaks)
107 return result
108
109 def interpret_raises(exc, func, values, view='auto', viewbefore='auto',
110 policy=None,
111 backendopt=False):
112 interp, graph = get_interpreter(func, values, view, viewbefore, policy,
113 backendopt=backendopt)
114 info = py.test.raises(LLException, "interp.eval_graph(graph, values)")
115 try:
116 got = interp.find_exception(info.value)
117 except ValueError as message:
118 got = 'None %r' % message
119 assert got is exc, "wrong exception type, expected %r got %r" % (exc, got)
120
121 #__________________________________________________________________
122 # tests
123
124 def test_int_ops():
125 res = interpret(number_ops, [3])
126 assert res == 4
127
128 def test_invert():
129 def f(x):
130 return ~x
131 res = interpret(f, [3])
132 assert res == ~3
133 assert interpret(f, [r_uint(3)]) == ~r_uint(3)
134
135 def test_float_ops():
136 res = interpret(number_ops, [3.5])
137 assert res == 4.5
138
139 def test_ifs():
140 res = interpret(simple_ifs, [0])
141 assert res == 43
142 res = interpret(simple_ifs, [1])
143 assert res == 42
144
145 def test_raise():
146 res = interpret(raise_exception, [41])
147 assert res == 41
148 interpret_raises(IndexError, raise_exception, [42])
149 interpret_raises(ValueError, raise_exception, [43])
150
151 def test_call_raise():
152 res = interpret(call_raise, [41])
153 assert res == 41
154 interpret_raises(IndexError, call_raise, [42])
155 interpret_raises(ValueError, call_raise, [43])
156
157 def test_call_raise_twice():
158 res = interpret(call_raise_twice, [6, 7])
159 assert res == 13
160 interpret_raises(IndexError, call_raise_twice, [6, 42])
161 res = interpret(call_raise_twice, [6, 43])
162 assert res == 1006
163 interpret_raises(IndexError, call_raise_twice, [42, 7])
164 interpret_raises(ValueError, call_raise_twice, [43, 7])
165
166 def test_call_raise_intercept():
167 res = interpret(call_raise_intercept, [41])
168 assert res == 41
169 res = interpret(call_raise_intercept, [42])
170 assert res == 42
171 interpret_raises(TypeError, call_raise_intercept, [43])
172
173 def test_while_simple():
174 res = interpret(while_simple, [3])
175 assert res == 6
176
177 def test_number_comparisons():
178 for t in float, int:
179 val1 = t(3)
180 val2 = t(4)
181 gcres = interpret(comparisons, [val1, val2])
182 res = [getattr(gcres, x) for x in typeOf(gcres).TO._names]
183 assert res == [True, True, False, True, False, False]
184
185 def test_some_builtin():
186 def f(i, j):
187 x = range(i)
188 return x[j-1]
189 res = interpret(f, [10, 7])
190 assert res == 6
191
192 def test_recursion_does_not_overwrite_my_variables():
193 def f(i):
194 j = i + 1
195 if i > 0:
196 f(i-1)
197 return j
198
199 res = interpret(f, [4])
200 assert res == 5
201
202 #
203 #__________________________________________________________________
204 #
205 # Test lists
206 def test_list_creation():
207 def f():
208 return [1,2,3]
209 res = interpret(f,[])
210 assert len(res.ll_items()) == len([1,2,3])
211 for i in range(3):
212 assert res.ll_items()[i] == i+1
213
214 def test_list_itemops():
215 def f(i):
216 l = [1, i]
217 l[0] = 0
218 del l[1]
219 return l[-1]
220 res = interpret(f, [3])
221 assert res == 0
222
223 def test_list_append():
224 def f(i):
225 l = [1]
226 l.append(i)
227 return l[0] + l[1]
228 res = interpret(f, [3])
229 assert res == 4
230
231 def test_list_extend():
232 def f(i):
233 l = [1]
234 l.extend([i])
235 return l[0] + l[1]
236 res = interpret(f, [3])
237 assert res == 4
238
239 def test_list_multiply():
240 def f(i):
241 l = [i]
242 l = l * i # uses alloc_and_set for len(l) == 1
243 return len(l)
244 res = interpret(f, [3])
245 assert res == 3
246
247 def test_list_reverse():
248 def f():
249 l = [1,2,3]
250 l.reverse()
251 return l
252 res = interpret(f,[])
253 assert len(res.ll_items()) == len([3,2,1])
254 print res
255 for i in range(3):
256 assert res.ll_items()[i] == 3-i
257
258 def test_list_pop():
259 def f():
260 l = [1,2,3]
261 l1 = l.pop(2)
262 l2 = l.pop(1)
263 l3 = l.pop(-1)
264 return [l1,l2,l3]
265 res = interpret(f,[])
266 assert len(res.ll_items()) == 3
267
268 def test_ovf():
269 def f(x):
270 try:
271 return ovfcheck(sys.maxint + x)
272 except OverflowError:
273 return 1
274 res = interpret(f, [1])
275 assert res == 1
276 res = interpret(f, [0])
277 assert res == sys.maxint
278 def g(x):
279 try:
280 return ovfcheck(abs(x))
281 except OverflowError:
282 return 42
283 res = interpret(g, [-sys.maxint - 1])
284 assert res == 42
285 res = interpret(g, [-15])
286 assert res == 15
287
288 def test_floordiv_ovf_zer():
289 def f(x):
290 try:
291 return ovfcheck((-sys.maxint - 1) // x)
292 except OverflowError:
293 return 1
294 except ZeroDivisionError:
295 return 0
296 res = interpret(f, [0])
297 assert res == 0
298 res = interpret(f, [-1])
299 assert res == 1
300 res = interpret(f, [30])
301 assert res == (-sys.maxint - 1) // 30
302
303 def test_mod_ovf_zer():
304 def f(x):
305 try:
306 return ovfcheck((-sys.maxint - 1) % x)
307 except OverflowError:
308 return 43
309 except ZeroDivisionError:
310 return 42
311 res = interpret(f, [0])
312 assert res == 42
313 # the following test doesn't work any more before translation,
314 # but "too bad" is the best answer I suppose
315 res = interpret(f, [-1])
316 if 0:
317 assert res == 43
318 res = interpret(f, [30])
319 assert res == (-sys.maxint - 1) % 30
320
321
322 def test_funny_links():
323 from rpython.flowspace.model import Block, FunctionGraph, \
324 Variable, Constant, Link
325 from rpython.flowspace.operation import op
326 for i in range(2):
327 v_i = Variable("i")
328 block = Block([v_i])
329 g = FunctionGraph("is_one", block)
330 op1 = op.eq(v_i, Constant(1))
331 block.operations.append(op1)
332 block.exitswitch = op1.result
333 tlink = Link([Constant(1)], g.returnblock, True)
334 flink = Link([Constant(0)], g.returnblock, False)
335 links = [tlink, flink]
336 if i:
337 links.reverse()
338 block.closeblock(*links)
339 t = TranslationContext()
340 a = t.buildannotator()
341 a.build_graph_types(g, [annmodel.SomeInteger()])
342 rtyper = t.buildrtyper()
343 rtyper.specialize()
344 interp = LLInterpreter(rtyper)
345 assert interp.eval_graph(g, [1]) == 1
346 assert interp.eval_graph(g, [0]) == 0
347
348 #__________________________________________________________________
349 #
350 # Test objects and instances
351
352 class ExampleClass:
353 def __init__(self, x):
354 self.x = x + 1
355
356 def test_basic_instantiation():
357 def f(x):
358 return ExampleClass(x).x
359 res = interpret(f, [4])
360 assert res == 5
361
362 def test_id():
363 from rpython.rlib.objectmodel import compute_unique_id
364 def getids(i, j):
365 e1 = ExampleClass(1)
366 e2 = ExampleClass(2)
367 a = [e1, e2][i]
368 b = [e1, e2][j]
369 return (compute_unique_id(a) == compute_unique_id(b)) == (a is b)
370 for i in [0, 1]:
371 for j in [0, 1]:
372 result = interpret(getids, [i, j])
373 assert result
374
375 def test_invalid_stack_access():
376 py.test.skip("stack-flavored mallocs no longer supported")
377 class A(object):
378 pass
379 globala = A()
380 globala.next = None
381 globala.i = 1
382 def g(a):
383 globala.next = a
384 def f():
385 a = A()
386 a.i = 2
387 g(a)
388 def h():
389 f()
390 return globala.next.i
391 interp, graph = get_interpreter(h, [])
392 fgraph = graph.startblock.operations[0].args[0].value._obj.graph
393 assert fgraph.startblock.operations[0].opname == 'malloc'
394 fgraph.startblock.operations[0].args[1] = inputconst(Void, {'flavor': "stack"})
395 py.test.raises(RuntimeError, "interp.eval_graph(graph, [])")
396
397 #__________________________________________________________________
398 # example functions for testing the LLInterpreter
399 _snap = globals().copy()
400
401 def number_ops(i):
402 j = i + 2
403 k = j * 2
404 m = k / 2
405 return m - 1
406
407 def comparisons(x, y):
408 return (x < y,
409 x <= y,
410 x == y,
411 x != y,
412 #x is None,
413 #x is not None,
414 x >= y,
415 x > y,
416 )
417
418 def simple_ifs(i):
419 if i:
420 return 42
421 else:
422 return 43
423
424 def while_simple(i):
425 sum = 0
426 while i > 0:
427 sum += i
428 i -= 1
429 return sum
430
431 def raise_exception(i):
432 if i == 42:
433 raise IndexError
434 elif i == 43:
435 raise ValueError
436 return i
437
438 def call_raise(i):
439 return raise_exception(i)
440
441 def call_raise_twice(i, j):
442 x = raise_exception(i)
443 try:
444 y = raise_exception(j)
445 except ValueError:
446 y = 1000
447 return x + y
448
449 def call_raise_intercept(i):
450 try:
451 return raise_exception(i)
452 except IndexError:
453 return i
454 except ValueError:
455 raise TypeError
456
457 def test_half_exceptiontransformed_graphs():
458 from rpython.translator import exceptiontransform
459 def f1(x):
460 if x < 0:
461 raise ValueError
462 return 754
463 def g1(x):
464 try:
465 return f1(x)
466 except ValueError:
467 return 5
468 def f2(x):
469 if x < 0:
470 raise ValueError
471 return 21
472 def g2(x):
473 try:
474 return f2(x)
475 except ValueError:
476 return 6
477 f3 = lltype.functionptr(lltype.FuncType([lltype.Signed], lltype.Signed),
478 'f3', _callable = f1)
479 def g3(x):
480 try:
481 return f3(x)
482 except ValueError:
483 return 7
484 def f(flag, x):
485 if flag == 1:
486 return g1(x)
487 elif flag == 2:
488 return g2(x)
489 else:
490 return g3(x)
491 t = TranslationContext()
492 t.buildannotator().build_types(f, [int, int])
493 t.buildrtyper().specialize()
494 etrafo = exceptiontransform.ExceptionTransformer(t)
495 etrafo.create_exception_handling(graphof(t, f1))
496 etrafo.create_exception_handling(graphof(t, g2))
497 etrafo.create_exception_handling(graphof(t, g3))
498 graph = graphof(t, f)
499 interp = LLInterpreter(t.rtyper)
500 res = interp.eval_graph(graph, [1, -64])
501 assert res == 5
502 res = interp.eval_graph(graph, [2, -897])
503 assert res == 6
504 res = interp.eval_graph(graph, [3, -9831])
505 assert res == 7
506
507 def test_exceptiontransformed_add_ovf():
508 from rpython.translator import exceptiontransform
509 def f(x, y):
510 try:
511 return ovfcheck(x + y)
512 except OverflowError:
513 return -42
514 t = TranslationContext()
515 t.buildannotator().build_types(f, [int, int])
516 t.buildrtyper().specialize()
517 etrafo = exceptiontransform.ExceptionTransformer(t)
518 graph = graphof(t, f)
519 etrafo.create_exception_handling(graph)
520 interp = LLInterpreter(t.rtyper)
521 res = interp.eval_graph(graph, [1, -64])
522 assert res == -63
523 res = interp.eval_graph(graph, [1, sys.maxint])
524 assert res == -42
525
526 def test_malloc_checker():
527 T = lltype.Struct('x')
528 def f(x):
529 t = malloc(T, flavor='raw')
530 if x:
531 free(t, flavor='raw')
532 interpret(f, [1])
533 py.test.raises(leakfinder.MallocMismatch, "interpret(f, [0])")
534
535 def f():
536 t1 = malloc(T, flavor='raw')
537 t2 = malloc(T, flavor='raw')
538 free(t1, flavor='raw')
539 free(t2, flavor='raw')
540
541 interpret(f, [])
542
543 def test_context_manager():
544 state = []
545 class C:
546 def __enter__(self):
547 state.append('acquire')
548 return self
549 def __exit__(self, *args):
550 if args[1] is not None:
551 state.append('raised')
552 state.append('release')
553 def f():
554 try:
555 with C() as c:
556 state.append('use')
557 raise ValueError
558 except ValueError:
559 pass
560 return ', '.join(state)
561 res = interpret(f, [])
562 assert hlstr(res) == 'acquire, use, raised, release'
563
564
565 def test_scoped_allocator():
566 from rpython.rtyper.lltypesystem.lltype import scoped_alloc, Array, Signed
567 T = Array(Signed)
568
569 def f():
570 x = 0
571 with scoped_alloc(T, 1) as array:
572 array[0] = -42
573 x = array[0]
574 assert x == -42
575
576 res = interpret(f, [])
577
578 def test_raising_llimpl():
579 from rpython.rtyper.extfunc import register_external
580
581 def external():
582 pass
583
584 def raising():
585 raise OSError(15, "abcd")
586
587 ext = register_external(external, [], llimpl=raising, llfakeimpl=raising)
588
589 def f():
590 # this is a useful llfakeimpl that raises an exception
591 try:
592 external()
593 return True
594 except OSError:
595 return False
596
597 res = interpret(f, [])
598 assert not res
599
600 def test_userdefined_exception():
601 class FooError(Exception):
602 pass
603 def g():
604 raise FooError
605 g_func = llhelper(lltype.Ptr(lltype.FuncType([], lltype.Void)), g)
606 def f():
607 g_func()
608
609 e = py.test.raises(UnknownException, interpret, f, [])
610 assert e.value.args[0] is FooError