Debian Codegraph @

Lib/test/test_compile.py

raw
1 import contextlib
2 import dis
3 import io
4 import itertools
5 import math
6 import opcode
7 import os
8 import unittest
9 import sys
10 import ast
11 import _ast
12 import tempfile
13 import types
14 import textwrap
15 import warnings
16 import _testinternalcapi
17
18 from test import support
19 from test.support import (script_helper, requires_debug_ranges, run_code,
20 requires_specialization, get_c_recursion_limit)
21 from test.support.bytecode_helper import instructions_with_positions
22 from test.support.os_helper import FakePath
23
24 class TestSpecifics(unittest.TestCase):
25
26 def compile_single(self, source):
27 compile(source, "<single>", "single")
28
29 def assertInvalidSingle(self, source):
30 self.assertRaises(SyntaxError, self.compile_single, source)
31
32 def test_no_ending_newline(self):
33 compile("hi", "<test>", "exec")
34 compile("hi\r", "<test>", "exec")
35
36 def test_empty(self):
37 compile("", "<test>", "exec")
38
39 def test_other_newlines(self):
40 compile("\r\n", "<test>", "exec")
41 compile("\r", "<test>", "exec")
42 compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
43 compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
44
45 def test_debug_assignment(self):
46 # catch assignments to __debug__
47 self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
48 import builtins
49 prev = builtins.__debug__
50 setattr(builtins, '__debug__', 'sure')
51 self.assertEqual(__debug__, prev)
52 setattr(builtins, '__debug__', prev)
53
54 def test_argument_handling(self):
55 # detect duplicate positional and keyword arguments
56 self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
57 self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
58 self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
59 self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
60 self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
61 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
62
63 def test_syntax_error(self):
64 self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
65
66 def test_none_keyword_arg(self):
67 self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
68
69 def test_duplicate_global_local(self):
70 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
71
72 def test_exec_with_general_mapping_for_locals(self):
73
74 class M:
75 "Test mapping interface versus possible calls from eval()."
76 def __getitem__(self, key):
77 if key == 'a':
78 return 12
79 raise KeyError
80 def __setitem__(self, key, value):
81 self.results = (key, value)
82 def keys(self):
83 return list('xyz')
84
85 m = M()
86 g = globals()
87 exec('z = a', g, m)
88 self.assertEqual(m.results, ('z', 12))
89 try:
90 exec('z = b', g, m)
91 except NameError:
92 pass
93 else:
94 self.fail('Did not detect a KeyError')
95 exec('z = dir()', g, m)
96 self.assertEqual(m.results, ('z', list('xyz')))
97 exec('z = globals()', g, m)
98 self.assertEqual(m.results, ('z', g))
99 exec('z = locals()', g, m)
100 self.assertEqual(m.results, ('z', m))
101 self.assertRaises(TypeError, exec, 'z = b', m)
102
103 class A:
104 "Non-mapping"
105 pass
106 m = A()
107 self.assertRaises(TypeError, exec, 'z = a', g, m)
108
109 # Verify that dict subclasses work as well
110 class D(dict):
111 def __getitem__(self, key):
112 if key == 'a':
113 return 12
114 return dict.__getitem__(self, key)
115 d = D()
116 exec('z = a', g, d)
117 self.assertEqual(d['z'], 12)
118
119 @unittest.skipIf(support.is_wasi, "exhausts limited stack on WASI")
120 def test_extended_arg(self):
121 repeat = int(get_c_recursion_limit() * 0.9)
122 longexpr = 'x = x or ' + '-x' * repeat
123 g = {}
124 code = textwrap.dedent('''
125 def f(x):
126 %s
127 %s
128 %s
129 %s
130 %s
131 %s
132 %s
133 %s
134 %s
135 %s
136 # the expressions above have no effect, x == argument
137 while x:
138 x -= 1
139 # EXTENDED_ARG/JUMP_ABSOLUTE here
140 return x
141 ''' % ((longexpr,)*10))
142 exec(code, g)
143 self.assertEqual(g['f'](5), 0)
144
145 def test_argument_order(self):
146 self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
147
148 def test_float_literals(self):
149 # testing bad float literals
150 self.assertRaises(SyntaxError, eval, "2e")
151 self.assertRaises(SyntaxError, eval, "2.0e+")
152 self.assertRaises(SyntaxError, eval, "1e-")
153 self.assertRaises(SyntaxError, eval, "3-4e/21")
154
155 def test_indentation(self):
156 # testing compile() of indented block w/o trailing newline"
157 s = textwrap.dedent("""
158 if 1:
159 if 2:
160 pass
161 """)
162 compile(s, "<string>", "exec")
163
164 # This test is probably specific to CPython and may not generalize
165 # to other implementations. We are trying to ensure that when
166 # the first line of code starts after 256, correct line numbers
167 # in tracebacks are still produced.
168 def test_leading_newlines(self):
169 s256 = "".join(["\n"] * 256 + ["spam"])
170 co = compile(s256, 'fn', 'exec')
171 self.assertEqual(co.co_firstlineno, 1)
172 lines = [line for _, _, line in co.co_lines()]
173 self.assertEqual(lines, [0, 257])
174
175 def test_literals_with_leading_zeroes(self):
176 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
177 "080000000000000", "000000000000009", "000000000000008",
178 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
179 "0b101j", "0o153j", "0b100e1", "0o777e1", "0777",
180 "000777", "000000000000007"]:
181 self.assertRaises(SyntaxError, eval, arg)
182
183 self.assertEqual(eval("0xff"), 255)
184 self.assertEqual(eval("0777."), 777)
185 self.assertEqual(eval("0777.0"), 777)
186 self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
187 self.assertEqual(eval("0777e1"), 7770)
188 self.assertEqual(eval("0e0"), 0)
189 self.assertEqual(eval("0000e-012"), 0)
190 self.assertEqual(eval("09.5"), 9.5)
191 self.assertEqual(eval("0777j"), 777j)
192 self.assertEqual(eval("000"), 0)
193 self.assertEqual(eval("00j"), 0j)
194 self.assertEqual(eval("00.0"), 0)
195 self.assertEqual(eval("0e3"), 0)
196 self.assertEqual(eval("090000000000000."), 90000000000000.)
197 self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
198 self.assertEqual(eval("090000000000000e0"), 90000000000000.)
199 self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
200 self.assertEqual(eval("090000000000000j"), 90000000000000j)
201 self.assertEqual(eval("000000000000008."), 8.)
202 self.assertEqual(eval("000000000000009."), 9.)
203 self.assertEqual(eval("0b101010"), 42)
204 self.assertEqual(eval("-0b000000000010"), -2)
205 self.assertEqual(eval("0o777"), 511)
206 self.assertEqual(eval("-0o0000010"), -8)
207
208 def test_int_literals_too_long(self):
209 n = 3000
210 source = f"a = 1\nb = 2\nc = {'3'*n}\nd = 4"
211 with support.adjust_int_max_str_digits(n):
212 compile(source, "<long_int_pass>", "exec") # no errors.
213 with support.adjust_int_max_str_digits(n-1):
214 with self.assertRaises(SyntaxError) as err_ctx:
215 compile(source, "<long_int_fail>", "exec")
216 exc = err_ctx.exception
217 self.assertEqual(exc.lineno, 3)
218 self.assertIn('Exceeds the limit ', str(exc))
219 self.assertIn(' Consider hexadecimal ', str(exc))
220
221 def test_unary_minus(self):
222 # Verify treatment of unary minus on negative numbers SF bug #660455
223 if sys.maxsize == 2147483647:
224 # 32-bit machine
225 all_one_bits = '0xffffffff'
226 self.assertEqual(eval(all_one_bits), 4294967295)
227 self.assertEqual(eval("-" + all_one_bits), -4294967295)
228 elif sys.maxsize == 9223372036854775807:
229 # 64-bit machine
230 all_one_bits = '0xffffffffffffffff'
231 self.assertEqual(eval(all_one_bits), 18446744073709551615)
232 self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
233 else:
234 self.fail("How many bits *does* this machine have???")
235 # Verify treatment of constant folding on -(sys.maxsize+1)
236 # i.e. -2147483648 on 32 bit platforms. Should return int.
237 self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
238 self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
239
240 if sys.maxsize == 9223372036854775807:
241 def test_32_63_bit_values(self):
242 a = +4294967296 # 1 << 32
243 b = -4294967296 # 1 << 32
244 c = +281474976710656 # 1 << 48
245 d = -281474976710656 # 1 << 48
246 e = +4611686018427387904 # 1 << 62
247 f = -4611686018427387904 # 1 << 62
248 g = +9223372036854775807 # 1 << 63 - 1
249 h = -9223372036854775807 # 1 << 63 - 1
250
251 for variable in self.test_32_63_bit_values.__code__.co_consts:
252 if variable is not None:
253 self.assertIsInstance(variable, int)
254
255 def test_sequence_unpacking_error(self):
256 # Verify sequence packing/unpacking with "or". SF bug #757818
257 i,j = (1, -1) or (-1, 1)
258 self.assertEqual(i, 1)
259 self.assertEqual(j, -1)
260
261 def test_none_assignment(self):
262 stmts = [
263 'None = 0',
264 'None += 0',
265 '__builtins__.None = 0',
266 'def None(): pass',
267 'class None: pass',
268 '(a, None) = 0, 0',
269 'for None in range(10): pass',
270 'def f(None): pass',
271 'import None',
272 'import x as None',
273 'from x import None',
274 'from x import y as None'
275 ]
276 for stmt in stmts:
277 stmt += "\n"
278 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
279 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
280
281 def test_import(self):
282 succeed = [
283 'import sys',
284 'import os, sys',
285 'import os as bar',
286 'import os.path as bar',
287 'from __future__ import nested_scopes, generators',
288 'from __future__ import (nested_scopes,\ngenerators)',
289 'from __future__ import (nested_scopes,\ngenerators,)',
290 'from sys import stdin, stderr, stdout',
291 'from sys import (stdin, stderr,\nstdout)',
292 'from sys import (stdin, stderr,\nstdout,)',
293 'from sys import (stdin\n, stderr, stdout)',
294 'from sys import (stdin\n, stderr, stdout,)',
295 'from sys import stdin as si, stdout as so, stderr as se',
296 'from sys import (stdin as si, stdout as so, stderr as se)',
297 'from sys import (stdin as si, stdout as so, stderr as se,)',
298 ]
299 fail = [
300 'import (os, sys)',
301 'import (os), (sys)',
302 'import ((os), (sys))',
303 'import (sys',
304 'import sys)',
305 'import (os,)',
306 'import os As bar',
307 'import os.path a bar',
308 'from sys import stdin As stdout',
309 'from sys import stdin a stdout',
310 'from (sys) import stdin',
311 'from __future__ import (nested_scopes',
312 'from __future__ import nested_scopes)',
313 'from __future__ import nested_scopes,\ngenerators',
314 'from sys import (stdin',
315 'from sys import stdin)',
316 'from sys import stdin, stdout,\nstderr',
317 'from sys import stdin si',
318 'from sys import stdin,',
319 'from sys import (*)',
320 'from sys import (stdin,, stdout, stderr)',
321 'from sys import (stdin, stdout),',
322 ]
323 for stmt in succeed:
324 compile(stmt, 'tmp', 'exec')
325 for stmt in fail:
326 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
327
328 def test_for_distinct_code_objects(self):
329 # SF bug 1048870
330 def f():
331 f1 = lambda x=1: x
332 f2 = lambda x=2: x
333 return f1, f2
334 f1, f2 = f()
335 self.assertNotEqual(id(f1.__code__), id(f2.__code__))
336
337 def test_lambda_doc(self):
338 l = lambda: "foo"
339 self.assertIsNone(l.__doc__)
340
341 def test_encoding(self):
342 code = b'# -*- coding: badencoding -*-\npass\n'
343 self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec')
344 code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n'
345 compile(code, 'tmp', 'exec')
346 self.assertEqual(eval(code), '\xc2\xa4')
347 code = '"\xc2\xa4"\n'
348 self.assertEqual(eval(code), '\xc2\xa4')
349 code = b'"\xc2\xa4"\n'
350 self.assertEqual(eval(code), '\xa4')
351 code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n'
352 self.assertEqual(eval(code), '\xc2\xa4')
353 code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n'
354 self.assertEqual(eval(code), '\xa4')
355 code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n'
356 self.assertEqual(eval(code), '\xc2\u20ac')
357 code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
358 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4')
359 code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
360 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4')
361
362 def test_subscripts(self):
363 # SF bug 1448804
364 # Class to make testing subscript results easy
365 class str_map(object):
366 def __init__(self):
367 self.data = {}
368 def __getitem__(self, key):
369 return self.data[str(key)]
370 def __setitem__(self, key, value):
371 self.data[str(key)] = value
372 def __delitem__(self, key):
373 del self.data[str(key)]
374 def __contains__(self, key):
375 return str(key) in self.data
376 d = str_map()
377 # Index
378 d[1] = 1
379 self.assertEqual(d[1], 1)
380 d[1] += 1
381 self.assertEqual(d[1], 2)
382 del d[1]
383 self.assertNotIn(1, d)
384 # Tuple of indices
385 d[1, 1] = 1
386 self.assertEqual(d[1, 1], 1)
387 d[1, 1] += 1
388 self.assertEqual(d[1, 1], 2)
389 del d[1, 1]
390 self.assertNotIn((1, 1), d)
391 # Simple slice
392 d[1:2] = 1
393 self.assertEqual(d[1:2], 1)
394 d[1:2] += 1
395 self.assertEqual(d[1:2], 2)
396 del d[1:2]
397 self.assertNotIn(slice(1, 2), d)
398 # Tuple of simple slices
399 d[1:2, 1:2] = 1
400 self.assertEqual(d[1:2, 1:2], 1)
401 d[1:2, 1:2] += 1
402 self.assertEqual(d[1:2, 1:2], 2)
403 del d[1:2, 1:2]
404 self.assertNotIn((slice(1, 2), slice(1, 2)), d)
405 # Extended slice
406 d[1:2:3] = 1
407 self.assertEqual(d[1:2:3], 1)
408 d[1:2:3] += 1
409 self.assertEqual(d[1:2:3], 2)
410 del d[1:2:3]
411 self.assertNotIn(slice(1, 2, 3), d)
412 # Tuple of extended slices
413 d[1:2:3, 1:2:3] = 1
414 self.assertEqual(d[1:2:3, 1:2:3], 1)
415 d[1:2:3, 1:2:3] += 1
416 self.assertEqual(d[1:2:3, 1:2:3], 2)
417 del d[1:2:3, 1:2:3]
418 self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
419 # Ellipsis
420 d[...] = 1
421 self.assertEqual(d[...], 1)
422 d[...] += 1
423 self.assertEqual(d[...], 2)
424 del d[...]
425 self.assertNotIn(Ellipsis, d)
426 # Tuple of Ellipses
427 d[..., ...] = 1
428 self.assertEqual(d[..., ...], 1)
429 d[..., ...] += 1
430 self.assertEqual(d[..., ...], 2)
431 del d[..., ...]
432 self.assertNotIn((Ellipsis, Ellipsis), d)
433
434 def test_annotation_limit(self):
435 # more than 255 annotations, should compile ok
436 s = "def f(%s): pass"
437 s %= ', '.join('a%d:%d' % (i,i) for i in range(300))
438 compile(s, '?', 'exec')
439
440 def test_mangling(self):
441 class A:
442 def f():
443 __mangled = 1
444 __not_mangled__ = 2
445 import __mangled_mod
446 import __package__.module
447
448 self.assertIn("_A__mangled", A.f.__code__.co_varnames)
449 self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
450 self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
451 self.assertIn("__package__", A.f.__code__.co_varnames)
452
453 def test_condition_expression_with_dead_blocks_compiles(self):
454 # See gh-113054
455 compile('if (5 if 5 else T): 0', '<eval>', 'exec')
456
457 def test_condition_expression_with_redundant_comparisons_compiles(self):
458 # See gh-113054, gh-114083
459 exprs = [
460 'if 9<9<9and 9or 9:9',
461 'if 9<9<9and 9or 9or 9:9',
462 'if 9<9<9and 9or 9or 9or 9:9',
463 'if 9<9<9and 9or 9or 9or 9or 9:9',
464 ]
465 for expr in exprs:
466 with self.subTest(expr=expr):
467 with self.assertWarns(SyntaxWarning):
468 compile(expr, '<eval>', 'exec')
469
470 def test_dead_code_with_except_handler_compiles(self):
471 compile(textwrap.dedent("""
472 if None:
473 with CM:
474 x = 1
475 else:
476 x = 2
477 """), '<eval>', 'exec')
478
479 def test_try_except_in_while_with_chained_condition_compiles(self):
480 # see gh-124871
481 compile(textwrap.dedent("""
482 name_1, name_2, name_3 = 1, 2, 3
483 while name_3 <= name_2 > name_1:
484 try:
485 raise
486 except:
487 pass
488 finally:
489 pass
490 """), '<eval>', 'exec')
491
492 def test_compile_invalid_namedexpr(self):
493 # gh-109351
494 m = ast.Module(
495 body=[
496 ast.Expr(
497 value=ast.ListComp(
498 elt=ast.NamedExpr(
499 target=ast.Constant(value=1),
500 value=ast.Constant(value=3),
501 ),
502 generators=[
503 ast.comprehension(
504 target=ast.Name(id="x", ctx=ast.Store()),
505 iter=ast.Name(id="y", ctx=ast.Load()),
506 ifs=[],
507 is_async=0,
508 )
509 ],
510 )
511 )
512 ],
513 type_ignores=[],
514 )
515
516 with self.assertRaisesRegex(TypeError, "NamedExpr target must be a Name"):
517 compile(ast.fix_missing_locations(m), "<file>", "exec")
518
519 def test_compile_redundant_jumps_and_nops_after_moving_cold_blocks(self):
520 # See gh-120367
521 code=textwrap.dedent("""
522 try:
523 pass
524 except:
525 pass
526 else:
527 match name_2:
528 case b'':
529 pass
530 finally:
531 something
532 """)
533
534 tree = ast.parse(code)
535
536 # make all instruction locations the same to create redundancies
537 for node in ast.walk(tree):
538 if hasattr(node,"lineno"):
539 del node.lineno
540 del node.end_lineno
541 del node.col_offset
542 del node.end_col_offset
543
544 compile(ast.fix_missing_locations(tree), "<file>", "exec")
545
546 def test_compile_redundant_jump_after_convert_pseudo_ops(self):
547 # See gh-120367
548 code=textwrap.dedent("""
549 if name_2:
550 pass
551 else:
552 try:
553 pass
554 except:
555 pass
556 ~name_5
557 """)
558
559 tree = ast.parse(code)
560
561 # make all instruction locations the same to create redundancies
562 for node in ast.walk(tree):
563 if hasattr(node,"lineno"):
564 del node.lineno
565 del node.end_lineno
566 del node.col_offset
567 del node.end_col_offset
568
569 compile(ast.fix_missing_locations(tree), "<file>", "exec")
570
571 def test_compile_ast(self):
572 fname = __file__
573 if fname.lower().endswith('pyc'):
574 fname = fname[:-1]
575 with open(fname, encoding='utf-8') as f:
576 fcontents = f.read()
577 sample_code = [
578 ['<assign>', 'x = 5'],
579 ['<ifblock>', """if True:\n pass\n"""],
580 ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
581 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
582 [fname, fcontents],
583 ]
584
585 for fname, code in sample_code:
586 co1 = compile(code, '%s1' % fname, 'exec')
587 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
588 self.assertTrue(type(ast) == _ast.Module)
589 co2 = compile(ast, '%s3' % fname, 'exec')
590 self.assertEqual(co1, co2)
591 # the code object's filename comes from the second compilation step
592 self.assertEqual(co2.co_filename, '%s3' % fname)
593
594 # raise exception when node type doesn't match with compile mode
595 co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
596 self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
597
598 # raise exception when node type is no start node
599 self.assertRaises(TypeError, compile, _ast.If(test=_ast.Name(id='x', ctx=_ast.Load())), '<ast>', 'exec')
600
601 # raise exception when node has invalid children
602 ast = _ast.Module()
603 ast.body = [_ast.BoolOp(op=_ast.Or())]
604 self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
605
606 def test_compile_invalid_typealias(self):
607 # gh-109341
608 m = ast.Module(
609 body=[
610 ast.TypeAlias(
611 name=ast.Subscript(
612 value=ast.Name(id="foo", ctx=ast.Load()),
613 slice=ast.Constant(value="x"),
614 ctx=ast.Store(),
615 ),
616 type_params=[],
617 value=ast.Name(id="Callable", ctx=ast.Load()),
618 )
619 ],
620 type_ignores=[],
621 )
622
623 with self.assertRaisesRegex(TypeError, "TypeAlias with non-Name name"):
624 compile(ast.fix_missing_locations(m), "<file>", "exec")
625
626 def test_dict_evaluation_order(self):
627 i = 0
628
629 def f():
630 nonlocal i
631 i += 1
632 return i
633
634 d = {f(): f(), f(): f()}
635 self.assertEqual(d, {1: 2, 3: 4})
636
637 def test_compile_filename(self):
638 for filename in 'file.py', b'file.py':
639 code = compile('pass', filename, 'exec')
640 self.assertEqual(code.co_filename, 'file.py')
641 for filename in bytearray(b'file.py'), memoryview(b'file.py'):
642 with self.assertRaises(TypeError):
643 compile('pass', filename, 'exec')
644 self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
645
646 def test_compile_filename_refleak(self):
647 # Regression tests for reference leak in PyUnicode_FSDecoder.
648 # See https://github.com/python/cpython/issues/139748.
649 mortal_str = 'this is a mortal string'
650 # check error path when 'mode' AC conversion failed
651 self.assertRaises(TypeError, compile, b'', mortal_str, mode=1234)
652 # check error path when 'optimize' AC conversion failed
653 self.assertRaises(OverflowError, compile, b'', mortal_str,
654 'exec', optimize=1 << 1000)
655 # check error path when 'dont_inherit' AC conversion failed
656 class EvilBool:
657 def __bool__(self): raise ValueError
658 self.assertRaises(ValueError, compile, b'', mortal_str,
659 'exec', dont_inherit=EvilBool())
660
661 @support.cpython_only
662 def test_same_filename_used(self):
663 s = """def f(): pass\ndef g(): pass"""
664 c = compile(s, "myfile", "exec")
665 for obj in c.co_consts:
666 if isinstance(obj, types.CodeType):
667 self.assertIs(obj.co_filename, c.co_filename)
668
669 def test_single_statement(self):
670 self.compile_single("1 + 2")
671 self.compile_single("\n1 + 2")
672 self.compile_single("1 + 2\n")
673 self.compile_single("1 + 2\n\n")
674 self.compile_single("1 + 2\t\t\n")
675 self.compile_single("1 + 2\t\t\n ")
676 self.compile_single("1 + 2 # one plus two")
677 self.compile_single("1; 2")
678 self.compile_single("import sys; sys")
679 self.compile_single("def f():\n pass")
680 self.compile_single("while False:\n pass")
681 self.compile_single("if x:\n f(x)")
682 self.compile_single("if x:\n f(x)\nelse:\n g(x)")
683 self.compile_single("class T:\n pass")
684 self.compile_single("c = '''\na=1\nb=2\nc=3\n'''")
685
686 def test_bad_single_statement(self):
687 self.assertInvalidSingle('1\n2')
688 self.assertInvalidSingle('def f(): pass')
689 self.assertInvalidSingle('a = 13\nb = 187')
690 self.assertInvalidSingle('del x\ndel y')
691 self.assertInvalidSingle('f()\ng()')
692 self.assertInvalidSingle('f()\n# blah\nblah()')
693 self.assertInvalidSingle('f()\nxy # blah\nblah()')
694 self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
695 self.assertInvalidSingle("c = '''\nd=1\n'''\na = 1\n\nb = 2\n")
696
697 def test_particularly_evil_undecodable(self):
698 # Issue 24022
699 src = b'0000\x00\n00000000000\n\x00\n\x9e\n'
700 with tempfile.TemporaryDirectory() as tmpd:
701 fn = os.path.join(tmpd, "bad.py")
702 with open(fn, "wb") as fp:
703 fp.write(src)
704 res = script_helper.run_python_until_end(fn)[0]
705 self.assertIn(b"source code cannot contain null bytes", res.err)
706
707 def test_yet_more_evil_still_undecodable(self):
708 # Issue #25388
709 src = b"#\x00\n#\xfd\n"
710 with tempfile.TemporaryDirectory() as tmpd:
711 fn = os.path.join(tmpd, "bad.py")
712 with open(fn, "wb") as fp:
713 fp.write(src)
714 res = script_helper.run_python_until_end(fn)[0]
715 self.assertIn(b"source code cannot contain null bytes", res.err)
716
717 @support.cpython_only
718 @unittest.skipIf(support.is_wasi, "exhausts limited stack on WASI")
719 def test_compiler_recursion_limit(self):
720 # Expected limit is Py_C_RECURSION_LIMIT
721 limit = get_c_recursion_limit()
722 fail_depth = limit + 1
723 crash_depth = limit * 100
724 success_depth = int(limit * 0.8)
725
726 def check_limit(prefix, repeated, mode="single"):
727 expect_ok = prefix + repeated * success_depth
728 compile(expect_ok, '<test>', mode)
729 for depth in (fail_depth, crash_depth):
730 broken = prefix + repeated * depth
731 details = "Compiling ({!r} + {!r} * {})".format(
732 prefix, repeated, depth)
733 with self.assertRaises(RecursionError, msg=details):
734 compile(broken, '<test>', mode)
735
736 check_limit("a", "()")
737 check_limit("a", ".b")
738 check_limit("a", "[0]")
739 check_limit("a", "*a")
740 # XXX Crashes in the parser.
741 # check_limit("a", " if a else a")
742 # check_limit("if a: pass", "\nelif a: pass", mode="exec")
743
744 def test_null_terminated(self):
745 # The source code is null-terminated internally, but bytes-like
746 # objects are accepted, which could be not terminated.
747 with self.assertRaisesRegex(SyntaxError, "cannot contain null"):
748 compile("123\x00", "<dummy>", "eval")
749 with self.assertRaisesRegex(SyntaxError, "cannot contain null"):
750 compile(memoryview(b"123\x00"), "<dummy>", "eval")
751 code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
752 self.assertEqual(eval(code), 23)
753 code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval")
754 self.assertEqual(eval(code), 23)
755 code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval")
756 self.assertEqual(eval(code), 23)
757
758 # Also test when eval() and exec() do the compilation step
759 self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23)
760 namespace = dict()
761 exec(memoryview(b"ax = 123")[1:-1], namespace)
762 self.assertEqual(namespace['x'], 12)
763
764 def check_constant(self, func, expected):
765 for const in func.__code__.co_consts:
766 if repr(const) == repr(expected):
767 break
768 else:
769 self.fail("unable to find constant %r in %r"
770 % (expected, func.__code__.co_consts))
771
772 # Merging equal constants is not a strict requirement for the Python
773 # semantics, it's a more an implementation detail.
774 @support.cpython_only
775 def test_merge_constants(self):
776 # Issue #25843: compile() must merge constants which are equal
777 # and have the same type.
778
779 def check_same_constant(const):
780 ns = {}
781 code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
782 exec(code, ns)
783 f1 = ns['f1']
784 f2 = ns['f2']
785 self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
786 self.check_constant(f1, const)
787 self.assertEqual(repr(f1()), repr(const))
788
789 check_same_constant(None)
790 check_same_constant(0)
791 check_same_constant(0.0)
792 check_same_constant(b'abc')
793 check_same_constant('abc')
794
795 # Note: "lambda: ..." emits "LOAD_CONST Ellipsis",
796 # whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis"
797 f1, f2 = lambda: ..., lambda: ...
798 self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
799 self.check_constant(f1, Ellipsis)
800 self.assertEqual(repr(f1()), repr(Ellipsis))
801
802 # Merge constants in tuple or frozenset
803 f1, f2 = lambda: "not a name", lambda: ("not a name",)
804 f3 = lambda x: x in {("not a name",)}
805 self.assertIs(f1.__code__.co_consts[1],
806 f2.__code__.co_consts[1][0])
807 self.assertIs(next(iter(f3.__code__.co_consts[1])),
808 f2.__code__.co_consts[1])
809
810 # {0} is converted to a constant frozenset({0}) by the peephole
811 # optimizer
812 f1, f2 = lambda x: x in {0}, lambda x: x in {0}
813 self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
814 self.check_constant(f1, frozenset({0}))
815 self.assertTrue(f1(0))
816
817 # Merging equal co_linetable is not a strict requirement
818 # for the Python semantics, it's a more an implementation detail.
819 @support.cpython_only
820 def test_merge_code_attrs(self):
821 # See https://bugs.python.org/issue42217
822 f1 = lambda x: x.y.z
823 f2 = lambda a: a.b.c
824
825 self.assertIs(f1.__code__.co_linetable, f2.__code__.co_linetable)
826
827 @support.cpython_only
828 def test_remove_unused_consts(self):
829 def f():
830 "docstring"
831 if True:
832 return "used"
833 else:
834 return "unused"
835
836 self.assertEqual(f.__code__.co_consts,
837 (f.__doc__, "used"))
838
839 @support.cpython_only
840 def test_remove_unused_consts_no_docstring(self):
841 # the first item (None for no docstring in this case) is
842 # always retained.
843 def f():
844 if True:
845 return "used"
846 else:
847 return "unused"
848
849 self.assertEqual(f.__code__.co_consts,
850 (None, "used"))
851
852 @support.cpython_only
853 def test_remove_unused_consts_extended_args(self):
854 N = 1000
855 code = ["def f():\n"]
856 code.append("\ts = ''\n")
857 code.append("\tfor i in range(1):\n")
858 for i in range(N):
859 code.append(f"\t\tif True: s += 't{i}'\n")
860 code.append(f"\t\tif False: s += 'f{i}'\n")
861 code.append("\treturn s\n")
862
863 code = "".join(code)
864 g = {}
865 eval(compile(code, "file.py", "exec"), g)
866 exec(code, g)
867 f = g['f']
868 expected = tuple([None, '', 1] + [f't{i}' for i in range(N)])
869 self.assertEqual(f.__code__.co_consts, expected)
870 expected = "".join(expected[3:])
871 self.assertEqual(expected, f())
872
873 # Stripping unused constants is not a strict requirement for the
874 # Python semantics, it's a more an implementation detail.
875 @support.cpython_only
876 def test_strip_unused_None(self):
877 # Python 3.10rc1 appended None to co_consts when None is not used
878 # at all. See bpo-45056.
879 def f1():
880 "docstring"
881 return 42
882 self.assertEqual(f1.__code__.co_consts, (f1.__doc__, 42))
883
884 # This is a regression test for a CPython specific peephole optimizer
885 # implementation bug present in a few releases. It's assertion verifies
886 # that peephole optimization was actually done though that isn't an
887 # indication of the bugs presence or not (crashing is).
888 @support.cpython_only
889 def test_peephole_opt_unreachable_code_array_access_in_bounds(self):
890 """Regression test for issue35193 when run under clang msan."""
891 def unused_code_at_end():
892 return 3
893 raise RuntimeError("unreachable")
894 # The above function definition will trigger the out of bounds
895 # bug in the peephole optimizer as it scans opcodes past the
896 # RETURN_VALUE opcode. This does not always crash an interpreter.
897 # When you build with the clang memory sanitizer it reliably aborts.
898 self.assertEqual(
899 'RETURN_CONST',
900 list(dis.get_instructions(unused_code_at_end))[-1].opname)
901
902 @support.cpython_only
903 def test_docstring(self):
904 src = textwrap.dedent("""
905 def with_docstring():
906 "docstring"
907
908 def with_fstring():
909 f"not docstring"
910
911 def with_const_expression():
912 "also" + " not docstring"
913 """)
914
915 for opt in [0, 1, 2]:
916 with self.subTest(opt=opt):
917 code = compile(src, "<test>", "exec", optimize=opt)
918 ns = {}
919 exec(code, ns)
920
921 if opt < 2:
922 self.assertEqual(ns['with_docstring'].__doc__, "docstring")
923 else:
924 self.assertIsNone(ns['with_docstring'].__doc__)
925 self.assertIsNone(ns['with_fstring'].__doc__)
926 self.assertIsNone(ns['with_const_expression'].__doc__)
927
928 @support.cpython_only
929 def test_docstring_omitted(self):
930 # See gh-115347
931 src = textwrap.dedent("""
932 def f():
933 "docstring1"
934 def h():
935 "docstring2"
936 return 42
937
938 class C:
939 "docstring3"
940 pass
941
942 return h
943 """)
944 for opt in [-1, 0, 1, 2]:
945 with self.subTest(opt=opt):
946 code = compile(src, "<test>", "exec", optimize=opt)
947 output = io.StringIO()
948 with contextlib.redirect_stdout(output):
949 dis.dis(code)
950 self.assertNotIn('NOP' , output.getvalue())
951
952 def test_dont_merge_constants(self):
953 # Issue #25843: compile() must not merge constants which are equal
954 # but have a different type.
955
956 def check_different_constants(const1, const2):
957 ns = {}
958 exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
959 f1 = ns['f1']
960 f2 = ns['f2']
961 self.assertIsNot(f1.__code__, f2.__code__)
962 self.assertNotEqual(f1.__code__, f2.__code__)
963 self.check_constant(f1, const1)
964 self.check_constant(f2, const2)
965 self.assertEqual(repr(f1()), repr(const1))
966 self.assertEqual(repr(f2()), repr(const2))
967
968 check_different_constants(0, 0.0)
969 check_different_constants(+0.0, -0.0)
970 check_different_constants((0,), (0.0,))
971 check_different_constants('a', b'a')
972 check_different_constants(('a',), (b'a',))
973
974 # check_different_constants() cannot be used because repr(-0j) is
975 # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
976 f1, f2 = lambda: +0.0j, lambda: -0.0j
977 self.assertIsNot(f1.__code__, f2.__code__)
978 self.check_constant(f1, +0.0j)
979 self.check_constant(f2, -0.0j)
980 self.assertEqual(repr(f1()), repr(+0.0j))
981 self.assertEqual(repr(f2()), repr(-0.0j))
982
983 # {0} is converted to a constant frozenset({0}) by the peephole
984 # optimizer
985 f1, f2 = lambda x: x in {0}, lambda x: x in {0.0}
986 self.assertIsNot(f1.__code__, f2.__code__)
987 self.check_constant(f1, frozenset({0}))
988 self.check_constant(f2, frozenset({0.0}))
989 self.assertTrue(f1(0))
990 self.assertTrue(f2(0.0))
991
992 def test_path_like_objects(self):
993 # An implicit test for PyUnicode_FSDecoder().
994 compile("42", FakePath("test_compile_pathlike"), "single")
995
996 # bpo-31113: Stack overflow when compile a long sequence of
997 # complex statements.
998 @support.requires_resource('cpu')
999 def test_stack_overflow(self):
1000 # Android test devices have less memory.
1001 size = 100_000 if sys.platform == "android" else 200_000
1002 compile("if a: b\n" * size, "<dummy>", "exec")
1003
1004 # Multiple users rely on the fact that CPython does not generate
1005 # bytecode for dead code blocks. See bpo-37500 for more context.
1006 @support.cpython_only
1007 def test_dead_blocks_do_not_generate_bytecode(self):
1008 def unused_block_if():
1009 if 0:
1010 return 42
1011
1012 def unused_block_while():
1013 while 0:
1014 return 42
1015
1016 def unused_block_if_else():
1017 if 1:
1018 return None
1019 else:
1020 return 42
1021
1022 def unused_block_while_else():
1023 while 1:
1024 return None
1025 else:
1026 return 42
1027
1028 funcs = [unused_block_if, unused_block_while,
1029 unused_block_if_else, unused_block_while_else]
1030
1031 for func in funcs:
1032 opcodes = list(dis.get_instructions(func))
1033 self.assertLessEqual(len(opcodes), 3)
1034 self.assertEqual('RETURN_CONST', opcodes[-1].opname)
1035 self.assertEqual(None, opcodes[-1].argval)
1036
1037 def test_false_while_loop(self):
1038 def break_in_while():
1039 while False:
1040 break
1041
1042 def continue_in_while():
1043 while False:
1044 continue
1045
1046 funcs = [break_in_while, continue_in_while]
1047
1048 # Check that we did not raise but we also don't generate bytecode
1049 for func in funcs:
1050 opcodes = list(dis.get_instructions(func))
1051 self.assertEqual(2, len(opcodes))
1052 self.assertEqual('RETURN_CONST', opcodes[1].opname)
1053 self.assertEqual(None, opcodes[1].argval)
1054
1055 def test_consts_in_conditionals(self):
1056 def and_true(x):
1057 return True and x
1058
1059 def and_false(x):
1060 return False and x
1061
1062 def or_true(x):
1063 return True or x
1064
1065 def or_false(x):
1066 return False or x
1067
1068 funcs = [and_true, and_false, or_true, or_false]
1069
1070 # Check that condition is removed.
1071 for func in funcs:
1072 with self.subTest(func=func):
1073 opcodes = list(dis.get_instructions(func))
1074 self.assertLessEqual(len(opcodes), 3)
1075 self.assertIn('LOAD_', opcodes[-2].opname)
1076 self.assertEqual('RETURN_VALUE', opcodes[-1].opname)
1077
1078 def test_imported_load_method(self):
1079 sources = [
1080 """\
1081 import os
1082 def foo():
1083 return os.uname()
1084 """,
1085 """\
1086 import os as operating_system
1087 def foo():
1088 return operating_system.uname()
1089 """,
1090 """\
1091 from os import path
1092 def foo(x):
1093 return path.join(x)
1094 """,
1095 """\
1096 from os import path as os_path
1097 def foo(x):
1098 return os_path.join(x)
1099 """
1100 ]
1101 for source in sources:
1102 namespace = {}
1103 exec(textwrap.dedent(source), namespace)
1104 func = namespace['foo']
1105 with self.subTest(func=func.__name__):
1106 opcodes = list(dis.get_instructions(func))
1107 instructions = [opcode.opname for opcode in opcodes]
1108 self.assertNotIn('LOAD_METHOD', instructions)
1109 self.assertIn('LOAD_ATTR', instructions)
1110 self.assertIn('CALL', instructions)
1111
1112 def test_lineno_procedure_call(self):
1113 def call():
1114 (
1115 print()
1116 )
1117 line1 = call.__code__.co_firstlineno + 1
1118 assert line1 not in [line for (_, _, line) in call.__code__.co_lines()]
1119
1120 def test_lineno_after_implicit_return(self):
1121 TRUE = True
1122 # Don't use constant True or False, as compiler will remove test
1123 def if1(x):
1124 x()
1125 if TRUE:
1126 pass
1127 def if2(x):
1128 x()
1129 if TRUE:
1130 pass
1131 else:
1132 pass
1133 def if3(x):
1134 x()
1135 if TRUE:
1136 pass
1137 else:
1138 return None
1139 def if4(x):
1140 x()
1141 if not TRUE:
1142 pass
1143 funcs = [ if1, if2, if3, if4]
1144 lastlines = [ 3, 3, 3, 2]
1145 frame = None
1146 def save_caller_frame():
1147 nonlocal frame
1148 frame = sys._getframe(1)
1149 for func, lastline in zip(funcs, lastlines, strict=True):
1150 with self.subTest(func=func):
1151 func(save_caller_frame)
1152 self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, lastline)
1153
1154 def test_lineno_after_no_code(self):
1155 def no_code1():
1156 "doc string"
1157
1158 def no_code2():
1159 a: int
1160
1161 for func in (no_code1, no_code2):
1162 with self.subTest(func=func):
1163 if func is no_code1 and no_code1.__doc__ is None:
1164 continue
1165 code = func.__code__
1166 [(start, end, line)] = code.co_lines()
1167 self.assertEqual(start, 0)
1168 self.assertEqual(end, len(code.co_code))
1169 self.assertEqual(line, code.co_firstlineno)
1170
1171 def get_code_lines(self, code):
1172 last_line = -2
1173 res = []
1174 for _, _, line in code.co_lines():
1175 if line is not None and line != last_line:
1176 res.append(line - code.co_firstlineno)
1177 last_line = line
1178 return res
1179
1180 def test_lineno_attribute(self):
1181 def load_attr():
1182 return (
1183 o.
1184 a
1185 )
1186 load_attr_lines = [ 0, 2, 3, 1 ]
1187
1188 def load_method():
1189 return (
1190 o.
1191 m(
1192 0
1193 )
1194 )
1195 load_method_lines = [ 0, 2, 3, 4, 3, 1 ]
1196
1197 def store_attr():
1198 (
1199 o.
1200 a
1201 ) = (
1202 v
1203 )
1204 store_attr_lines = [ 0, 5, 2, 3 ]
1205
1206 def aug_store_attr():
1207 (
1208 o.
1209 a
1210 ) += (
1211 v
1212 )
1213 aug_store_attr_lines = [ 0, 2, 3, 5, 1, 3 ]
1214
1215 funcs = [ load_attr, load_method, store_attr, aug_store_attr]
1216 func_lines = [ load_attr_lines, load_method_lines,
1217 store_attr_lines, aug_store_attr_lines]
1218
1219 for func, lines in zip(funcs, func_lines, strict=True):
1220 with self.subTest(func=func):
1221 code_lines = self.get_code_lines(func.__code__)
1222 self.assertEqual(lines, code_lines)
1223
1224 def test_line_number_genexp(self):
1225
1226 def return_genexp():
1227 return (1
1228 for
1229 x
1230 in
1231 y)
1232 genexp_lines = [0, 4, 2, 0, 4]
1233
1234 genexp_code = return_genexp.__code__.co_consts[1]
1235 code_lines = self.get_code_lines(genexp_code)
1236 self.assertEqual(genexp_lines, code_lines)
1237
1238 def test_line_number_implicit_return_after_async_for(self):
1239
1240 async def test(aseq):
1241 async for i in aseq:
1242 body
1243
1244 expected_lines = [0, 1, 2, 1]
1245 code_lines = self.get_code_lines(test.__code__)
1246 self.assertEqual(expected_lines, code_lines)
1247
1248 def check_line_numbers(self, code, opnames=None):
1249 # Check that all instructions whose op matches opnames
1250 # have a line number. opnames can be a single name, or
1251 # a sequence of names. If it is None, match all ops.
1252
1253 if isinstance(opnames, str):
1254 opnames = (opnames, )
1255 for inst in dis.Bytecode(code):
1256 if opnames and inst.opname in opnames:
1257 self.assertIsNotNone(inst.positions.lineno)
1258
1259 def test_line_number_synthetic_jump_multiple_predecessors(self):
1260 def f():
1261 for x in it:
1262 try:
1263 if C1:
1264 yield 2
1265 except OSError:
1266 pass
1267
1268 self.check_line_numbers(f.__code__, 'JUMP_BACKWARD')
1269
1270 def test_line_number_synthetic_jump_multiple_predecessors_nested(self):
1271 def f():
1272 for x in it:
1273 try:
1274 X = 3
1275 except OSError:
1276 try:
1277 if C3:
1278 X = 4
1279 except OSError:
1280 pass
1281 return 42
1282
1283 self.check_line_numbers(f.__code__, 'JUMP_BACKWARD')
1284
1285 def test_line_number_synthetic_jump_multiple_predecessors_more_nested(self):
1286 def f():
1287 for x in it:
1288 try:
1289 X = 3
1290 except OSError:
1291 try:
1292 if C3:
1293 if C4:
1294 X = 4
1295 except OSError:
1296 try:
1297 if C3:
1298 if C4:
1299 X = 5
1300 except OSError:
1301 pass
1302 return 42
1303
1304 self.check_line_numbers(f.__code__, 'JUMP_BACKWARD')
1305
1306 def test_lineno_of_backward_jump_conditional_in_loop(self):
1307 # Issue gh-107901
1308 def f():
1309 for i in x:
1310 if y:
1311 pass
1312
1313 self.check_line_numbers(f.__code__, 'JUMP_BACKWARD')
1314
1315 def test_big_dict_literal(self):
1316 # The compiler has a flushing point in "compiler_dict" that calls compiles
1317 # a portion of the dictionary literal when the loop that iterates over the items
1318 # reaches 0xFFFF elements but the code was not including the boundary element,
1319 # dropping the key at position 0xFFFF. See bpo-41531 for more information
1320
1321 dict_size = 0xFFFF + 1
1322 the_dict = "{" + ",".join(f"{x}:{x}" for x in range(dict_size)) + "}"
1323 self.assertEqual(len(eval(the_dict)), dict_size)
1324
1325 def test_redundant_jump_in_if_else_break(self):
1326 # Check if bytecode containing jumps that simply point to the next line
1327 # is generated around if-else-break style structures. See bpo-42615.
1328
1329 def if_else_break():
1330 val = 1
1331 while True:
1332 if val > 0:
1333 val -= 1
1334 else:
1335 break
1336 val = -1
1337
1338 INSTR_SIZE = 2
1339 HANDLED_JUMPS = (
1340 'POP_JUMP_IF_FALSE',
1341 'POP_JUMP_IF_TRUE',
1342 'JUMP_ABSOLUTE',
1343 'JUMP_FORWARD',
1344 )
1345
1346 for line, instr in enumerate(
1347 dis.Bytecode(if_else_break, show_caches=True)
1348 ):
1349 if instr.opname == 'JUMP_FORWARD':
1350 self.assertNotEqual(instr.arg, 0)
1351 elif instr.opname in HANDLED_JUMPS:
1352 self.assertNotEqual(instr.arg, (line + 1)*INSTR_SIZE)
1353
1354 def test_no_wraparound_jump(self):
1355 # See https://bugs.python.org/issue46724
1356
1357 def while_not_chained(a, b, c):
1358 while not (a < b < c):
1359 pass
1360
1361 for instr in dis.Bytecode(while_not_chained):
1362 self.assertNotEqual(instr.opname, "EXTENDED_ARG")
1363
1364 @support.cpython_only
1365 def test_uses_slice_instructions(self):
1366
1367 def check_op_count(func, op, expected):
1368 actual = 0
1369 for instr in dis.Bytecode(func):
1370 if instr.opname == op:
1371 actual += 1
1372 self.assertEqual(actual, expected)
1373
1374 def load():
1375 return x[a:b] + x [a:] + x[:b] + x[:]
1376
1377 def store():
1378 x[a:b] = y
1379 x [a:] = y
1380 x[:b] = y
1381 x[:] = y
1382
1383 def long_slice():
1384 return x[a:b:c]
1385
1386 def aug():
1387 x[a:b] += y
1388
1389 check_op_count(load, "BINARY_SLICE", 4)
1390 check_op_count(load, "BUILD_SLICE", 0)
1391 check_op_count(store, "STORE_SLICE", 4)
1392 check_op_count(store, "BUILD_SLICE", 0)
1393 check_op_count(long_slice, "BUILD_SLICE", 1)
1394 check_op_count(long_slice, "BINARY_SLICE", 0)
1395 check_op_count(aug, "BINARY_SLICE", 1)
1396 check_op_count(aug, "STORE_SLICE", 1)
1397 check_op_count(aug, "BUILD_SLICE", 0)
1398
1399 def test_compare_positions(self):
1400 for opname_prefix, op in [
1401 ("COMPARE_", "<"),
1402 ("COMPARE_", "<="),
1403 ("COMPARE_", ">"),
1404 ("COMPARE_", ">="),
1405 ("CONTAINS_OP", "in"),
1406 ("CONTAINS_OP", "not in"),
1407 ("IS_OP", "is"),
1408 ("IS_OP", "is not"),
1409 ]:
1410 expr = f'a {op} b {op} c'
1411 expected_positions = 2 * [(2, 2, 0, len(expr))]
1412 for source in [
1413 f"\\\n{expr}", f'if \\\n{expr}: x', f"x if \\\n{expr} else y"
1414 ]:
1415 code = compile(source, "<test>", "exec")
1416 actual_positions = [
1417 instruction.positions
1418 for instruction in dis.get_instructions(code)
1419 if instruction.opname.startswith(opname_prefix)
1420 ]
1421 with self.subTest(source):
1422 self.assertEqual(actual_positions, expected_positions)
1423
1424 def test_if_expression_expression_empty_block(self):
1425 # See regression in gh-99708
1426 exprs = [
1427 "assert (False if 1 else True)",
1428 "def f():\n\tif not (False if 1 else True): raise AssertionError",
1429 "def f():\n\tif not (False if 1 else True): return 12",
1430 ]
1431 for expr in exprs:
1432 with self.subTest(expr=expr):
1433 compile(expr, "<single>", "exec")
1434
1435 def test_multi_line_lambda_as_argument(self):
1436 # See gh-101928
1437 code = textwrap.dedent("""
1438 def foo(param, lambda_exp):
1439 pass
1440
1441 foo(param=0,
1442 lambda_exp=lambda:
1443 1)
1444 """)
1445 compile(code, "<test>", "exec")
1446
1447 def test_apply_static_swaps(self):
1448 def f(x, y):
1449 a, a = x, y
1450 return a
1451 self.assertEqual(f("x", "y"), "y")
1452
1453 def test_apply_static_swaps_2(self):
1454 def f(x, y, z):
1455 a, b, a = x, y, z
1456 return a
1457 self.assertEqual(f("x", "y", "z"), "z")
1458
1459 def test_apply_static_swaps_3(self):
1460 def f(x, y, z):
1461 a, a, b = x, y, z
1462 return a
1463 self.assertEqual(f("x", "y", "z"), "y")
1464
1465 def test_variable_dependent(self):
1466 # gh-104635: Since the value of b is dependent on the value of a
1467 # the first STORE_FAST for a should not be skipped. (e.g POP_TOP).
1468 # This test case is added to prevent potential regression from aggressive optimization.
1469 def f():
1470 a = 42; b = a + 54; a = 54
1471 return a, b
1472 self.assertEqual(f(), (54, 96))
1473
1474 def test_duplicated_small_exit_block(self):
1475 # See gh-109627
1476 def f():
1477 while element and something:
1478 try:
1479 return something
1480 except:
1481 pass
1482
1483 def test_cold_block_moved_to_end(self):
1484 # See gh-109719
1485 def f():
1486 while name:
1487 try:
1488 break
1489 except:
1490 pass
1491 else:
1492 1 if 1 else 1
1493
1494 def test_remove_empty_basic_block_with_jump_target_label(self):
1495 # See gh-109823
1496 def f(x):
1497 while x:
1498 0 if 1 else 0
1499
1500 def test_remove_redundant_nop_edge_case(self):
1501 # See gh-109889
1502 def f():
1503 a if (1 if b else c) else d
1504
1505 def test_global_declaration_in_except_used_in_else(self):
1506 # See gh-111123
1507 code = textwrap.dedent("""\
1508 def f():
1509 try:
1510 pass
1511 %s Exception:
1512 global a
1513 else:
1514 print(a)
1515 """)
1516
1517 g, l = {'a': 5}, {}
1518 for kw in ("except", "except*"):
1519 exec(code % kw, g, l);
1520
1521 def test_regression_gh_120225(self):
1522 async def name_4():
1523 match b'':
1524 case True:
1525 pass
1526 case name_5 if f'e':
1527 {name_3: name_4 async for name_2 in name_5}
1528 case []:
1529 pass
1530 [[]]
1531
1532 def test_compile_warnings(self):
1533 # Each invocation of compile() emits compiler warnings, even if they
1534 # have the same message and line number.
1535 source = textwrap.dedent(r"""
1536 # tokenizer
1537 1or 0 # line 3
1538 # code generator
1539 1 is 1 # line 5
1540 """)
1541 with warnings.catch_warnings(record=True) as caught:
1542 warnings.simplefilter("default")
1543 for i in range(2):
1544 # Even if compile() is at the same line.
1545 compile(source, '<stdin>', 'exec')
1546
1547 self.assertEqual([wm.lineno for wm in caught], [3, 5] * 2)
1548
1549 def test_compile_warning_in_finally(self):
1550 # Ensure that warnings inside finally blocks are
1551 # only emitted once despite the block being
1552 # compiled twice (for normal execution and for
1553 # exception handling).
1554 source = textwrap.dedent("""
1555 try:
1556 pass
1557 finally:
1558 1 is 1 # line 5
1559 try:
1560 pass
1561 finally: # nested
1562 1 is 1 # line 9
1563 """)
1564
1565 with warnings.catch_warnings(record=True) as caught:
1566 warnings.simplefilter("always")
1567 compile(source, '<stdin>', 'exec')
1568
1569 self.assertEqual(sorted(wm.lineno for wm in caught), [5, 9])
1570 for wm in caught:
1571 self.assertEqual(wm.category, SyntaxWarning)
1572 self.assertIn("\"is\" with 'int' literal", str(wm.message))
1573
1574 # Other code path is used for "try" with "except*".
1575 source = textwrap.dedent("""
1576 try:
1577 pass
1578 except *Exception:
1579 pass
1580 finally:
1581 1 is 1 # line 7
1582 try:
1583 pass
1584 except *Exception:
1585 pass
1586 finally: # nested
1587 1 is 1 # line 13
1588 """)
1589
1590 with warnings.catch_warnings(record=True) as caught:
1591 warnings.simplefilter("always")
1592 compile(source, '<stdin>', 'exec')
1593
1594 self.assertEqual(sorted(wm.lineno for wm in caught), [7, 13])
1595 for wm in caught:
1596 self.assertEqual(wm.category, SyntaxWarning)
1597 self.assertIn("\"is\" with 'int' literal", str(wm.message))
1598
1599
1600 @requires_debug_ranges()
1601 class TestSourcePositions(unittest.TestCase):
1602 # Ensure that compiled code snippets have correct line and column numbers
1603 # in `co_positions()`.
1604
1605 def check_positions_against_ast(self, snippet):
1606 # Basic check that makes sure each line and column is at least present
1607 # in one of the AST nodes of the source code.
1608 code = compile(snippet, 'test_compile.py', 'exec')
1609 ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST)
1610 self.assertTrue(type(ast_tree) == _ast.Module)
1611
1612 # Use an AST visitor that notes all the offsets.
1613 lines, end_lines, columns, end_columns = set(), set(), set(), set()
1614 class SourceOffsetVisitor(ast.NodeVisitor):
1615 def generic_visit(self, node):
1616 super().generic_visit(node)
1617 if not isinstance(node, (ast.expr, ast.stmt, ast.pattern)):
1618 return
1619 lines.add(node.lineno)
1620 end_lines.add(node.end_lineno)
1621 columns.add(node.col_offset)
1622 end_columns.add(node.end_col_offset)
1623
1624 SourceOffsetVisitor().visit(ast_tree)
1625
1626 # Check against the positions in the code object.
1627 for (line, end_line, col, end_col) in code.co_positions():
1628 if line == 0:
1629 continue # This is an artificial module-start line
1630 # If the offset is not None (indicating missing data), ensure that
1631 # it was part of one of the AST nodes.
1632 if line is not None:
1633 self.assertIn(line, lines)
1634 if end_line is not None:
1635 self.assertIn(end_line, end_lines)
1636 if col is not None:
1637 self.assertIn(col, columns)
1638 if end_col is not None:
1639 self.assertIn(end_col, end_columns)
1640
1641 return code, ast_tree
1642
1643 def assertOpcodeSourcePositionIs(self, code, opcode,
1644 line, end_line, column, end_column, occurrence=1):
1645
1646 for instr, position in instructions_with_positions(
1647 dis.Bytecode(code), code.co_positions()
1648 ):
1649 if instr.opname == opcode:
1650 occurrence -= 1
1651 if not occurrence:
1652 self.assertEqual(position[0], line)
1653 self.assertEqual(position[1], end_line)
1654 self.assertEqual(position[2], column)
1655 self.assertEqual(position[3], end_column)
1656 return
1657
1658 self.fail(f"Opcode {opcode} not found in code")
1659
1660 def test_simple_assignment(self):
1661 snippet = "x = 1"
1662 self.check_positions_against_ast(snippet)
1663
1664 def test_compiles_to_extended_op_arg(self):
1665 # Make sure we still have valid positions when the code compiles to an
1666 # EXTENDED_ARG by performing a loop which needs a JUMP_ABSOLUTE after
1667 # a bunch of opcodes.
1668 snippet = "x = x\n" * 10_000
1669 snippet += ("while x != 0:\n"
1670 " x -= 1\n"
1671 "while x != 0:\n"
1672 " x += 1\n"
1673 )
1674
1675 compiled_code, _ = self.check_positions_against_ast(snippet)
1676
1677 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
1678 line=10_000 + 2, end_line=10_000 + 2,
1679 column=2, end_column=8, occurrence=1)
1680 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
1681 line=10_000 + 4, end_line=10_000 + 4,
1682 column=2, end_column=9, occurrence=2)
1683
1684 def test_multiline_expression(self):
1685 snippet = textwrap.dedent("""\
1686 f(
1687 1, 2, 3, 4
1688 )
1689 """)
1690 compiled_code, _ = self.check_positions_against_ast(snippet)
1691 self.assertOpcodeSourcePositionIs(compiled_code, 'CALL',
1692 line=1, end_line=3, column=0, end_column=1)
1693
1694 @requires_specialization
1695 def test_multiline_boolean_expression(self):
1696 snippet = textwrap.dedent("""\
1697 if (a or
1698 (b and not c) or
1699 not (
1700 d > 0)):
1701 x = 42
1702 """)
1703 compiled_code, _ = self.check_positions_against_ast(snippet)
1704 # jump if a is true:
1705 self.assertOpcodeSourcePositionIs(compiled_code, 'POP_JUMP_IF_TRUE',
1706 line=1, end_line=1, column=4, end_column=5, occurrence=1)
1707 # jump if b is false:
1708 self.assertOpcodeSourcePositionIs(compiled_code, 'POP_JUMP_IF_FALSE',
1709 line=2, end_line=2, column=5, end_column=6, occurrence=1)
1710 # jump if c is false:
1711 self.assertOpcodeSourcePositionIs(compiled_code, 'POP_JUMP_IF_FALSE',
1712 line=2, end_line=2, column=15, end_column=16, occurrence=2)
1713 # compare d and 0
1714 self.assertOpcodeSourcePositionIs(compiled_code, 'COMPARE_OP',
1715 line=4, end_line=4, column=8, end_column=13, occurrence=1)
1716 # jump if comparison it True
1717 self.assertOpcodeSourcePositionIs(compiled_code, 'POP_JUMP_IF_TRUE',
1718 line=4, end_line=4, column=8, end_column=13, occurrence=2)
1719
1720 @unittest.skipIf(sys.flags.optimize, "Assertions are disabled in optimized mode")
1721 def test_multiline_assert(self):
1722 snippet = textwrap.dedent("""\
1723 assert (a > 0 and
1724 bb > 0 and
1725 ccc == 1000000), "error msg"
1726 """)
1727 compiled_code, _ = self.check_positions_against_ast(snippet)
1728 self.assertOpcodeSourcePositionIs(compiled_code, 'LOAD_ASSERTION_ERROR',
1729 line=1, end_line=3, column=0, end_column=36, occurrence=1)
1730 # The "error msg":
1731 self.assertOpcodeSourcePositionIs(compiled_code, 'LOAD_CONST',
1732 line=3, end_line=3, column=25, end_column=36, occurrence=4)
1733 self.assertOpcodeSourcePositionIs(compiled_code, 'CALL',
1734 line=1, end_line=3, column=0, end_column=36, occurrence=1)
1735 self.assertOpcodeSourcePositionIs(compiled_code, 'RAISE_VARARGS',
1736 line=1, end_line=3, column=8, end_column=22, occurrence=1)
1737
1738 def test_multiline_generator_expression(self):
1739 snippet = textwrap.dedent("""\
1740 ((x,
1741 2*x)
1742 for x
1743 in [1,2,3] if (x > 0
1744 and x < 100
1745 and x != 50))
1746 """)
1747 compiled_code, _ = self.check_positions_against_ast(snippet)
1748 compiled_code = compiled_code.co_consts[0]
1749 self.assertIsInstance(compiled_code, types.CodeType)
1750 self.assertOpcodeSourcePositionIs(compiled_code, 'YIELD_VALUE',
1751 line=1, end_line=2, column=1, end_column=8, occurrence=1)
1752 self.assertOpcodeSourcePositionIs(compiled_code, 'JUMP_BACKWARD',
1753 line=1, end_line=2, column=1, end_column=8, occurrence=1)
1754 self.assertOpcodeSourcePositionIs(compiled_code, 'RETURN_CONST',
1755 line=4, end_line=4, column=7, end_column=14, occurrence=1)
1756
1757 def test_multiline_async_generator_expression(self):
1758 snippet = textwrap.dedent("""\
1759 ((x,
1760 2*x)
1761 async for x
1762 in [1,2,3] if (x > 0
1763 and x < 100
1764 and x != 50))
1765 """)
1766 compiled_code, _ = self.check_positions_against_ast(snippet)
1767 compiled_code = compiled_code.co_consts[0]
1768 self.assertIsInstance(compiled_code, types.CodeType)
1769 self.assertOpcodeSourcePositionIs(compiled_code, 'YIELD_VALUE',
1770 line=1, end_line=2, column=1, end_column=8, occurrence=2)
1771 self.assertOpcodeSourcePositionIs(compiled_code, 'RETURN_CONST',
1772 line=1, end_line=6, column=0, end_column=32, occurrence=1)
1773
1774 def test_multiline_list_comprehension(self):
1775 snippet = textwrap.dedent("""\
1776 [(x,
1777 2*x)
1778 for x
1779 in [1,2,3] if (x > 0
1780 and x < 100
1781 and x != 50)]
1782 """)
1783 compiled_code, _ = self.check_positions_against_ast(snippet)
1784 self.assertIsInstance(compiled_code, types.CodeType)
1785 self.assertOpcodeSourcePositionIs(compiled_code, 'LIST_APPEND',
1786 line=1, end_line=2, column=1, end_column=8, occurrence=1)
1787 self.assertOpcodeSourcePositionIs(compiled_code, 'JUMP_BACKWARD',
1788 line=1, end_line=2, column=1, end_column=8, occurrence=1)
1789
1790 def test_multiline_async_list_comprehension(self):
1791 snippet = textwrap.dedent("""\
1792 async def f():
1793 [(x,
1794 2*x)
1795 async for x
1796 in [1,2,3] if (x > 0
1797 and x < 100
1798 and x != 50)]
1799 """)
1800 compiled_code, _ = self.check_positions_against_ast(snippet)
1801 g = {}
1802 eval(compiled_code, g)
1803 compiled_code = g['f'].__code__
1804 self.assertIsInstance(compiled_code, types.CodeType)
1805 self.assertOpcodeSourcePositionIs(compiled_code, 'LIST_APPEND',
1806 line=2, end_line=3, column=5, end_column=12, occurrence=1)
1807 self.assertOpcodeSourcePositionIs(compiled_code, 'JUMP_BACKWARD',
1808 line=2, end_line=3, column=5, end_column=12, occurrence=1)
1809 self.assertOpcodeSourcePositionIs(compiled_code, 'RETURN_CONST',
1810 line=2, end_line=7, column=4, end_column=36, occurrence=1)
1811
1812 def test_multiline_set_comprehension(self):
1813 snippet = textwrap.dedent("""\
1814 {(x,
1815 2*x)
1816 for x
1817 in [1,2,3] if (x > 0
1818 and x < 100
1819 and x != 50)}
1820 """)
1821 compiled_code, _ = self.check_positions_against_ast(snippet)
1822 self.assertIsInstance(compiled_code, types.CodeType)
1823 self.assertOpcodeSourcePositionIs(compiled_code, 'SET_ADD',
1824 line=1, end_line=2, column=1, end_column=8, occurrence=1)
1825 self.assertOpcodeSourcePositionIs(compiled_code, 'JUMP_BACKWARD',
1826 line=1, end_line=2, column=1, end_column=8, occurrence=1)
1827
1828 def test_multiline_async_set_comprehension(self):
1829 snippet = textwrap.dedent("""\
1830 async def f():
1831 {(x,
1832 2*x)
1833 async for x
1834 in [1,2,3] if (x > 0
1835 and x < 100
1836 and x != 50)}
1837 """)
1838 compiled_code, _ = self.check_positions_against_ast(snippet)
1839 g = {}
1840 eval(compiled_code, g)
1841 compiled_code = g['f'].__code__
1842 self.assertIsInstance(compiled_code, types.CodeType)
1843 self.assertOpcodeSourcePositionIs(compiled_code, 'SET_ADD',
1844 line=2, end_line=3, column=5, end_column=12, occurrence=1)
1845 self.assertOpcodeSourcePositionIs(compiled_code, 'JUMP_BACKWARD',
1846 line=2, end_line=3, column=5, end_column=12, occurrence=1)
1847 self.assertOpcodeSourcePositionIs(compiled_code, 'RETURN_CONST',
1848 line=2, end_line=7, column=4, end_column=36, occurrence=1)
1849
1850 def test_multiline_dict_comprehension(self):
1851 snippet = textwrap.dedent("""\
1852 {x:
1853 2*x
1854 for x
1855 in [1,2,3] if (x > 0
1856 and x < 100
1857 and x != 50)}
1858 """)
1859 compiled_code, _ = self.check_positions_against_ast(snippet)
1860 self.assertIsInstance(compiled_code, types.CodeType)
1861 self.assertOpcodeSourcePositionIs(compiled_code, 'MAP_ADD',
1862 line=1, end_line=2, column=1, end_column=7, occurrence=1)
1863 self.assertOpcodeSourcePositionIs(compiled_code, 'JUMP_BACKWARD',
1864 line=1, end_line=2, column=1, end_column=7, occurrence=1)
1865
1866 def test_multiline_async_dict_comprehension(self):
1867 snippet = textwrap.dedent("""\
1868 async def f():
1869 {x:
1870 2*x
1871 async for x
1872 in [1,2,3] if (x > 0
1873 and x < 100
1874 and x != 50)}
1875 """)
1876 compiled_code, _ = self.check_positions_against_ast(snippet)
1877 g = {}
1878 eval(compiled_code, g)
1879 compiled_code = g['f'].__code__
1880 self.assertIsInstance(compiled_code, types.CodeType)
1881 self.assertOpcodeSourcePositionIs(compiled_code, 'MAP_ADD',
1882 line=2, end_line=3, column=5, end_column=11, occurrence=1)
1883 self.assertOpcodeSourcePositionIs(compiled_code, 'JUMP_BACKWARD',
1884 line=2, end_line=3, column=5, end_column=11, occurrence=1)
1885 self.assertOpcodeSourcePositionIs(compiled_code, 'RETURN_CONST',
1886 line=2, end_line=7, column=4, end_column=36, occurrence=1)
1887
1888 def test_matchcase_sequence(self):
1889 snippet = textwrap.dedent("""\
1890 match x:
1891 case a, b:
1892 pass
1893 """)
1894 compiled_code, _ = self.check_positions_against_ast(snippet)
1895 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_SEQUENCE',
1896 line=2, end_line=2, column=9, end_column=13, occurrence=1)
1897 self.assertOpcodeSourcePositionIs(compiled_code, 'UNPACK_SEQUENCE',
1898 line=2, end_line=2, column=9, end_column=13, occurrence=1)
1899 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1900 line=2, end_line=2, column=9, end_column=13, occurrence=1)
1901 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1902 line=2, end_line=2, column=9, end_column=13, occurrence=2)
1903
1904 def test_matchcase_sequence_wildcard(self):
1905 snippet = textwrap.dedent("""\
1906 match x:
1907 case a, *b, c:
1908 pass
1909 """)
1910 compiled_code, _ = self.check_positions_against_ast(snippet)
1911 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_SEQUENCE',
1912 line=2, end_line=2, column=9, end_column=17, occurrence=1)
1913 self.assertOpcodeSourcePositionIs(compiled_code, 'UNPACK_EX',
1914 line=2, end_line=2, column=9, end_column=17, occurrence=1)
1915 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1916 line=2, end_line=2, column=9, end_column=17, occurrence=1)
1917 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1918 line=2, end_line=2, column=9, end_column=17, occurrence=2)
1919 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1920 line=2, end_line=2, column=9, end_column=17, occurrence=3)
1921
1922 def test_matchcase_mapping(self):
1923 snippet = textwrap.dedent("""\
1924 match x:
1925 case {"a" : a, "b": b}:
1926 pass
1927 """)
1928 compiled_code, _ = self.check_positions_against_ast(snippet)
1929 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_MAPPING',
1930 line=2, end_line=2, column=9, end_column=26, occurrence=1)
1931 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_KEYS',
1932 line=2, end_line=2, column=9, end_column=26, occurrence=1)
1933 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1934 line=2, end_line=2, column=9, end_column=26, occurrence=1)
1935 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1936 line=2, end_line=2, column=9, end_column=26, occurrence=2)
1937
1938 def test_matchcase_mapping_wildcard(self):
1939 snippet = textwrap.dedent("""\
1940 match x:
1941 case {"a" : a, "b": b, **c}:
1942 pass
1943 """)
1944 compiled_code, _ = self.check_positions_against_ast(snippet)
1945 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_MAPPING',
1946 line=2, end_line=2, column=9, end_column=31, occurrence=1)
1947 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_KEYS',
1948 line=2, end_line=2, column=9, end_column=31, occurrence=1)
1949 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1950 line=2, end_line=2, column=9, end_column=31, occurrence=1)
1951 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1952 line=2, end_line=2, column=9, end_column=31, occurrence=2)
1953
1954 def test_matchcase_class(self):
1955 snippet = textwrap.dedent("""\
1956 match x:
1957 case C(a, b):
1958 pass
1959 """)
1960 compiled_code, _ = self.check_positions_against_ast(snippet)
1961 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_CLASS',
1962 line=2, end_line=2, column=9, end_column=16, occurrence=1)
1963 self.assertOpcodeSourcePositionIs(compiled_code, 'UNPACK_SEQUENCE',
1964 line=2, end_line=2, column=9, end_column=16, occurrence=1)
1965 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1966 line=2, end_line=2, column=9, end_column=16, occurrence=1)
1967 self.assertOpcodeSourcePositionIs(compiled_code, 'STORE_NAME',
1968 line=2, end_line=2, column=9, end_column=16, occurrence=2)
1969
1970 def test_matchcase_or(self):
1971 snippet = textwrap.dedent("""\
1972 match x:
1973 case C(1) | C(2):
1974 pass
1975 """)
1976 compiled_code, _ = self.check_positions_against_ast(snippet)
1977 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_CLASS',
1978 line=2, end_line=2, column=9, end_column=13, occurrence=1)
1979 self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_CLASS',
1980 line=2, end_line=2, column=16, end_column=20, occurrence=2)
1981
1982 def test_very_long_line_end_offset(self):
1983 # Make sure we get the correct column offset for offsets
1984 # too large to store in a byte.
1985 long_string = "a" * 1000
1986 snippet = f"g('{long_string}')"
1987
1988 compiled_code, _ = self.check_positions_against_ast(snippet)
1989 self.assertOpcodeSourcePositionIs(compiled_code, 'CALL',
1990 line=1, end_line=1, column=0, end_column=1005)
1991
1992 def test_complex_single_line_expression(self):
1993 snippet = "a - b @ (c * x['key'] + 23)"
1994
1995 compiled_code, _ = self.check_positions_against_ast(snippet)
1996 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_SUBSCR',
1997 line=1, end_line=1, column=13, end_column=21)
1998 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
1999 line=1, end_line=1, column=9, end_column=21, occurrence=1)
2000 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
2001 line=1, end_line=1, column=9, end_column=26, occurrence=2)
2002 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
2003 line=1, end_line=1, column=4, end_column=27, occurrence=3)
2004 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
2005 line=1, end_line=1, column=0, end_column=27, occurrence=4)
2006
2007 def test_multiline_assert_rewritten_as_method_call(self):
2008 # GH-94694: Don't crash if pytest rewrites a multiline assert as a
2009 # method call with the same location information:
2010 tree = ast.parse("assert (\n42\n)")
2011 old_node = tree.body[0]
2012 new_node = ast.Expr(
2013 ast.Call(
2014 ast.Attribute(
2015 ast.Name("spam", ast.Load()),
2016 "eggs",
2017 ast.Load(),
2018 ),
2019 [],
2020 [],
2021 )
2022 )
2023 ast.copy_location(new_node, old_node)
2024 ast.fix_missing_locations(new_node)
2025 tree.body[0] = new_node
2026 compile(tree, "<test>", "exec")
2027
2028 def test_push_null_load_global_positions(self):
2029 source_template = """
2030 import abc, dis
2031 import ast as art
2032
2033 abc = None
2034 dix = dis
2035 ast = art
2036
2037 def f():
2038 {}
2039 """
2040 for body in [
2041 " abc.a()",
2042 " art.a()",
2043 " ast.a()",
2044 " dis.a()",
2045 " dix.a()",
2046 " abc[...]()",
2047 " art()()",
2048 " (ast or ...)()",
2049 " [dis]()",
2050 " (dix + ...)()",
2051 ]:
2052 with self.subTest(body):
2053 namespace = {}
2054 source = textwrap.dedent(source_template.format(body))
2055 with warnings.catch_warnings():
2056 warnings.simplefilter('ignore', SyntaxWarning)
2057 exec(source, namespace)
2058 code = namespace["f"].__code__
2059 self.assertOpcodeSourcePositionIs(
2060 code,
2061 "LOAD_GLOBAL",
2062 line=10,
2063 end_line=10,
2064 column=4,
2065 end_column=7,
2066 )
2067
2068 def test_attribute_augassign(self):
2069 source = "(\n lhs \n . \n rhs \n ) += 42"
2070 code = compile(source, "<test>", "exec")
2071 self.assertOpcodeSourcePositionIs(
2072 code, "LOAD_ATTR", line=4, end_line=4, column=5, end_column=8
2073 )
2074 self.assertOpcodeSourcePositionIs(
2075 code, "STORE_ATTR", line=4, end_line=4, column=5, end_column=8
2076 )
2077
2078 def test_attribute_del(self):
2079 source = "del (\n lhs \n . \n rhs \n )"
2080 code = compile(source, "<test>", "exec")
2081 self.assertOpcodeSourcePositionIs(
2082 code, "DELETE_ATTR", line=4, end_line=4, column=5, end_column=8
2083 )
2084
2085 def test_attribute_load(self):
2086 source = "(\n lhs \n . \n rhs \n )"
2087 code = compile(source, "<test>", "exec")
2088 self.assertOpcodeSourcePositionIs(
2089 code, "LOAD_ATTR", line=4, end_line=4, column=5, end_column=8
2090 )
2091
2092 def test_attribute_store(self):
2093 source = "(\n lhs \n . \n rhs \n ) = 42"
2094 code = compile(source, "<test>", "exec")
2095 self.assertOpcodeSourcePositionIs(
2096 code, "STORE_ATTR", line=4, end_line=4, column=5, end_column=8
2097 )
2098
2099 def test_method_call(self):
2100 source = "(\n lhs \n . \n rhs \n )()"
2101 code = compile(source, "<test>", "exec")
2102 self.assertOpcodeSourcePositionIs(
2103 code, "LOAD_ATTR", line=4, end_line=4, column=5, end_column=8
2104 )
2105 self.assertOpcodeSourcePositionIs(
2106 code, "CALL", line=4, end_line=5, column=5, end_column=10
2107 )
2108
2109 def test_weird_attribute_position_regressions(self):
2110 def f():
2111 (bar.
2112 baz)
2113 (bar.
2114 baz(
2115 ))
2116 files().setdefault(
2117 0
2118 ).setdefault(
2119 0
2120 )
2121 for line, end_line, column, end_column in f.__code__.co_positions():
2122 self.assertIsNotNone(line)
2123 self.assertIsNotNone(end_line)
2124 self.assertIsNotNone(column)
2125 self.assertIsNotNone(end_column)
2126 self.assertLessEqual((line, column), (end_line, end_column))
2127
2128 @support.cpython_only
2129 def test_column_offset_deduplication(self):
2130 # GH-95150: Code with different column offsets shouldn't be merged!
2131 for source in [
2132 "lambda: a",
2133 "(a for b in c)",
2134 ]:
2135 with self.subTest(source):
2136 code = compile(f"{source}, {source}", "<test>", "eval")
2137 self.assertEqual(len(code.co_consts), 2)
2138 self.assertIsInstance(code.co_consts[0], types.CodeType)
2139 self.assertIsInstance(code.co_consts[1], types.CodeType)
2140 self.assertNotEqual(code.co_consts[0], code.co_consts[1])
2141 self.assertNotEqual(
2142 list(code.co_consts[0].co_positions()),
2143 list(code.co_consts[1].co_positions()),
2144 )
2145
2146 def test_load_super_attr(self):
2147 source = "class C:\n def __init__(self):\n super().__init__()"
2148 for const in compile(source, "<test>", "exec").co_consts[0].co_consts:
2149 if isinstance(const, types.CodeType):
2150 code = const
2151 break
2152 self.assertOpcodeSourcePositionIs(
2153 code, "LOAD_GLOBAL", line=3, end_line=3, column=4, end_column=9
2154 )
2155
2156 def test_lambda_return_position(self):
2157 snippets = [
2158 "f = lambda: x",
2159 "f = lambda: 42",
2160 "f = lambda: 1 + 2",
2161 "f = lambda: a + b",
2162 ]
2163 for snippet in snippets:
2164 with self.subTest(snippet=snippet):
2165 lamb = run_code(snippet)["f"]
2166 positions = lamb.__code__.co_positions()
2167 # assert that all positions are within the lambda
2168 for i, pos in enumerate(positions):
2169 with self.subTest(i=i, pos=pos):
2170 start_line, end_line, start_col, end_col = pos
2171 if i == 0 and start_col == end_col == 0:
2172 # ignore the RESUME in the beginning
2173 continue
2174 self.assertEqual(start_line, 1)
2175 self.assertEqual(end_line, 1)
2176 code_start = snippet.find(":") + 2
2177 code_end = len(snippet)
2178 self.assertGreaterEqual(start_col, code_start)
2179 self.assertLessEqual(end_col, code_end)
2180 self.assertGreaterEqual(end_col, start_col)
2181 self.assertLessEqual(end_col, code_end)
2182
2183 def test_return_in_with_positions(self):
2184 # See gh-98442
2185 def f():
2186 with xyz:
2187 1
2188 2
2189 3
2190 4
2191 return R
2192
2193 # All instructions should have locations on a single line
2194 for instr in dis.get_instructions(f):
2195 start_line, end_line, _, _ = instr.positions
2196 self.assertEqual(start_line, end_line)
2197
2198 # Expect three load None instructions for the no-exception __exit__ call,
2199 # and one RETURN_VALUE.
2200 # They should all have the locations of the context manager ('xyz').
2201
2202 load_none = [instr for instr in dis.get_instructions(f) if
2203 instr.opname == 'LOAD_CONST' and instr.argval is None]
2204 return_value = [instr for instr in dis.get_instructions(f) if
2205 instr.opname == 'RETURN_VALUE']
2206
2207 self.assertEqual(len(load_none), 3)
2208 self.assertEqual(len(return_value), 1)
2209 for instr in load_none + return_value:
2210 start_line, end_line, start_col, end_col = instr.positions
2211 self.assertEqual(start_line, f.__code__.co_firstlineno + 1)
2212 self.assertEqual(end_line, f.__code__.co_firstlineno + 1)
2213 self.assertEqual(start_col, 17)
2214 self.assertEqual(end_col, 20)
2215
2216
2217 class TestStaticAttributes(unittest.TestCase):
2218
2219 def test_basic(self):
2220 class C:
2221 def f(self):
2222 self.a = self.b = 42
2223 # read fields are not included
2224 self.f()
2225 self.arr[3]
2226
2227 self.assertIsInstance(C.__static_attributes__, tuple)
2228 self.assertEqual(sorted(C.__static_attributes__), ['a', 'b'])
2229
2230 def test_nested_function(self):
2231 class C:
2232 def f(self):
2233 self.x = 1
2234 self.y = 2
2235 self.x = 3 # check deduplication
2236
2237 def g(self, obj):
2238 self.y = 4
2239 self.z = 5
2240
2241 def h(self, a):
2242 self.u = 6
2243 self.v = 7
2244
2245 obj.self = 8
2246
2247 self.assertEqual(sorted(C.__static_attributes__), ['u', 'v', 'x', 'y', 'z'])
2248
2249 def test_nested_class(self):
2250 class C:
2251 def f(self):
2252 self.x = 42
2253 self.y = 42
2254
2255 class D:
2256 def g(self):
2257 self.y = 42
2258 self.z = 42
2259
2260 self.assertEqual(sorted(C.__static_attributes__), ['x', 'y'])
2261 self.assertEqual(sorted(C.D.__static_attributes__), ['y', 'z'])
2262
2263 def test_subclass(self):
2264 class C:
2265 def f(self):
2266 self.x = 42
2267 self.y = 42
2268
2269 class D(C):
2270 def g(self):
2271 self.y = 42
2272 self.z = 42
2273
2274 self.assertEqual(sorted(C.__static_attributes__), ['x', 'y'])
2275 self.assertEqual(sorted(D.__static_attributes__), ['y', 'z'])
2276
2277
2278 class TestExpressionStackSize(unittest.TestCase):
2279 # These tests check that the computed stack size for a code object
2280 # stays within reasonable bounds (see issue #21523 for an example
2281 # dysfunction).
2282 N = 100
2283
2284 def check_stack_size(self, code):
2285 # To assert that the alleged stack size is not O(N), we
2286 # check that it is smaller than log(N).
2287 if isinstance(code, str):
2288 code = compile(code, "<foo>", "single")
2289 max_size = math.ceil(math.log(len(code.co_code)))
2290 self.assertLessEqual(code.co_stacksize, max_size)
2291
2292 def test_and(self):
2293 self.check_stack_size("x and " * self.N + "x")
2294
2295 def test_or(self):
2296 self.check_stack_size("x or " * self.N + "x")
2297
2298 def test_and_or(self):
2299 self.check_stack_size("x and x or " * self.N + "x")
2300
2301 def test_chained_comparison(self):
2302 self.check_stack_size("x < " * self.N + "x")
2303
2304 def test_if_else(self):
2305 self.check_stack_size("x if x else " * self.N + "x")
2306
2307 def test_binop(self):
2308 self.check_stack_size("x + " * self.N + "x")
2309
2310 def test_list(self):
2311 self.check_stack_size("[" + "x, " * self.N + "x]")
2312
2313 def test_tuple(self):
2314 self.check_stack_size("(" + "x, " * self.N + "x)")
2315
2316 def test_set(self):
2317 self.check_stack_size("{" + "x, " * self.N + "x}")
2318
2319 def test_dict(self):
2320 self.check_stack_size("{" + "x:x, " * self.N + "x:x}")
2321
2322 def test_func_args(self):
2323 self.check_stack_size("f(" + "x, " * self.N + ")")
2324
2325 def test_func_kwargs(self):
2326 kwargs = (f'a{i}=x' for i in range(self.N))
2327 self.check_stack_size("f(" + ", ".join(kwargs) + ")")
2328
2329 def test_meth_args(self):
2330 self.check_stack_size("o.m(" + "x, " * self.N + ")")
2331
2332 def test_meth_kwargs(self):
2333 kwargs = (f'a{i}=x' for i in range(self.N))
2334 self.check_stack_size("o.m(" + ", ".join(kwargs) + ")")
2335
2336 def test_func_and(self):
2337 code = "def f(x):\n"
2338 code += " x and x\n" * self.N
2339 self.check_stack_size(code)
2340
2341 def test_stack_3050(self):
2342 M = 3050
2343 code = "x," * M + "=t"
2344 # This raised on 3.10.0 to 3.10.5
2345 compile(code, "<foo>", "single")
2346
2347 def test_stack_3050_2(self):
2348 M = 3050
2349 args = ", ".join(f"arg{i}:type{i}" for i in range(M))
2350 code = f"def f({args}):\n pass"
2351 # This raised on 3.10.0 to 3.10.5
2352 compile(code, "<foo>", "single")
2353
2354
2355 class TestStackSizeStability(unittest.TestCase):
2356 # Check that repeating certain snippets doesn't increase the stack size
2357 # beyond what a single snippet requires.
2358
2359 def check_stack_size(self, snippet, async_=False):
2360 def compile_snippet(i):
2361 ns = {}
2362 script = """def func():\n""" + i * snippet
2363 if async_:
2364 script = "async " + script
2365 code = compile(script, "<script>", "exec")
2366 exec(code, ns, ns)
2367 return ns['func'].__code__
2368
2369 sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)]
2370 if len(set(sizes)) != 1:
2371 import dis, io
2372 out = io.StringIO()
2373 dis.dis(compile_snippet(1), file=out)
2374 self.fail("stack sizes diverge with # of consecutive snippets: "
2375 "%s\n%s\n%s" % (sizes, snippet, out.getvalue()))
2376
2377 def test_if(self):
2378 snippet = """
2379 if x:
2380 a
2381 """
2382 self.check_stack_size(snippet)
2383
2384 def test_if_else(self):
2385 snippet = """
2386 if x:
2387 a
2388 elif y:
2389 b
2390 else:
2391 c
2392 """
2393 self.check_stack_size(snippet)
2394
2395 def test_try_except_bare(self):
2396 snippet = """
2397 try:
2398 a
2399 except:
2400 b
2401 """
2402 self.check_stack_size(snippet)
2403
2404 def test_try_except_qualified(self):
2405 snippet = """
2406 try:
2407 a
2408 except ImportError:
2409 b
2410 except:
2411 c
2412 else:
2413 d
2414 """
2415 self.check_stack_size(snippet)
2416
2417 def test_try_except_as(self):
2418 snippet = """
2419 try:
2420 a
2421 except ImportError as e:
2422 b
2423 except:
2424 c
2425 else:
2426 d
2427 """
2428 self.check_stack_size(snippet)
2429
2430 def test_try_except_star_qualified(self):
2431 snippet = """
2432 try:
2433 a
2434 except* ImportError:
2435 b
2436 else:
2437 c
2438 """
2439 self.check_stack_size(snippet)
2440
2441 def test_try_except_star_as(self):
2442 snippet = """
2443 try:
2444 a
2445 except* ImportError as e:
2446 b
2447 else:
2448 c
2449 """
2450 self.check_stack_size(snippet)
2451
2452 def test_try_except_star_finally(self):
2453 snippet = """
2454 try:
2455 a
2456 except* A:
2457 b
2458 finally:
2459 c
2460 """
2461 self.check_stack_size(snippet)
2462
2463 def test_try_finally(self):
2464 snippet = """
2465 try:
2466 a
2467 finally:
2468 b
2469 """
2470 self.check_stack_size(snippet)
2471
2472 def test_with(self):
2473 snippet = """
2474 with x as y:
2475 a
2476 """
2477 self.check_stack_size(snippet)
2478
2479 def test_while_else(self):
2480 snippet = """
2481 while x:
2482 a
2483 else:
2484 b
2485 """
2486 self.check_stack_size(snippet)
2487
2488 def test_for(self):
2489 snippet = """
2490 for x in y:
2491 a
2492 """
2493 self.check_stack_size(snippet)
2494
2495 def test_for_else(self):
2496 snippet = """
2497 for x in y:
2498 a
2499 else:
2500 b
2501 """
2502 self.check_stack_size(snippet)
2503
2504 def test_for_break_continue(self):
2505 snippet = """
2506 for x in y:
2507 if z:
2508 break
2509 elif u:
2510 continue
2511 else:
2512 a
2513 else:
2514 b
2515 """
2516 self.check_stack_size(snippet)
2517
2518 def test_for_break_continue_inside_try_finally_block(self):
2519 snippet = """
2520 for x in y:
2521 try:
2522 if z:
2523 break
2524 elif u:
2525 continue
2526 else:
2527 a
2528 finally:
2529 f
2530 else:
2531 b
2532 """
2533 self.check_stack_size(snippet)
2534
2535 def test_for_break_continue_inside_finally_block(self):
2536 snippet = """
2537 for x in y:
2538 try:
2539 t
2540 finally:
2541 if z:
2542 break
2543 elif u:
2544 continue
2545 else:
2546 a
2547 else:
2548 b
2549 """
2550 self.check_stack_size(snippet)
2551
2552 def test_for_break_continue_inside_except_block(self):
2553 snippet = """
2554 for x in y:
2555 try:
2556 t
2557 except:
2558 if z:
2559 break
2560 elif u:
2561 continue
2562 else:
2563 a
2564 else:
2565 b
2566 """
2567 self.check_stack_size(snippet)
2568
2569 def test_for_break_continue_inside_with_block(self):
2570 snippet = """
2571 for x in y:
2572 with c:
2573 if z:
2574 break
2575 elif u:
2576 continue
2577 else:
2578 a
2579 else:
2580 b
2581 """
2582 self.check_stack_size(snippet)
2583
2584 def test_return_inside_try_finally_block(self):
2585 snippet = """
2586 try:
2587 if z:
2588 return
2589 else:
2590 a
2591 finally:
2592 f
2593 """
2594 self.check_stack_size(snippet)
2595
2596 def test_return_inside_finally_block(self):
2597 snippet = """
2598 try:
2599 t
2600 finally:
2601 if z:
2602 return
2603 else:
2604 a
2605 """
2606 self.check_stack_size(snippet)
2607
2608 def test_return_inside_except_block(self):
2609 snippet = """
2610 try:
2611 t
2612 except:
2613 if z:
2614 return
2615 else:
2616 a
2617 """
2618 self.check_stack_size(snippet)
2619
2620 def test_return_inside_with_block(self):
2621 snippet = """
2622 with c:
2623 if z:
2624 return
2625 else:
2626 a
2627 """
2628 self.check_stack_size(snippet)
2629
2630 def test_async_with(self):
2631 snippet = """
2632 async with x as y:
2633 a
2634 """
2635 self.check_stack_size(snippet, async_=True)
2636
2637 def test_async_for(self):
2638 snippet = """
2639 async for x in y:
2640 a
2641 """
2642 self.check_stack_size(snippet, async_=True)
2643
2644 def test_async_for_else(self):
2645 snippet = """
2646 async for x in y:
2647 a
2648 else:
2649 b
2650 """
2651 self.check_stack_size(snippet, async_=True)
2652
2653 def test_for_break_continue_inside_async_with_block(self):
2654 snippet = """
2655 for x in y:
2656 async with c:
2657 if z:
2658 break
2659 elif u:
2660 continue
2661 else:
2662 a
2663 else:
2664 b
2665 """
2666 self.check_stack_size(snippet, async_=True)
2667
2668 def test_return_inside_async_with_block(self):
2669 snippet = """
2670 async with c:
2671 if z:
2672 return
2673 else:
2674 a
2675 """
2676 self.check_stack_size(snippet, async_=True)
2677
2678 class TestInstructionSequence(unittest.TestCase):
2679 def compare_instructions(self, seq, expected):
2680 self.assertEqual([(opcode.opname[i[0]],) + i[1:] for i in seq.get_instructions()],
2681 expected)
2682
2683 def test_basics(self):
2684 seq = _testinternalcapi.new_instruction_sequence()
2685
2686 def add_op(seq, opname, oparg, bl, bc=0, el=0, ec=0):
2687 seq.addop(opcode.opmap[opname], oparg, bl, bc, el, el)
2688
2689 add_op(seq, 'LOAD_CONST', 1, 1)
2690 add_op(seq, 'JUMP', lbl1 := seq.new_label(), 2)
2691 add_op(seq, 'LOAD_CONST', 1, 3)
2692 add_op(seq, 'JUMP', lbl2 := seq.new_label(), 4)
2693 seq.use_label(lbl1)
2694 add_op(seq, 'LOAD_CONST', 2, 4)
2695 seq.use_label(lbl2)
2696 add_op(seq, 'RETURN_VALUE', 0, 3)
2697
2698 expected = [('LOAD_CONST', 1, 1),
2699 ('JUMP', 4, 2),
2700 ('LOAD_CONST', 1, 3),
2701 ('JUMP', 5, 4),
2702 ('LOAD_CONST', 2, 4),
2703 ('RETURN_VALUE', None, 3),
2704 ]
2705
2706 self.compare_instructions(seq, [ex + (0,0,0) for ex in expected])
2707
2708 def test_nested(self):
2709 seq = _testinternalcapi.new_instruction_sequence()
2710 seq.addop(opcode.opmap['LOAD_CONST'], 1, 1, 0, 0, 0)
2711 nested = _testinternalcapi.new_instruction_sequence()
2712 nested.addop(opcode.opmap['LOAD_CONST'], 2, 2, 0, 0, 0)
2713
2714 self.compare_instructions(seq, [('LOAD_CONST', 1, 1, 0, 0, 0)])
2715 self.compare_instructions(nested, [('LOAD_CONST', 2, 2, 0, 0, 0)])
2716
2717 seq.add_nested(nested)
2718 self.compare_instructions(seq, [('LOAD_CONST', 1, 1, 0, 0, 0)])
2719 self.compare_instructions(seq.get_nested()[0], [('LOAD_CONST', 2, 2, 0, 0, 0)])
2720
2721 def test_static_attributes_are_sorted(self):
2722 code = (
2723 'class T:\n'
2724 ' def __init__(self):\n'
2725 ' self.{V1} = 10\n'
2726 ' self.{V2} = 10\n'
2727 ' def foo(self):\n'
2728 ' self.{V3} = 10\n'
2729 )
2730 attributes = ("a", "b", "c")
2731 for perm in itertools.permutations(attributes):
2732 var_names = {f'V{i + 1}': name for i, name in enumerate(perm)}
2733 ns = run_code(code.format(**var_names))
2734 t = ns['T']
2735 self.assertEqual(t.__static_attributes__, attributes)
2736
2737
2738 if __name__ == "__main__":
2739 unittest.main()