Debian Codegraph @

lib-python/3/test/test_peepholer.py

raw symbols SCIP
1 import dis
2 from itertools import combinations, product
3 import textwrap
4 import unittest
5 from test.support import cpython_only
6
7 from test import support
8 from test.support.bytecode_helper import BytecodeTestCase
9
10
11 def compile_pattern_with_fast_locals(pattern):
12 source = textwrap.dedent(
13 f"""
14 def f(x):
15 match x:
16 case {pattern}:
17 pass
18 """
19 )
20 namespace = {}
21 exec(source, namespace)
22 return namespace["f"].__code__
23
24
25 def count_instr_recursively(f, opname):
26 count = 0
27 for instr in dis.get_instructions(f):
28 if instr.opname == opname:
29 count += 1
30 if hasattr(f, '__code__'):
31 f = f.__code__
32 for c in f.co_consts:
33 if hasattr(c, 'co_code'):
34 count += count_instr_recursively(c, opname)
35 return count
36
37
38 class TestTranforms(BytecodeTestCase):
39
40 def check_jump_targets(self, code):
41 instructions = list(dis.get_instructions(code))
42 targets = {instr.offset: instr for instr in instructions}
43 for instr in instructions:
44 if 'JUMP_' not in instr.opname:
45 continue
46 tgt = targets[instr.argval]
47 # jump to unconditional jump
48 if tgt.opname in ('JUMP_ABSOLUTE', 'JUMP_FORWARD'):
49 self.fail(f'{instr.opname} at {instr.offset} '
50 f'jumps to {tgt.opname} at {tgt.offset}')
51 # unconditional jump to RETURN_VALUE
52 if (instr.opname in ('JUMP_ABSOLUTE', 'JUMP_FORWARD') and
53 tgt.opname == 'RETURN_VALUE'):
54 self.fail(f'{instr.opname} at {instr.offset} '
55 f'jumps to {tgt.opname} at {tgt.offset}')
56 # JUMP_IF_*_OR_POP jump to conditional jump
57 if '_OR_POP' in instr.opname and 'JUMP_IF_' in tgt.opname:
58 self.fail(f'{instr.opname} at {instr.offset} '
59 f'jumps to {tgt.opname} at {tgt.offset}')
60
61 def check_lnotab(self, code):
62 "Check that the lnotab byte offsets are sensible."
63 code = dis._get_code_object(code)
64 lnotab = list(dis.findlinestarts(code))
65 # Don't bother checking if the line info is sensible, because
66 # most of the line info we can get at comes from lnotab.
67 min_bytecode = min(t[0] for t in lnotab)
68 max_bytecode = max(t[0] for t in lnotab)
69 self.assertGreaterEqual(min_bytecode, 0)
70 self.assertLess(max_bytecode, len(code.co_code))
71 # This could conceivably test more (and probably should, as there
72 # aren't very many tests of lnotab), if peepholer wasn't scheduled
73 # to be replaced anyway.
74
75 @cpython_only
76 def test_unot(self):
77 # UNARY_NOT POP_JUMP_IF_FALSE --> POP_JUMP_IF_TRUE'
78 def unot(x):
79 if not x == 2:
80 del x
81 self.assertNotInBytecode(unot, 'UNARY_NOT')
82 self.assertNotInBytecode(unot, 'POP_JUMP_FORWARD_IF_FALSE')
83 self.assertNotInBytecode(unot, 'POP_JUMP_BACKWARD_IF_FALSE')
84 self.assertInBytecode(unot, 'POP_JUMP_FORWARD_IF_TRUE')
85 self.check_lnotab(unot)
86
87 def test_elim_inversion_of_is_or_in(self):
88 for line, cmp_op, invert in (
89 ('not a is b', 'IS_OP', 1,),
90 ('not a is not b', 'IS_OP', 0,),
91 ('not a in b', 'CONTAINS_OP', 1,),
92 ('not a not in b', 'CONTAINS_OP', 0,),
93 ):
94 with self.subTest(line=line):
95 code = compile(line, '', 'single')
96 self.assertInBytecode(code, cmp_op, invert)
97 self.check_lnotab(code)
98
99 def test_global_as_constant(self):
100 # LOAD_GLOBAL None/True/False --> LOAD_CONST None/True/False
101 def f():
102 x = None
103 x = None
104 return x
105 def g():
106 x = True
107 return x
108 def h():
109 x = False
110 return x
111
112 for func, elem in ((f, None), (g, True), (h, False)):
113 with self.subTest(func=func):
114 self.assertNotInBytecode(func, 'LOAD_GLOBAL')
115 self.assertInBytecode(func, 'LOAD_CONST', elem)
116 self.check_lnotab(func)
117
118 def f():
119 'Adding a docstring made this test fail in Py2.5.0'
120 return None
121
122 self.assertNotInBytecode(f, 'LOAD_GLOBAL')
123 self.assertInBytecode(f, 'LOAD_CONST', None)
124 self.check_lnotab(f)
125
126 @cpython_only
127 def test_while_one(self):
128 # Skip over: LOAD_CONST trueconst POP_JUMP_IF_FALSE xx
129 def f():
130 while 1:
131 pass
132 return list
133 for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'):
134 self.assertNotInBytecode(f, elem)
135 for elem in ('JUMP_BACKWARD',):
136 self.assertInBytecode(f, elem)
137 self.check_lnotab(f)
138
139 @cpython_only
140 def test_pack_unpack(self):
141 for line, elem in (
142 ('a, = a,', 'LOAD_CONST',),
143 ('a, b = a, b', 'SWAP',),
144 ('a, b, c = a, b, c', 'SWAP',),
145 ):
146 with self.subTest(line=line):
147 code = compile(line,'','single')
148 self.assertInBytecode(code, elem)
149 self.assertNotInBytecode(code, 'BUILD_TUPLE')
150 self.assertNotInBytecode(code, 'UNPACK_SEQUENCE')
151 self.check_lnotab(code)
152
153 @cpython_only
154 def test_folding_of_tuples_of_constants(self):
155 for line, elem in (
156 ('a = 1,2,3', (1, 2, 3)),
157 ('("a","b","c")', ('a', 'b', 'c')),
158 ('a,b,c = 1,2,3', (1, 2, 3)),
159 ('(None, 1, None)', (None, 1, None)),
160 ('((1, 2), 3, 4)', ((1, 2), 3, 4)),
161 ):
162 with self.subTest(line=line):
163 code = compile(line,'','single')
164 self.assertInBytecode(code, 'LOAD_CONST', elem)
165 self.assertNotInBytecode(code, 'BUILD_TUPLE')
166 self.check_lnotab(code)
167
168 # Long tuples should be folded too.
169 code = compile(repr(tuple(range(10000))),'','single')
170 self.assertNotInBytecode(code, 'BUILD_TUPLE')
171 # One LOAD_CONST for the tuple, one for the None return value
172 load_consts = [instr for instr in dis.get_instructions(code)
173 if instr.opname == 'LOAD_CONST']
174 self.assertEqual(len(load_consts), 2)
175 self.check_lnotab(code)
176
177 # Bug 1053819: Tuple of constants misidentified when presented with:
178 # . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . .
179 # The following would segfault upon compilation
180 def crater():
181 (~[
182 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
183 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
184 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
185 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
186 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
187 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
188 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
189 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
190 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
191 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
192 ],)
193 self.check_lnotab(crater)
194
195 def test_folding_of_lists_of_constants(self):
196 for line, elem in (
197 # in/not in constants with BUILD_LIST should be folded to a tuple:
198 ('a in [1,2,3]', (1, 2, 3)),
199 ('a not in ["a","b","c"]', ('a', 'b', 'c')),
200 ('a in [None, 1, None]', (None, 1, None)),
201 ('a not in [(1, 2), 3, 4]', ((1, 2), 3, 4)),
202 ):
203 with self.subTest(line=line):
204 code = compile(line, '', 'single')
205 self.assertInBytecode(code, 'LOAD_CONST', elem)
206 self.assertNotInBytecode(code, 'BUILD_LIST')
207 self.check_lnotab(code)
208
209 def test_folding_of_sets_of_constants(self):
210 for line, elem in (
211 # in/not in constants with BUILD_SET should be folded to a frozenset:
212 ('a in {1,2,3}', frozenset({1, 2, 3})),
213 ('a not in {"a","b","c"}', frozenset({'a', 'c', 'b'})),
214 ('a in {None, 1, None}', frozenset({1, None})),
215 ('a not in {(1, 2), 3, 4}', frozenset({(1, 2), 3, 4})),
216 ('a in {1, 2, 3, 3, 2, 1}', frozenset({1, 2, 3})),
217 ):
218 with self.subTest(line=line):
219 code = compile(line, '', 'single')
220 self.assertNotInBytecode(code, 'BUILD_SET')
221 self.assertInBytecode(code, 'LOAD_CONST', elem)
222 self.check_lnotab(code)
223
224 # Ensure that the resulting code actually works:
225 def f(a):
226 return a in {1, 2, 3}
227
228 def g(a):
229 return a not in {1, 2, 3}
230
231 self.assertTrue(f(3))
232 self.assertTrue(not f(4))
233 self.check_lnotab(f)
234
235 self.assertTrue(not g(3))
236 self.assertTrue(g(4))
237 self.check_lnotab(g)
238
239
240 @cpython_only
241 def test_folding_of_binops_on_constants(self):
242 for line, elem in (
243 ('a = 2+3+4', 9), # chained fold
244 ('"@"*4', '@@@@'), # check string ops
245 ('a="abc" + "def"', 'abcdef'), # check string ops
246 ('a = 3**4', 81), # binary power
247 ('a = 3*4', 12), # binary multiply
248 ('a = 13//4', 3), # binary floor divide
249 ('a = 14%4', 2), # binary modulo
250 ('a = 2+3', 5), # binary add
251 ('a = 13-4', 9), # binary subtract
252 ('a = (12,13)[1]', 13), # binary subscr
253 ('a = 13 << 2', 52), # binary lshift
254 ('a = 13 >> 2', 3), # binary rshift
255 ('a = 13 & 7', 5), # binary and
256 ('a = 13 ^ 7', 10), # binary xor
257 ('a = 13 | 7', 15), # binary or
258 ):
259 with self.subTest(line=line):
260 code = compile(line, '', 'single')
261 self.assertInBytecode(code, 'LOAD_CONST', elem)
262 for instr in dis.get_instructions(code):
263 self.assertFalse(instr.opname.startswith('BINARY_'))
264 self.check_lnotab(code)
265
266 # Verify that unfoldables are skipped
267 code = compile('a=2+"b"', '', 'single')
268 self.assertInBytecode(code, 'LOAD_CONST', 2)
269 self.assertInBytecode(code, 'LOAD_CONST', 'b')
270 self.check_lnotab(code)
271
272 # Verify that large sequences do not result from folding
273 code = compile('a="x"*10000', '', 'single')
274 self.assertInBytecode(code, 'LOAD_CONST', 10000)
275 self.assertNotIn("x"*10000, code.co_consts)
276 self.check_lnotab(code)
277 code = compile('a=1<<1000', '', 'single')
278 self.assertInBytecode(code, 'LOAD_CONST', 1000)
279 self.assertNotIn(1<<1000, code.co_consts)
280 self.check_lnotab(code)
281 code = compile('a=2**1000', '', 'single')
282 self.assertInBytecode(code, 'LOAD_CONST', 1000)
283 self.assertNotIn(2**1000, code.co_consts)
284 self.check_lnotab(code)
285
286 @cpython_only # we currently not bother to implement that
287 def test_binary_subscr_on_unicode(self):
288 # valid code get optimized
289 code = compile('"foo"[0]', '', 'single')
290 self.assertInBytecode(code, 'LOAD_CONST', 'f')
291 self.assertNotInBytecode(code, 'BINARY_SUBSCR')
292 self.check_lnotab(code)
293 code = compile('"\u0061\uffff"[1]', '', 'single')
294 self.assertInBytecode(code, 'LOAD_CONST', '\uffff')
295 self.assertNotInBytecode(code,'BINARY_SUBSCR')
296 self.check_lnotab(code)
297
298 # With PEP 393, non-BMP char get optimized
299 code = compile('"\U00012345"[0]', '', 'single')
300 self.assertInBytecode(code, 'LOAD_CONST', '\U00012345')
301 self.assertNotInBytecode(code, 'BINARY_SUBSCR')
302 self.check_lnotab(code)
303
304 # invalid code doesn't get optimized
305 # out of range
306 code = compile('"fuu"[10]', '', 'single')
307 self.assertInBytecode(code, 'BINARY_SUBSCR')
308 self.check_lnotab(code)
309
310 def test_folding_of_unaryops_on_constants(self):
311 for line, elem in (
312 ('-0.5', -0.5), # unary negative
313 ('-0.0', -0.0), # -0.0
314 ('-(1.0-1.0)', -0.0), # -0.0 after folding
315 ('-0', 0), # -0
316 ('~-2', 1), # unary invert
317 ('+1', 1), # unary positive
318 ):
319 with self.subTest(line=line):
320 code = compile(line, '', 'single')
321 self.assertInBytecode(code, 'LOAD_CONST', elem)
322 for instr in dis.get_instructions(code):
323 self.assertFalse(instr.opname.startswith('UNARY_'))
324 self.check_lnotab(code)
325
326 # Check that -0.0 works after marshaling
327 def negzero():
328 return -(1.0-1.0)
329
330 for instr in dis.get_instructions(negzero):
331 self.assertFalse(instr.opname.startswith('UNARY_'))
332 self.check_lnotab(negzero)
333
334 # Verify that unfoldables are skipped
335 for line, elem, opname in (
336 ('-"abc"', 'abc', 'UNARY_NEGATIVE'),
337 ('~"abc"', 'abc', 'UNARY_INVERT'),
338 ):
339 with self.subTest(line=line):
340 code = compile(line, '', 'single')
341 self.assertInBytecode(code, 'LOAD_CONST', elem)
342 self.assertInBytecode(code, opname)
343 self.check_lnotab(code)
344
345 def test_elim_extra_return(self):
346 # RETURN LOAD_CONST None RETURN --> RETURN
347 def f(x):
348 return x
349 self.assertNotInBytecode(f, 'LOAD_CONST', None)
350 returns = [instr for instr in dis.get_instructions(f)
351 if instr.opname == 'RETURN_VALUE']
352 self.assertEqual(len(returns), 1)
353 self.check_lnotab(f)
354
355 @unittest.skip("Following gh-92228 the return has two predecessors "
356 "and that prevents jump elimination.")
357 def test_elim_jump_to_return(self):
358 # JUMP_FORWARD to RETURN --> RETURN
359 def f(cond, true_value, false_value):
360 # Intentionally use two-line expression to test issue37213.
361 return (true_value if cond
362 else false_value)
363 self.check_jump_targets(f)
364 self.assertNotInBytecode(f, 'JUMP_FORWARD')
365 self.assertNotInBytecode(f, 'JUMP_ABSOLUTE')
366 returns = [instr for instr in dis.get_instructions(f)
367 if instr.opname == 'RETURN_VALUE']
368 self.assertEqual(len(returns), 2)
369 self.check_lnotab(f)
370
371 def test_elim_jump_to_uncond_jump(self):
372 # POP_JUMP_IF_FALSE to JUMP_FORWARD --> POP_JUMP_IF_FALSE to non-jump
373 def f():
374 if a:
375 # Intentionally use two-line expression to test issue37213.
376 if (c
377 or d):
378 foo()
379 else:
380 baz()
381 self.check_jump_targets(f)
382 self.check_lnotab(f)
383
384 def test_elim_jump_to_uncond_jump2(self):
385 # POP_JUMP_IF_FALSE to JUMP_ABSOLUTE --> POP_JUMP_IF_FALSE to non-jump
386 def f():
387 while a:
388 # Intentionally use two-line expression to test issue37213.
389 if (c
390 or d):
391 a = foo()
392 self.check_jump_targets(f)
393 self.check_lnotab(f)
394
395 @cpython_only # PyPy fails check_jump_targets in some cases
396 def test_elim_jump_to_uncond_jump3(self):
397 # Intentionally use two-line expressions to test issue37213.
398 # JUMP_IF_FALSE_OR_POP to JUMP_IF_FALSE_OR_POP --> JUMP_IF_FALSE_OR_POP to non-jump
399 def f(a, b, c):
400 return ((a and b)
401 and c)
402 self.check_jump_targets(f)
403 self.check_lnotab(f)
404 self.assertEqual(count_instr_recursively(f, 'JUMP_IF_FALSE_OR_POP'), 2)
405 # JUMP_IF_TRUE_OR_POP to JUMP_IF_TRUE_OR_POP --> JUMP_IF_TRUE_OR_POP to non-jump
406 def f(a, b, c):
407 return ((a or b)
408 or c)
409 self.check_jump_targets(f)
410 self.check_lnotab(f)
411 self.assertEqual(count_instr_recursively(f, 'JUMP_IF_TRUE_OR_POP'), 2)
412 # JUMP_IF_FALSE_OR_POP to JUMP_IF_TRUE_OR_POP --> POP_JUMP_IF_FALSE to non-jump
413 def f(a, b, c):
414 return ((a and b)
415 or c)
416 self.check_jump_targets(f)
417 self.check_lnotab(f)
418 self.assertNotInBytecode(f, 'JUMP_IF_FALSE_OR_POP')
419 self.assertInBytecode(f, 'JUMP_IF_TRUE_OR_POP')
420 self.assertInBytecode(f, 'POP_JUMP_FORWARD_IF_FALSE')
421 # JUMP_IF_TRUE_OR_POP to JUMP_IF_FALSE_OR_POP --> POP_JUMP_IF_TRUE to non-jump
422 def f(a, b, c):
423 return ((a or b)
424 and c)
425 self.check_jump_targets(f)
426 self.check_lnotab(f)
427 self.assertNotInBytecode(f, 'JUMP_IF_TRUE_OR_POP')
428 self.assertInBytecode(f, 'JUMP_IF_FALSE_OR_POP')
429 self.assertInBytecode(f, 'POP_JUMP_FORWARD_IF_TRUE')
430
431 def test_elim_jump_after_return1(self):
432 # Eliminate dead code: jumps immediately after returns can't be reached
433 def f(cond1, cond2):
434 if cond1: return 1
435 if cond2: return 2
436 while 1:
437 return 3
438 while 1:
439 if cond1: return 4
440 return 5
441 return 6
442 self.assertNotInBytecode(f, 'JUMP_FORWARD')
443 self.assertNotInBytecode(f, 'JUMP_ABSOLUTE')
444 returns = [instr for instr in dis.get_instructions(f)
445 if instr.opname == 'RETURN_VALUE']
446 self.assertLessEqual(len(returns), 6)
447 self.check_lnotab(f)
448
449 def test_make_function_doesnt_bail(self):
450 def f():
451 def g()->1+1:
452 pass
453 return g
454 self.assertNotInBytecode(f, 'BINARY_OP')
455 self.check_lnotab(f)
456
457 def test_constant_folding(self):
458 # Issue #11244: aggressive constant folding.
459 exprs = [
460 '3 * -5',
461 '-3 * 5',
462 '2 * (3 * 4)',
463 '(2 * 3) * 4',
464 '(-1, 2, 3)',
465 '(1, -2, 3)',
466 '(1, 2, -3)',
467 '(1, 2, -3) * 6',
468 'lambda x: x in {(3 * -5) + (-1 - 6), (1, -2, 3) * 2, None}',
469 ]
470 for e in exprs:
471 code = compile(e, '', 'single')
472 for instr in dis.get_instructions(code):
473 self.assertFalse(instr.opname.startswith('UNARY_'))
474 self.assertFalse(instr.opname.startswith('BINARY_'))
475 self.assertFalse(instr.opname.startswith('BUILD_'))
476 self.check_lnotab(code)
477
478 @cpython_only
479 def test_in_literal_list(self):
480 def containtest():
481 return x in [a, b]
482 self.assertEqual(count_instr_recursively(containtest, 'BUILD_LIST'), 0)
483 self.check_lnotab(containtest)
484
485 @cpython_only
486 def test_iterate_literal_list(self):
487 def forloop():
488 for x in [a, b]:
489 pass
490 self.assertEqual(count_instr_recursively(forloop, 'BUILD_LIST'), 0)
491 self.check_lnotab(forloop)
492
493 def test_condition_with_binop_with_bools(self):
494 def f():
495 if True or False:
496 return 1
497 return 0
498 self.assertEqual(f(), 1)
499 self.check_lnotab(f)
500
501 def test_if_with_if_expression(self):
502 # Check bpo-37289
503 def f(x):
504 if (True if x else False):
505 return True
506 return False
507 self.assertTrue(f(True))
508 self.check_lnotab(f)
509
510 def test_trailing_nops(self):
511 # Check the lnotab of a function that even after trivial
512 # optimization has trailing nops, which the lnotab adjustment has to
513 # handle properly (bpo-38115).
514 def f(x):
515 while 1:
516 return 3
517 while 1:
518 return 5
519 return 6
520 self.check_lnotab(f)
521
522 def test_assignment_idiom_in_comprehensions(self):
523 def listcomp():
524 return [y for x in a for y in [f(x)]]
525 self.assertEqual(count_instr_recursively(listcomp, 'FOR_ITER'), 1)
526 def setcomp():
527 return {y for x in a for y in [f(x)]}
528 self.assertEqual(count_instr_recursively(setcomp, 'FOR_ITER'), 1)
529 def dictcomp():
530 return {y: y for x in a for y in [f(x)]}
531 self.assertEqual(count_instr_recursively(dictcomp, 'FOR_ITER'), 1)
532 def genexpr():
533 return (y for x in a for y in [f(x)])
534 self.assertEqual(count_instr_recursively(genexpr, 'FOR_ITER'), 1)
535
536 @support.requires_resource('cpu')
537 def test_format_combinations(self):
538 flags = '-+ #0'
539 testcases = [
540 *product(('', '1234', 'абвг'), 'sra'),
541 *product((1234, -1234), 'duioxX'),
542 *product((1234.5678901, -1234.5678901), 'duifegFEG'),
543 *product((float('inf'), -float('inf')), 'fegFEG'),
544 ]
545 width_precs = [
546 *product(('', '1', '30'), ('', '.', '.0', '.2')),
547 ('', '.40'),
548 ('30', '.40'),
549 ]
550 for value, suffix in testcases:
551 for width, prec in width_precs:
552 for r in range(len(flags) + 1):
553 for spec in combinations(flags, r):
554 fmt = '%' + ''.join(spec) + width + prec + suffix
555 with self.subTest(fmt=fmt, value=value):
556 s1 = fmt % value
557 s2 = eval(f'{fmt!r} % (x,)', {'x': value})
558 self.assertEqual(s2, s1, f'{fmt = }')
559
560 def test_format_misc(self):
561 def format(fmt, *values):
562 vars = [f'x{i+1}' for i in range(len(values))]
563 if len(vars) == 1:
564 args = '(' + vars[0] + ',)'
565 else:
566 args = '(' + ', '.join(vars) + ')'
567 return eval(f'{fmt!r} % {args}', dict(zip(vars, values)))
568
569 self.assertEqual(format('string'), 'string')
570 self.assertEqual(format('x = %s!', 1234), 'x = 1234!')
571 self.assertEqual(format('x = %d!', 1234), 'x = 1234!')
572 self.assertEqual(format('x = %x!', 1234), 'x = 4d2!')
573 self.assertEqual(format('x = %f!', 1234), 'x = 1234.000000!')
574 self.assertEqual(format('x = %s!', 1234.5678901), 'x = 1234.5678901!')
575 self.assertEqual(format('x = %f!', 1234.5678901), 'x = 1234.567890!')
576 self.assertEqual(format('x = %d!', 1234.5678901), 'x = 1234!')
577 self.assertEqual(format('x = %s%% %%%%', 1234), 'x = 1234% %%')
578 self.assertEqual(format('x = %s!', '%% %s'), 'x = %% %s!')
579 self.assertEqual(format('x = %s, y = %d', 12, 34), 'x = 12, y = 34')
580
581 @cpython_only
582 def test_format_errors(self):
583 with self.assertRaisesRegex(TypeError,
584 'not enough arguments for format string'):
585 eval("'%s' % ()")
586 with self.assertRaisesRegex(TypeError,
587 'not all arguments converted during string formatting'):
588 eval("'%s' % (x, y)", {'x': 1, 'y': 2})
589 with self.assertRaisesRegex(ValueError, 'incomplete format'):
590 eval("'%s%' % (x,)", {'x': 1234})
591 with self.assertRaisesRegex(ValueError, 'incomplete format'):
592 eval("'%s%%%' % (x,)", {'x': 1234})
593 with self.assertRaisesRegex(TypeError,
594 'not enough arguments for format string'):
595 eval("'%s%z' % (x,)", {'x': 1234})
596 with self.assertRaisesRegex(ValueError, 'unsupported format character'):
597 eval("'%s%z' % (x, 5)", {'x': 1234})
598 with self.assertRaisesRegex(TypeError, 'a real number is required, not str'):
599 eval("'%d' % (x,)", {'x': '1234'})
600 with self.assertRaisesRegex(TypeError, 'an integer is required, not float'):
601 eval("'%x' % (x,)", {'x': 1234.56})
602 with self.assertRaisesRegex(TypeError, 'an integer is required, not str'):
603 eval("'%x' % (x,)", {'x': '1234'})
604 with self.assertRaisesRegex(TypeError, 'must be real number, not str'):
605 eval("'%f' % (x,)", {'x': '1234'})
606 with self.assertRaisesRegex(TypeError,
607 'not enough arguments for format string'):
608 eval("'%s, %s' % (x, *y)", {'x': 1, 'y': []})
609 with self.assertRaisesRegex(TypeError,
610 'not all arguments converted during string formatting'):
611 eval("'%s, %s' % (x, *y)", {'x': 1, 'y': [2, 3]})
612
613 def test_static_swaps_unpack_two(self):
614 def f(a, b):
615 a, b = a, b
616 b, a = a, b
617 self.assertNotInBytecode(f, "SWAP")
618
619 def test_static_swaps_unpack_three(self):
620 def f(a, b, c):
621 a, b, c = a, b, c
622 a, c, b = a, b, c
623 b, a, c = a, b, c
624 b, c, a = a, b, c
625 c, a, b = a, b, c
626 c, b, a = a, b, c
627 self.assertNotInBytecode(f, "SWAP")
628
629 def test_static_swaps_match_mapping(self):
630 for a, b, c in product("_a", "_b", "_c"):
631 pattern = f"{{'a': {a}, 'b': {b}, 'c': {c}}}"
632 with self.subTest(pattern):
633 code = compile_pattern_with_fast_locals(pattern)
634 self.assertNotInBytecode(code, "SWAP")
635
636 def test_static_swaps_match_class(self):
637 forms = [
638 "C({}, {}, {})",
639 "C({}, {}, c={})",
640 "C({}, b={}, c={})",
641 "C(a={}, b={}, c={})"
642 ]
643 for a, b, c in product("_a", "_b", "_c"):
644 for form in forms:
645 pattern = form.format(a, b, c)
646 with self.subTest(pattern):
647 code = compile_pattern_with_fast_locals(pattern)
648 self.assertNotInBytecode(code, "SWAP")
649
650 @cpython_only
651 def test_static_swaps_match_sequence(self):
652 swaps = {"*_, b, c", "a, *_, c", "a, b, *_"}
653 forms = ["{}, {}, {}", "{}, {}, *{}", "{}, *{}, {}", "*{}, {}, {}"]
654 for a, b, c in product("_a", "_b", "_c"):
655 for form in forms:
656 pattern = form.format(a, b, c)
657 with self.subTest(pattern):
658 code = compile_pattern_with_fast_locals(pattern)
659 if pattern in swaps:
660 # If this fails... great! Remove this pattern from swaps
661 # to prevent regressing on any improvement:
662 self.assertInBytecode(code, "SWAP")
663 else:
664 self.assertNotInBytecode(code, "SWAP")
665
666
667 class TestBuglets(unittest.TestCase):
668
669 def test_bug_11510(self):
670 # folded constant set optimization was commingled with the tuple
671 # unpacking optimization which would fail if the set had duplicate
672 # elements so that the set length was unexpected
673 def f():
674 x, y = {1, 1}
675 return x, y
676 with self.assertRaises(ValueError):
677 f()
678
679 def test_bpo_42057(self):
680 for i in range(10):
681 try:
682 raise Exception
683 except Exception or Exception:
684 pass
685
686 def test_bpo_45773_pop_jump_if_true(self):
687 compile("while True or spam: pass", "<test>", "exec")
688
689 def test_bpo_45773_pop_jump_if_false(self):
690 compile("while True or not spam: pass", "<test>", "exec")
691
692
693 if __name__ == "__main__":
694 unittest.main()