Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Lib/test/test_peepholer.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ast
import dis
import gc
from itertools import combinations, product
Expand Down Expand Up @@ -1125,6 +1126,53 @@ def trace(frame, event, arg):

class DirectCfgOptimizerTests(CfgOptimizationTestCase):

def test_optimize_cfg_const_index_out_of_range(self):
insts = [
('LOAD_CONST', 2, 0),
('RETURN_VALUE', None, 0),
]
seq = self.seq_from_insts(insts)
with self.assertRaisesRegex(ValueError, "out of range"):
_testinternalcapi.optimize_cfg(seq, [0, 1], 0)

def test_optimize_cfg_consts_must_be_list(self):
insts = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
seq = self.seq_from_insts(insts)
with self.assertRaisesRegex(TypeError, "consts must be a list"):
_testinternalcapi.optimize_cfg(seq, (0,), 0)

def test_compiler_codegen_metadata_consts_roundtrips_optimize_cfg(self):
tree = ast.parse("x = (1, 2)", mode="exec", optimize=1)
insts, meta = _testinternalcapi.compiler_codegen(tree, "<s>", 0)
consts = meta["consts"]
self.assertIsInstance(consts, list)
_testinternalcapi.optimize_cfg(insts, consts, 0)

def test_compiler_codegen_consts_include_none_required_for_implicit_return(self):
# Module "pass" only needs the const table entry for None once
# _PyCodegen_AddReturnAtEnd runs. If metadata["consts"] were taken
# before that, the list would not match LOAD_CONST opargs (here: 0
# for None), and optimize_cfg would read out of range.
tree = ast.parse("pass", mode="exec", optimize=1)
insts, meta = _testinternalcapi.compiler_codegen(tree, "<s>", 0)
consts = meta["consts"]
self.assertEqual(consts, [None])

load_const = opcode.opmap["LOAD_CONST"]
self.assertEqual(
[t[1] for t in insts.get_instructions() if t[0] == load_const],
[0],
)

# As if consts were snapshotted before AddReturnAtEnd: still LOAD_CONST 0, no row.
with self.assertRaisesRegex(ValueError, "out of range"):
_testinternalcapi.optimize_cfg(insts, [], 0)

_testinternalcapi.optimize_cfg(insts, list(consts), 0)

def cfg_optimization_test(self, insts, expected_insts,
consts=None, expected_consts=None,
nlocals=0):
Expand Down
Loading