1
2 from test.support.bytecode_helper import CodegenTestCase
3
4 # Tests for the code-generation stage of the compiler.
5 # Examine the un-optimized code generated from the AST.
6
7 class ESC[4;38;5;81mIsolatedCodeGenTests(ESC[4;38;5;149mCodegenTestCase):
8
9 def codegen_test(self, snippet, expected_insts):
10 import ast
11 a = ast.parse(snippet, "my_file.py", "exec");
12 insts = self.generate_code(a)
13 self.assertInstructionsMatch(insts, expected_insts)
14
15 def test_if_expression(self):
16 snippet = "42 if True else 24"
17 false_lbl = self.Label()
18 expected = [
19 ('RESUME', 0, 0),
20 ('LOAD_CONST', 0, 1),
21 ('POP_JUMP_IF_FALSE', false_lbl := self.Label(), 1),
22 ('LOAD_CONST', 1, 1),
23 ('JUMP', exit_lbl := self.Label()),
24 false_lbl,
25 ('LOAD_CONST', 2, 1),
26 exit_lbl,
27 ('POP_TOP', None),
28 ('LOAD_CONST', 3),
29 ('RETURN_VALUE', None),
30 ]
31 self.codegen_test(snippet, expected)
32
33 def test_for_loop(self):
34 snippet = "for x in l:\n\tprint(x)"
35 false_lbl = self.Label()
36 expected = [
37 ('RESUME', 0, 0),
38 ('LOAD_NAME', 0, 1),
39 ('GET_ITER', None, 1),
40 loop_lbl := self.Label(),
41 ('FOR_ITER', exit_lbl := self.Label(), 1),
42 ('STORE_NAME', 1, 1),
43 ('PUSH_NULL', None, 2),
44 ('LOAD_NAME', 2, 2),
45 ('LOAD_NAME', 1, 2),
46 ('CALL', 1, 2),
47 ('POP_TOP', None),
48 ('JUMP', loop_lbl),
49 exit_lbl,
50 ('END_FOR', None),
51 ('LOAD_CONST', 0),
52 ('RETURN_VALUE', None),
53 ]
54 self.codegen_test(snippet, expected)