|
| 1 | +import ast |
1 | 2 | import dis |
2 | 3 | from itertools import combinations, product |
3 | 4 | import opcode |
|
6 | 7 | import unittest |
7 | 8 |
|
8 | 9 | from test import support |
9 | | -from test.support.bytecode_helper import BytecodeTestCase, CfgOptimizationTestCase |
| 10 | +from test.support.bytecode_helper import ( |
| 11 | + BytecodeTestCase, |
| 12 | + CfgOptimizationTestCase, |
| 13 | + _testinternalcapi, |
| 14 | +) |
10 | 15 |
|
11 | 16 |
|
12 | 17 | def compile_pattern_with_fast_locals(pattern): |
@@ -962,6 +967,45 @@ def trace(frame, event, arg): |
962 | 967 |
|
963 | 968 | class DirectCfgOptimizerTests(CfgOptimizationTestCase): |
964 | 969 |
|
| 970 | + def test_optimize_cfg_const_index_out_of_range(self): |
| 971 | + insts = [ |
| 972 | + ('LOAD_CONST', 2, 0), |
| 973 | + ('RETURN_VALUE', None, 0), |
| 974 | + ] |
| 975 | + seq = self.seq_from_insts(insts) |
| 976 | + with self.assertRaisesRegex(ValueError, "out of range"): |
| 977 | + _testinternalcapi.optimize_cfg(seq, [0, 1], 0) |
| 978 | + |
| 979 | + def test_optimize_cfg_consts_must_be_list(self): |
| 980 | + insts = [ |
| 981 | + ('LOAD_CONST', 0, 0), |
| 982 | + ('RETURN_VALUE', None, 0), |
| 983 | + ] |
| 984 | + seq = self.seq_from_insts(insts) |
| 985 | + with self.assertRaisesRegex(TypeError, "consts must be a list"): |
| 986 | + _testinternalcapi.optimize_cfg(seq, (0,), 0) |
| 987 | + |
| 988 | + def test_compiler_codegen_metadata_consts_roundtrips_optimize_cfg(self): |
| 989 | + tree = ast.parse("x = (1, 2)", mode="exec", optimize=1) |
| 990 | + insts, meta = _testinternalcapi.compiler_codegen(tree, "<s>", 0) |
| 991 | + consts = meta["consts"] |
| 992 | + self.assertIsInstance(consts, list) |
| 993 | + _testinternalcapi.optimize_cfg(insts, consts, 0) |
| 994 | + |
| 995 | + def test_compiler_codegen_consts_include_none_required_for_implicit_return(self): |
| 996 | + tree = ast.parse("pass", mode="exec", optimize=1) |
| 997 | + insts, meta = _testinternalcapi.compiler_codegen(tree, "<s>", 0) |
| 998 | + consts = meta["consts"] |
| 999 | + self.assertEqual(consts, [None]) |
| 1000 | + |
| 1001 | + load_const = opcode.opmap["LOAD_CONST"] |
| 1002 | + self.assertEqual( |
| 1003 | + [t[1] for t in insts.get_instructions() if t[0] == load_const], |
| 1004 | + [0], |
| 1005 | + ) |
| 1006 | + |
| 1007 | + _testinternalcapi.optimize_cfg(insts, list(consts), 0) |
| 1008 | + |
965 | 1009 | def cfg_optimization_test(self, insts, expected_insts, |
966 | 1010 | consts=None, expected_consts=None, |
967 | 1011 | nlocals=0): |
|
0 commit comments