Debian Codegraph @

pypy/interpreter/astcompiler/test/apptest_compiler.py

raw symbols SCIP
1 import pytest
2
3
4 def _get_line_numbers(source, function=False):
5 import dis
6 code = compile(source, '<test>', 'exec')
7 if function:
8 code = code.co_consts[0]
9 lines = [line for (start, line) in dis.findlinestarts(code)]
10 if function:
11 # Normalize relative to co_firstlineno (the def line).
12 # CPython 3.11+ emits RESUME at co_firstlineno; PyPy does not.
13 # Skip that entry so both produce the same sequence.
14 base = code.co_firstlineno - 1
15 lines = [l for l in lines if l != code.co_firstlineno]
16 else:
17 base = min(lines)
18 return [line - base for line in lines]
19
20
21 def test_nonlocal_class_nesting_bug():
22 def foo():
23 var = 0
24 class C:
25 def wrapper():
26 nonlocal var
27 var = 1
28 wrapper()
29 nonlocal var
30 return var
31 assert foo() == 1
32
33
34 def test_if_call_or_call_bug():
35 # used to crash the compiler
36 a = True
37 calls = []
38 def f1(): calls.append('f1')
39 def g1(): calls.append('g1')
40 if a:
41 (f1() or
42 g1())
43 assert calls == ['f1', 'g1'] # f1 returns None (falsy), so g1 runs
44 calls = []
45 if a:
46 (f1() and
47 g1())
48 assert calls == ['f1'] # f1 returns None (falsy), g1 short-circuits
49
50
51 def test_match_optimize_default():
52 def f(x):
53 match x:
54 case 1:
55 return 1
56 case _:
57 return 2
58 assert f(1) == 1
59 assert f(99) == 2
60
61
62 def test_elim_jump_to_return():
63 # CPython 3.11 keeps JUMP_FORWARD for "return x if cond else y".
64 # We check that no JUMP_ABSOLUTE is emitted, matching CPython.
65 import dis
66 def f():
67 return true_value if cond else false_value # noqa: F821
68 instrs = list(dis.get_instructions(f))
69 opnames = [i.opname for i in instrs]
70 assert 'JUMP_ABSOLUTE' not in opnames
71
72
73 def test_crash_ifelse_in_except():
74 got = _get_line_numbers("""
75 def buggy():
76 try:
77 pass
78 except OSError as exc:
79 if a:
80 pass
81 elif b:
82 pass
83 else:
84 f
85 """, function=True)
86 assert got == [2, 3, 10, 4, 5, 6, 7, 8, 7, 6, 4]
87
88
89 def test_or_with_implicit_return():
90 got = _get_line_numbers("""
91 def or_with_implicit_return():
92 if a:
93 (g
94 or
95 h)""", function=True)
96 assert got == [2, 3, 5, 2]