Debian Codegraph @

rpython/translator/test/test_exceptiontransform.py

raw symbols SCIP
1 import py
2 from rpython.translator.translator import TranslationContext, graphof
3 from rpython.translator.simplify import join_blocks
4 from rpython.translator import exceptiontransform
5 from rpython.flowspace.model import summary
6 from rpython.rtyper.llinterp import LLException
7 from rpython.rtyper.lltypesystem import lltype
8 from rpython.rtyper.annlowlevel import llhelper
9 from rpython.rtyper.test.test_llinterp import get_interpreter
10 from rpython.rlib.objectmodel import llhelper_error_value, dont_inline
11 from rpython.translator.backendopt.all import backend_optimizations
12 from rpython.conftest import option
13 import sys
14
15 def check_debug_build():
16 # the 'not option.view' is because debug builds rarely
17 # have pygame, so if you want to see the graphs pass --view and
18 # don't be surprised when the test then passes when it shouldn't.
19 if not hasattr(sys, 'gettotalrefcount') and not option.view:
20 py.test.skip("test needs a debug build of Python")
21
22 _already_transformed = {}
23
24 def interpret(func, values):
25 interp, graph = get_interpreter(func, values)
26 t = interp.typer.annotator.translator
27 if t not in _already_transformed:
28 etrafo = exceptiontransform.ExceptionTransformer(t)
29 etrafo.transform_completely()
30 _already_transformed[t] = True
31 return interp.eval_graph(graph, values)
32
33 class TestExceptionTransform:
34 def compile(self, fn, inputargs, **kwargs):
35 from rpython.translator.c.test.test_genc import compile
36 return compile(fn, inputargs, **kwargs)
37
38 def transform_func(self, fn, inputtypes, backendopt=False):
39 t = TranslationContext()
40 t.buildannotator().build_types(fn, inputtypes)
41 t.buildrtyper().specialize()
42 if option.view:
43 t.view()
44 if backendopt:
45 backend_optimizations(t)
46 g = graphof(t, fn)
47 etrafo = exceptiontransform.ExceptionTransformer(t)
48 etrafo.create_exception_handling(g)
49 join_blocks(g)
50 if option.view:
51 t.view()
52 return t, g
53
54 def test_simple(self):
55 def one():
56 return 1
57
58 def foo():
59 one()
60 return one()
61
62 t, g = self.transform_func(foo, [])
63 assert len(list(g.iterblocks())) == 2 # graph does not change
64 result = interpret(foo, [])
65 assert result == 1
66 f = self.compile(foo, [])
67 assert f() == 1
68
69 def test_passthrough(self):
70 def one(x):
71 if x:
72 raise ValueError()
73
74 def foo():
75 one(0)
76 one(1)
77 t, g = self.transform_func(foo, [])
78 f = self.compile(foo, [])
79 f(expected_exception_name='ValueError')
80
81 def test_catches(self):
82 def one(x):
83 if x == 1:
84 raise ValueError()
85 elif x == 2:
86 raise TypeError()
87 return x - 5
88
89 def foo(x):
90 x = one(x)
91 try:
92 x = one(x)
93 except ValueError:
94 return 1 + x
95 except TypeError:
96 return 2 + x
97 except:
98 return 3 + x
99 return 4 + x
100 t, g = self.transform_func(foo, [int])
101 assert len(list(g.iterblocks())) == 10
102 f = self.compile(foo, [int])
103 result = interpret(foo, [6])
104 assert result == 2
105 result = f(6)
106 assert result == 2
107 result = interpret(foo, [7])
108 assert result == 4
109 result = f(7)
110 assert result == 4
111 result = interpret(foo, [8])
112 assert result == 2
113 result = f(8)
114 assert result == 2
115
116 def test_type_checking_catching_does_no_calls(self):
117 def one(x):
118 if x == 1:
119 raise ValueError()
120 elif x == 2:
121 raise TypeError()
122 return x - 5
123
124 def foo(x):
125 x = one(x)
126 try:
127 x = one(x)
128 except ValueError:
129 return 1 + x
130 except TypeError:
131 return 2 + x
132 except:
133 return 3 + x
134 return 4 + x
135 t, g = self.transform_func(foo, [int])
136 s = summary(g)
137 assert s['direct_call'] == 2 # two calls to one, 0 to ll_issubclass
138 assert s['int_between'] == 2 # subclass checks done directly
139
140 def test_bare_except(self):
141 def one(x):
142 if x == 1:
143 raise ValueError()
144 elif x == 2:
145 raise TypeError()
146 return x - 5
147
148 def foo(x):
149 x = one(x)
150 try:
151 x = one(x)
152 except:
153 return 1 + x
154 return 4 + x
155 t, g = self.transform_func(foo, [int])
156 assert len(list(g.iterblocks())) == 6
157 f = self.compile(foo, [int])
158 result = interpret(foo, [6])
159 assert result == 2
160 result = f(6)
161 assert result == 2
162 result = interpret(foo, [7])
163 assert result == 3
164 result = f(7)
165 assert result == 3
166 result = interpret(foo, [8])
167 assert result == 2
168 result = f(8)
169 assert result == 2
170
171 def test_raises(self):
172 def foo(x):
173 if x:
174 raise ValueError()
175 t, g = self.transform_func(foo, [int])
176 assert len(list(g.iterblocks())) == 3
177 f = self.compile(foo, [int])
178 f(0)
179 f(1, expected_exception_name='ValueError')
180
181
182 def test_no_multiple_transform(self):
183 def f(x):
184 return x + 1
185 t = TranslationContext()
186 t.buildannotator().build_types(f, [int])
187 t.buildrtyper().specialize()
188 g = graphof(t, f)
189 etrafo = exceptiontransform.ExceptionTransformer(t)
190 etrafo.create_exception_handling(g)
191 etrafo2 = exceptiontransform.ExceptionTransformer(t)
192 py.test.raises(AssertionError, etrafo2.create_exception_handling, g)
193
194 def test_preserve_can_raise(self):
195 def f(x):
196 raise ValueError
197 t = TranslationContext()
198 t.buildannotator().build_types(f, [int])
199 t.buildrtyper().specialize()
200 g = graphof(t, f)
201 etrafo = exceptiontransform.ExceptionTransformer(t)
202 etrafo.create_exception_handling(g)
203 assert etrafo.raise_analyzer.analyze_direct_call(g)
204
205 def test_reraise_is_not_raise(self):
206 def one(x):
207 if x == 1:
208 raise ValueError()
209 elif x == 2:
210 raise TypeError()
211 return x - 5
212 def foo(x):
213 try:
214 return one(x)
215 except ValueError:
216 return -42
217 t, g = self.transform_func(foo, [int])
218 for block in g.iterblocks():
219 for op in block.operations:
220 # the operation 'debug_record_traceback' should only show up
221 # in a normal raise, not in a reraise
222 assert op.opname != 'debug_record_traceback'
223 f = self.compile(foo, [int])
224 result = interpret(foo, [7])
225 assert result == 2
226 result = f(7)
227 assert result == 2
228 result = interpret(foo, [1])
229 assert result == -42
230 result = f(1)
231 assert result == -42
232
233 def test_needs_keepalive(self):
234 check_debug_build()
235 from rpython.rtyper.lltypesystem import lltype
236 X = lltype.GcStruct("X",
237 ('y', lltype.Struct("Y", ('z', lltype.Signed))))
238 def can_raise(n):
239 if n:
240 raise Exception
241 else:
242 return 1
243 def foo(n):
244 x = lltype.malloc(X)
245 y = x.y
246 y.z = 42
247 r = can_raise(n)
248 return r + y.z
249 f = self.compile(foo, [int])
250 res = f(0)
251 assert res == 43
252
253 def test_inserting_zeroing_op(self):
254 from rpython.rtyper.lltypesystem import lltype
255 S = lltype.GcStruct("S", ('x', lltype.Signed))
256 def f(x):
257 s = lltype.malloc(S)
258 s.x = 0
259 return s.x
260 t = TranslationContext()
261 t.buildannotator().build_types(f, [int])
262 t.buildrtyper().specialize()
263 g = graphof(t, f)
264 etrafo = exceptiontransform.ExceptionTransformer(t)
265 etrafo.create_exception_handling(g)
266 ops = dict.fromkeys([o.opname for b, o in g.iterblockops()])
267 assert 'zero_gc_pointers_inside' in ops
268
269 def test_llexternal(self):
270 from rpython.rtyper.lltypesystem.rffi import llexternal
271 from rpython.rtyper.lltypesystem import lltype
272 z = llexternal('z', [lltype.Signed], lltype.Signed)
273 def f(x):
274 y = -1
275 if x > 0:
276 y = z(x)
277 return y + x
278
279 t,g = self.transform_func(f, [int], True)
280 # llexternals normally should not raise, the graph should have no exception
281 # checking
282 assert summary(g) == {'int_gt': 1, 'int_add': 1, 'direct_call': 1}
283
284 def test_get_exception_addr(self):
285 from rpython.rtyper.lltypesystem import lltype, llmemory
286 from rpython.rtyper.lltypesystem.lloperation import llop
287 def foo():
288 # a bit hard to test, really
289 a = llop.get_exception_addr(llmemory.Address)
290 assert lltype.typeOf(a) is llmemory.Address
291 a = llop.get_exc_value_addr(llmemory.Address)
292 assert lltype.typeOf(a) is llmemory.Address
293 return 42
294 f = self.compile(foo, [])
295 res = f()
296 assert res == 42
297
298 def test_default_error_value(self):
299 def foo(x):
300 if x == 42:
301 raise ValueError
302 return 123
303
304 result = interpret(foo, [1])
305 assert result == 123
306 with py.test.raises(LLException) as exc:
307 interpret(foo, [42])
308 assert exc.value.error_value == -1
309 assert 'ValueError' in str(exc.value)
310
311 def test_llhelper_error_value(self):
312 @llhelper_error_value(-456)
313 def _foo(x):
314 if x == 42:
315 raise ValueError
316 return x
317
318 FN = lltype.Ptr(lltype.FuncType([lltype.Signed], lltype.Signed))
319 def bar(x):
320 foo = llhelper(FN, _foo)
321 return foo(x)
322
323 result = interpret(bar, [123])
324 assert result == 123
325 with py.test.raises(LLException) as exc:
326 interpret(bar, [42])
327 assert exc.value.error_value == -456
328 assert 'ValueError' in str(exc.value)
329 #
330 compiled_foo = self.compile(bar, [int], backendopt=False)
331 assert compiled_foo(123) == 123
332 compiled_foo(42, expected_exception_name='ValueError')
333
334 def test_enforce_llhelper_error_value_in_case_of_nested_exception(self):
335 @dont_inline
336 def my_divide(a, b):
337 if b == 0:
338 raise ZeroDivisionError
339 return a/b
340
341 @llhelper_error_value(-456)
342 def _foo(a, b):
343 res = my_divide(a, b)
344 return res
345
346 FN = lltype.Ptr(lltype.FuncType([lltype.Signed, lltype.Signed], lltype.Signed))
347 def bar(a, b):
348 foo = llhelper(FN, _foo)
349 return foo(a, b)
350
351 result = interpret(bar, [21, 3])
352 assert result == 7
353 with py.test.raises(LLException) as exc:
354 interpret(bar, [21, 0])
355 assert exc.value.error_value == -456
356 assert 'ZeroDivisionError' in str(exc.value)
357 #
358 compiled_foo = self.compile(bar, [int, int], backendopt=False)
359 assert compiled_foo(21, 3) == 7
360 compiled_foo(21, 0, expected_exception_name='ZeroDivisionError')