Debian Codegraph @

pypy/interpreter/test/test_pyframe.py

raw symbols SCIP
1 from pypy.conftest import option
2 from pypy.interpreter.gateway import interp2app
3 from pypy.interpreter.pyframe import mark_stacks, MarkStacks
4 from pypy.interpreter.astcompiler.assemble import _encode_varint
5 from pypy.tool import stdlib_opcode as ops
6
7
8 class FakeCode(object):
9 def __init__(self, co_code, co_exceptiontable=''):
10 self.co_code = co_code
11 self.co_exceptiontable = co_exceptiontable
12
13
14 def make_bytecode(*instrs):
15 return ''.join(chr(op) + chr(arg) for op, arg in instrs)
16
17
18 def make_exceptiontable(*entries):
19 result = []
20 for start, length, target, depth, lasti in entries:
21 _encode_varint(result, start)
22 _encode_varint(result, length)
23 _encode_varint(result, target)
24 _encode_varint(result, (depth << 1) | lasti)
25 return ''.join(result)
26
27
28 _ms = MarkStacks(0) # instance used for constants and push() in helpers below
29
30 def stack(*kinds):
31 """Build expected stack state, bottom-to-top order."""
32 s = _ms.EMPTY
33 for kind in kinds:
34 s = _ms.push(s, kind)
35 return s
36
37
38 # MarkStacks unit tests
39
40 def test_markstacks_push_empty():
41 assert _ms.push(_ms.EMPTY, _ms.OBJECT) == _ms.OBJECT
42
43 def test_markstacks_push_stacks():
44 s = _ms.push(_ms.EMPTY, _ms.ITERATOR)
45 s = _ms.push(s, _ms.OBJECT)
46 # TOS is OBJECT (lowest bits), then ITERATOR
47 assert s & _ms.MASK == _ms.OBJECT
48 assert (s >> _ms.BITS) & _ms.MASK == _ms.ITERATOR
49
50 def test_markstacks_push_overflow():
51 s = _ms.OVERFLOWED
52 assert _ms.push(s, _ms.OBJECT) == _ms.OVERFLOWED
53 s = _ms.UNINITIALIZED
54 assert _ms.push(s, _ms.OBJECT) == _ms.OVERFLOWED
55
56 def test_markstacks_set_initializes():
57 ms = MarkStacks(3)
58 assert ms[1] == ms.UNINITIALIZED
59 changed = ms.set(1, ms.EMPTY, False)
60 assert changed
61 assert ms[1] == ms.EMPTY
62
63 def test_markstacks_set_no_overwrite():
64 ms = MarkStacks(3)
65 ms.set(1, ms.OBJECT, False)
66 changed = ms.set(1, ms.ITERATOR, False)
67 assert not changed
68 assert ms[1] == ms.OBJECT # original value preserved
69
70 def test_markstacks_set_preserves_changed():
71 ms = MarkStacks(3)
72 ms.set(1, ms.OBJECT, False)
73 # slot already set; changed=True should be passed through
74 changed = ms.set(1, ms.ITERATOR, True)
75 assert changed
76
77 def test_markstacks_len():
78 ms = MarkStacks(5)
79 assert len(ms) == 6 # n + 1 slots
80
81 def test_markstacks_compatible_empty_to_empty():
82 assert _ms.compatible(_ms.EMPTY, _ms.EMPTY)
83
84 def test_markstacks_compatible_object_to_object():
85 s = stack(_ms.OBJECT)
86 assert _ms.compatible(s, s)
87
88 def test_markstacks_compatible_deeper_to_shallower():
89 deep = stack(_ms.OBJECT, _ms.OBJECT)
90 shallow = stack(_ms.OBJECT)
91 assert _ms.compatible(deep, shallow)
92
93 def test_markstacks_compatible_shallower_to_deeper():
94 deep = stack(_ms.OBJECT, _ms.OBJECT)
95 shallow = stack(_ms.OBJECT)
96 assert not _ms.compatible(shallow, deep)
97
98 def test_markstacks_compatible_object_accepts_iterator():
99 # OBJECT slot accepts any non-empty kind (iterator, except, etc.)
100 it = stack(_ms.ITERATOR)
101 obj = stack(_ms.OBJECT)
102 assert _ms.compatible(it, obj)
103
104 def test_markstacks_compatible_except_not_interchangeable():
105 exc = stack(_ms.EXCEPT)
106 it = stack(_ms.ITERATOR)
107 assert not _ms.compatible(exc, it)
108 assert not _ms.compatible(it, exc)
109
110 def test_markstacks_compatible_negative():
111 assert not _ms.compatible(_ms.UNINITIALIZED, _ms.EMPTY)
112 assert not _ms.compatible(_ms.EMPTY, _ms.OVERFLOWED)
113
114 def test_markstacks_explain_incompatible_overflowed():
115 assert "deep" in _ms.explain_incompatible(_ms.OVERFLOWED)
116
117 def test_markstacks_explain_incompatible_uninitialized():
118 assert "unreachable" in _ms.explain_incompatible(_ms.UNINITIALIZED)
119
120 def test_markstacks_explain_incompatible_empty():
121 assert "unreachable" in _ms.explain_incompatible(_ms.EMPTY)
122
123 def test_markstacks_explain_incompatible_except():
124 assert "except" in _ms.explain_incompatible(stack(_ms.EXCEPT))
125
126 def test_markstacks_explain_incompatible_iterator():
127 assert "for" in _ms.explain_incompatible(stack(_ms.ITERATOR))
128
129 def test_markstacks_pop_to_level():
130 s = stack(_ms.OBJECT, _ms.ITERATOR, _ms.EXCEPT)
131 assert _ms.pop_to_level(s, 1) == stack(_ms.OBJECT)
132 assert _ms.pop_to_level(s, 0) == _ms.EMPTY
133
134
135 # mark_stacks unit tests
136
137 def test_mark_stacks_linear():
138 # LOAD_CONST pushes an object; RETURN_VALUE is terminal.
139 code = FakeCode(make_bytecode(
140 (ops.LOAD_CONST, 0),
141 (ops.RETURN_VALUE, 0),
142 ))
143 stacks = mark_stacks(code)
144 assert stacks[0] == stacks.EMPTY
145 assert stacks[1] == stack(stacks.OBJECT)
146 assert stacks[2] == stacks.UNINITIALIZED # terminal, no fall-through
147
148 def test_mark_stacks_jump_forward_unreachable():
149 # JUMP_FORWARD skips the NOP; the NOP's slot stays uninitialized.
150 code = FakeCode(make_bytecode(
151 (ops.JUMP_FORWARD, 1), # jump to instr 0+1+1 = 2
152 (ops.NOP, 0), # unreachable
153 (ops.LOAD_CONST, 0),
154 (ops.RETURN_VALUE, 0),
155 ))
156 stacks = mark_stacks(code)
157 assert stacks[0] == stacks.EMPTY
158 assert stacks[1] == stacks.UNINITIALIZED # unreachable NOP
159 assert stacks[2] == stacks.EMPTY # jump target
160 assert stacks[3] == stack(stacks.OBJECT)
161 assert stacks[4] == stacks.UNINITIALIZED # terminal
162
163 def test_mark_stacks_conditional_branch():
164 # POP_JUMP_IF_TRUE pops the condition and branches to index 4 or falls
165 # to index 2; both paths are reachable with an empty stack.
166 code = FakeCode(make_bytecode(
167 (ops.LOAD_CONST, 0), # 0: push object
168 (ops.POP_JUMP_IF_TRUE, 4), # 1: pop, branch to 4 or fall to 2
169 (ops.LOAD_CONST, 0), # 2: false path
170 (ops.RETURN_VALUE, 0), # 3
171 (ops.LOAD_CONST, 0), # 4: true path
172 (ops.RETURN_VALUE, 0), # 5
173 ))
174 stacks = mark_stacks(code)
175 assert stacks[0] == stacks.EMPTY
176 assert stacks[1] == stack(stacks.OBJECT)
177 assert stacks[2] == stacks.EMPTY # fall-through, condition popped
178 assert stacks[3] == stack(stacks.OBJECT)
179 assert stacks[4] == stacks.EMPTY # branch target, condition popped
180 assert stacks[5] == stack(stacks.OBJECT)
181 assert stacks[6] == stacks.UNINITIALIZED
182
183 def test_mark_stacks_for_iter_loop():
184 # GET_ITER converts an object to an iterator; FOR_ITER pushes the loop
185 # variable on the fall-through edge and pops the iterator on the
186 # exhausted-jump edge.
187 code = FakeCode(make_bytecode(
188 (ops.LOAD_CONST, 0), # 0: iterable
189 (ops.GET_ITER, 0), # 1: -> iterator
190 (ops.FOR_ITER, 2), # 2: loop var on fall, jump to 2+2+1=5 when done
191 (ops.POP_TOP, 0), # 3: discard loop var
192 (ops.JUMP_ABSOLUTE, 2), # 4: back to FOR_ITER
193 (ops.RETURN_VALUE, 0), # 5: after loop
194 ))
195 stacks = mark_stacks(code)
196 assert stacks[0] == stacks.EMPTY
197 assert stacks[1] == stack(stacks.OBJECT)
198 assert stacks[2] == stack(stacks.ITERATOR)
199 assert stacks[3] == stack(stacks.ITERATOR, stacks.OBJECT) # loop var on top
200 assert stacks[4] == stack(stacks.ITERATOR) # after discarding loop var
201 assert stacks[5] == stacks.EMPTY # iterator popped on exhaustion
202 assert stacks[6] == stacks.UNINITIALIZED
203
204 def test_mark_stacks_push_exc_info_pop_except():
205 # PUSH_EXC_INFO: pops exc (Object), pushes prev_exc (Except) + exc (Object).
206 # POP_EXCEPT: pops the prev_exc (Except slot).
207 code = FakeCode(make_bytecode(
208 (ops.LOAD_CONST, 0), # 0: exc object
209 (ops.PUSH_EXC_INFO, 0), # 1
210 (ops.POP_EXCEPT, 0), # 2
211 (ops.RETURN_VALUE, 0), # 3
212 ))
213 stacks = mark_stacks(code)
214 assert stacks[0] == stacks.EMPTY
215 assert stacks[1] == stack(stacks.OBJECT)
216 assert stacks[2] == stack(stacks.EXCEPT, stacks.OBJECT)
217 assert stacks[3] == stack(stacks.EXCEPT)
218
219 def test_mark_stacks_exceptiontable_no_lasti():
220 # Exception table entry with lasti=False seeds the handler with [EXCEPT].
221 code = FakeCode(
222 make_bytecode(
223 (ops.LOAD_CONST, 0), # 0: try body
224 (ops.RETURN_VALUE, 0), # 1: terminal
225 (ops.PUSH_EXC_INFO, 0), # 2: handler entry point
226 (ops.RETURN_VALUE, 0), # 3
227 ),
228 make_exceptiontable((0, 1, 2, 0, 0)), # start=0, len=1, target=2, depth=0, lasti=0
229 )
230 stacks = mark_stacks(code)
231 assert stacks[2] == stack(stacks.EXCEPT)
232 # PUSH_EXC_INFO at 2 pops EXCEPT, pushes EXCEPT + OBJECT
233 assert stacks[3] == stack(stacks.EXCEPT, stacks.OBJECT)
234
235 def test_mark_stacks_exceptiontable_lasti():
236 # Exception table entry with lasti=True seeds the handler with [LASTI, EXCEPT].
237 code = FakeCode(
238 make_bytecode(
239 (ops.LOAD_CONST, 0), # 0: try body
240 (ops.RETURN_VALUE, 0), # 1: terminal
241 (ops.PUSH_EXC_INFO, 0), # 2: handler entry point
242 (ops.RETURN_VALUE, 0), # 3
243 ),
244 make_exceptiontable((0, 1, 2, 0, 1)), # start=0, len=1, target=2, depth=0, lasti=1
245 )
246 stacks = mark_stacks(code)
247 assert stacks[2] == stack(stacks.LASTI, stacks.EXCEPT)
248 # PUSH_EXC_INFO at 2: pops EXCEPT (TOS), pushes EXCEPT + OBJECT
249 assert stacks[3] == stack(stacks.LASTI, stacks.EXCEPT, stacks.OBJECT)
250
251 def check_no_w_locals(space, w_frame):
252 return space.wrap(w_frame.getorcreatedebug().w_locals is None)
253
254 class AppTestPyFrame:
255
256 def setup_class(cls):
257 space = cls.space
258 if not option.runappdirect:
259 w_call_further = cls.space.appexec([], """():
260 def call_further(f):
261 return f()
262 return call_further
263 """)
264 assert not w_call_further.code.hidden_applevel
265 w_call_further.code.hidden_applevel = True # hack
266 cls.w_call_further = w_call_further
267
268 cls.w_check_no_w_locals = space.wrap(interp2app(check_no_w_locals))
269
270 # test for the presence of the attributes, not functionality
271
272 def test_set_lineno(self):
273 import sys
274 class JumpTracer:
275 def __init__(self, function):
276 self.function = function
277 self.jumpFrom = function.jump[0]
278 self.jumpTo = function.jump[1]
279 self.done = False
280
281 def trace(self, frame, event, arg):
282 if not self.done and frame.f_code == self.function.__code__:
283 firstLine = frame.f_code.co_firstlineno
284 if event == 'line' and frame.f_lineno == firstLine + self.jumpFrom:
285 # Cope with non-integer self.jumpTo (because of
286 # no_jump_to_non_integers below).
287 try:
288 frame.f_lineno = firstLine + self.jumpTo
289 except TypeError:
290 frame.f_lineno = self.jumpTo
291 self.done = True
292 return self.trace
293
294 def run_test(func):
295 tracer = JumpTracer(func)
296 sys.settrace(tracer.trace)
297 output = []
298 func(output)
299 sys.settrace(None)
300 assert func.output == output
301
302 # copied from cpython test suite
303 def jump_out_of_block_forwards(output):
304 for i in 1, 2:
305 output.append(2)
306 for j in [3]: # Also tests jumping over a block
307 output.append(4)
308 output.append(5)
309
310 jump_out_of_block_forwards.jump = (3, 5)
311 jump_out_of_block_forwards.output = [2, 5]
312 run_test(jump_out_of_block_forwards)
313
314 def jump_out_of_block_backwards(output):
315 output.append(1)
316 for i in [1]:
317 output.append(3)
318 for j in [2]: # Also tests jumping over a block
319 output.append(5)
320 output.append(6)
321 output.append(7)
322
323 jump_out_of_block_backwards.jump = (6, 1)
324 jump_out_of_block_backwards.output = [1, 3, 5, 1, 3, 5, 6, 7]
325 run_test(jump_out_of_block_backwards)
326
327
328 def jump_to_codeless_line(output):
329 output.append(1)
330 # Jumping to this line should skip to the next one.
331 output.append(3)
332 jump_to_codeless_line.jump = (1, 2)
333 jump_to_codeless_line.output = [3]
334 run_test(jump_to_codeless_line)
335
336 def jump_in_nested_finally(output):
337 try:
338 output.append(2)
339 finally:
340 output.append(4)
341 try:
342 output.append(6)
343 finally:
344 output.append(8)
345 output.append(9)
346 jump_in_nested_finally.jump = (4, 9)
347 jump_in_nested_finally.output = [2, 9]
348 run_test(jump_in_nested_finally)
349
350
351 def test_f_back_hidden(self):
352 if not hasattr(self, 'call_further'):
353 skip("not for runappdirect testing")
354 import sys
355 def f():
356 return (sys._getframe(0),
357 sys._getframe(1),
358 sys._getframe(0).f_back)
359 def main():
360 return self.call_further(f)
361 f0, f1, f1bis = main()
362 assert f0.f_code.co_name == 'f'
363 assert f1.f_code.co_name == 'main'
364 assert f1bis is f1
365 assert f0.f_back is f1
366
367 def test_fast2locals_called_lazily(self):
368 import sys
369 class FrameHolder:
370 pass
371 fh = FrameHolder()
372 def trace(frame, what, arg):
373 # trivial trace function, does not access f_locals
374 fh.frame = frame
375 return trace
376 def f(x):
377 x += 1
378 return x
379 sys.settrace(trace)
380 res = f(1)
381 sys.settrace(None)
382 assert res == 2
383 if hasattr(self, "check_no_w_locals"): # not appdirect
384 assert self.check_no_w_locals(fh.frame)
385
386 def test_del_cell_locals_bug(self):
387 """
388 def f():
389 x = object()
390
391 def foo():
392 print(x)
393
394 locals()
395 del x
396 assert "x" not in locals()
397 f()
398 """
399
400 def test_repr(self):
401 import sys
402 def a_name(a, b, c):
403 a + b + c
404 return sys._getframe()
405 frame = a_name(5, 6, 4)
406 r = repr(frame)
407 assert "a_name" in r