Debian Codegraph @

lib-python/3/test/test_compile.py

raw symbols SCIP
1 import dis
2 import math
3 import os
4 import unittest
5 import sys
6 import ast
7 import _ast
8 import tempfile
9 import types
10 import textwrap
11 from test import support
12 from test.support import script_helper, requires_debug_ranges
13 from test.support.os_helper import FakePath
14
15
16 class TestSpecifics(unittest.TestCase):
17
18 def compile_single(self, source):
19 compile(source, "<single>", "single")
20
21 def assertInvalidSingle(self, source):
22 self.assertRaises(SyntaxError, self.compile_single, source)
23
24 def test_no_ending_newline(self):
25 compile("hi", "<test>", "exec")
26 compile("hi\r", "<test>", "exec")
27
28 def test_empty(self):
29 compile("", "<test>", "exec")
30
31 def test_other_newlines(self):
32 compile("\r\n", "<test>", "exec")
33 compile("\r", "<test>", "exec")
34 compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
35 compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
36
37 def test_debug_assignment(self):
38 # catch assignments to __debug__
39 self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
40 import builtins
41 prev = builtins.__debug__
42 setattr(builtins, '__debug__', 'sure')
43 self.assertEqual(__debug__, prev)
44 setattr(builtins, '__debug__', prev)
45
46 def test_argument_handling(self):
47 # detect duplicate positional and keyword arguments
48 self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
49 self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
50 self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
51 self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
52 self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
53 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
54
55 def test_syntax_error(self):
56 self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
57
58 def test_none_keyword_arg(self):
59 self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
60
61 def test_duplicate_global_local(self):
62 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
63
64 def test_exec_with_general_mapping_for_locals(self):
65
66 class M:
67 "Test mapping interface versus possible calls from eval()."
68 def __getitem__(self, key):
69 if key == 'a':
70 return 12
71 raise KeyError
72 def __setitem__(self, key, value):
73 self.results = (key, value)
74 def keys(self):
75 return list('xyz')
76
77 m = M()
78 g = globals()
79 exec('z = a', g, m)
80 self.assertEqual(m.results, ('z', 12))
81 try:
82 exec('z = b', g, m)
83 except NameError:
84 pass
85 else:
86 self.fail('Did not detect a KeyError')
87 exec('z = dir()', g, m)
88 self.assertEqual(m.results, ('z', list('xyz')))
89 exec('z = globals()', g, m)
90 self.assertEqual(m.results, ('z', g))
91 exec('z = locals()', g, m)
92 self.assertEqual(m.results, ('z', m))
93 self.assertRaises(TypeError, exec, 'z = b', m)
94
95 class A:
96 "Non-mapping"
97 pass
98 m = A()
99 self.assertRaises(TypeError, exec, 'z = a', g, m)
100
101 # Verify that dict subclasses work as well
102 class D(dict):
103 def __getitem__(self, key):
104 if key == 'a':
105 return 12
106 return dict.__getitem__(self, key)
107 d = D()
108 exec('z = a', g, d)
109 self.assertEqual(d['z'], 12)
110
111 def test_extended_arg(self):
112 # default: 1000 * 2.5 = 2500 repetitions
113 repeat = int(sys.getrecursionlimit() * 2.5)
114 longexpr = 'x = x or ' + '-x' * repeat
115 g = {}
116 code = '''
117 def f(x):
118 %s
119 %s
120 %s
121 %s
122 %s
123 %s
124 %s
125 %s
126 %s
127 %s
128 # the expressions above have no effect, x == argument
129 while x:
130 x -= 1
131 # EXTENDED_ARG/JUMP_ABSOLUTE here
132 return x
133 ''' % ((longexpr,)*10)
134 exec(code, g)
135 self.assertEqual(g['f'](5), 0)
136
137 def test_argument_order(self):
138 self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
139
140 def test_float_literals(self):
141 # testing bad float literals
142 self.assertRaises(SyntaxError, eval, "2e")
143 self.assertRaises(SyntaxError, eval, "2.0e+")
144 self.assertRaises(SyntaxError, eval, "1e-")
145 self.assertRaises(SyntaxError, eval, "3-4e/21")
146
147 def test_indentation(self):
148 # testing compile() of indented block w/o trailing newline"
149 s = """
150 if 1:
151 if 2:
152 pass"""
153 compile(s, "<string>", "exec")
154
155 # This test is probably specific to CPython and may not generalize
156 # to other implementations. We are trying to ensure that when
157 # the first line of code starts after 256, correct line numbers
158 # in tracebacks are still produced.
159 def test_leading_newlines(self):
160 s256 = "".join(["\n"] * 256 + ["spam"])
161 co = compile(s256, 'fn', 'exec')
162 self.assertEqual(co.co_firstlineno, 1)
163 lines = list(co.co_lines())
164 if sys.implementation.name == 'pypy':
165 # PyPy has no RESUME opcode, so there is no line-0 entry.
166 self.assertEqual(lines[0][2], 257)
167 else:
168 self.assertEqual(lines[0][2], 0)
169 self.assertEqual(lines[1][2], 257)
170
171 def test_literals_with_leading_zeroes(self):
172 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
173 "080000000000000", "000000000000009", "000000000000008",
174 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
175 "0b101j", "0o153j", "0b100e1", "0o777e1", "0777",
176 "000777", "000000000000007"]:
177 self.assertRaises(SyntaxError, eval, arg)
178
179 self.assertEqual(eval("0xff"), 255)
180 self.assertEqual(eval("0777."), 777)
181 self.assertEqual(eval("0777.0"), 777)
182 self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
183 self.assertEqual(eval("0777e1"), 7770)
184 self.assertEqual(eval("0e0"), 0)
185 self.assertEqual(eval("0000e-012"), 0)
186 self.assertEqual(eval("09.5"), 9.5)
187 self.assertEqual(eval("0777j"), 777j)
188 self.assertEqual(eval("000"), 0)
189 self.assertEqual(eval("00j"), 0j)
190 self.assertEqual(eval("00.0"), 0)
191 self.assertEqual(eval("0e3"), 0)
192 self.assertEqual(eval("090000000000000."), 90000000000000.)
193 self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
194 self.assertEqual(eval("090000000000000e0"), 90000000000000.)
195 self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
196 self.assertEqual(eval("090000000000000j"), 90000000000000j)
197 self.assertEqual(eval("000000000000008."), 8.)
198 self.assertEqual(eval("000000000000009."), 9.)
199 self.assertEqual(eval("0b101010"), 42)
200 self.assertEqual(eval("-0b000000000010"), -2)
201 self.assertEqual(eval("0o777"), 511)
202 self.assertEqual(eval("-0o0000010"), -8)
203
204 def test_int_literals_too_long(self):
205 n = 3000
206 source = f"a = 1\nb = 2\nc = {'3'*n}\nd = 4"
207 with support.adjust_int_max_str_digits(n):
208 compile(source, "<long_int_pass>", "exec") # no errors.
209 with support.adjust_int_max_str_digits(n-1):
210 with self.assertRaises(SyntaxError) as err_ctx:
211 compile(source, "<long_int_fail>", "exec")
212 exc = err_ctx.exception
213 self.assertEqual(exc.lineno, 3)
214 self.assertIn('Exceeds the limit ', str(exc))
215 self.assertIn(' Consider hexadecimal ', str(exc))
216
217 def test_unary_minus(self):
218 # Verify treatment of unary minus on negative numbers SF bug #660455
219 if sys.maxsize == 2147483647:
220 # 32-bit machine
221 all_one_bits = '0xffffffff'
222 self.assertEqual(eval(all_one_bits), 4294967295)
223 self.assertEqual(eval("-" + all_one_bits), -4294967295)
224 elif sys.maxsize == 9223372036854775807:
225 # 64-bit machine
226 all_one_bits = '0xffffffffffffffff'
227 self.assertEqual(eval(all_one_bits), 18446744073709551615)
228 self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
229 else:
230 self.fail("How many bits *does* this machine have???")
231 # Verify treatment of constant folding on -(sys.maxsize+1)
232 # i.e. -2147483648 on 32 bit platforms. Should return int.
233 self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
234 self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
235
236 if sys.maxsize == 9223372036854775807:
237 def test_32_63_bit_values(self):
238 a = +4294967296 # 1 << 32
239 b = -4294967296 # 1 << 32
240 c = +281474976710656 # 1 << 48
241 d = -281474976710656 # 1 << 48
242 e = +4611686018427387904 # 1 << 62
243 f = -4611686018427387904 # 1 << 62
244 g = +9223372036854775807 # 1 << 63 - 1
245 h = -9223372036854775807 # 1 << 63 - 1
246
247 for variable in self.test_32_63_bit_values.__code__.co_consts:
248 if variable is not None:
249 self.assertIsInstance(variable, int)
250
251 def test_sequence_unpacking_error(self):
252 # Verify sequence packing/unpacking with "or". SF bug #757818
253 i,j = (1, -1) or (-1, 1)
254 self.assertEqual(i, 1)
255 self.assertEqual(j, -1)
256
257 def test_none_assignment(self):
258 stmts = [
259 'None = 0',
260 'None += 0',
261 '__builtins__.None = 0',
262 'def None(): pass',
263 'class None: pass',
264 '(a, None) = 0, 0',
265 'for None in range(10): pass',
266 'def f(None): pass',
267 'import None',
268 'import x as None',
269 'from x import None',
270 'from x import y as None'
271 ]
272 for stmt in stmts:
273 stmt += "\n"
274 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
275 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
276
277 def test_import(self):
278 succeed = [
279 'import sys',
280 'import os, sys',
281 'import os as bar',
282 'import os.path as bar',
283 'from __future__ import nested_scopes, generators',
284 'from __future__ import (nested_scopes,\ngenerators)',
285 'from __future__ import (nested_scopes,\ngenerators,)',
286 'from sys import stdin, stderr, stdout',
287 'from sys import (stdin, stderr,\nstdout)',
288 'from sys import (stdin, stderr,\nstdout,)',
289 'from sys import (stdin\n, stderr, stdout)',
290 'from sys import (stdin\n, stderr, stdout,)',
291 'from sys import stdin as si, stdout as so, stderr as se',
292 'from sys import (stdin as si, stdout as so, stderr as se)',
293 'from sys import (stdin as si, stdout as so, stderr as se,)',
294 ]
295 fail = [
296 'import (os, sys)',
297 'import (os), (sys)',
298 'import ((os), (sys))',
299 'import (sys',
300 'import sys)',
301 'import (os,)',
302 'import os As bar',
303 'import os.path a bar',
304 'from sys import stdin As stdout',
305 'from sys import stdin a stdout',
306 'from (sys) import stdin',
307 'from __future__ import (nested_scopes',
308 'from __future__ import nested_scopes)',
309 'from __future__ import nested_scopes,\ngenerators',
310 'from sys import (stdin',
311 'from sys import stdin)',
312 'from sys import stdin, stdout,\nstderr',
313 'from sys import stdin si',
314 'from sys import stdin,',
315 'from sys import (*)',
316 'from sys import (stdin,, stdout, stderr)',
317 'from sys import (stdin, stdout),',
318 ]
319 for stmt in succeed:
320 compile(stmt, 'tmp', 'exec')
321 for stmt in fail:
322 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
323
324 def test_for_distinct_code_objects(self):
325 # SF bug 1048870
326 def f():
327 f1 = lambda x=1: x
328 f2 = lambda x=2: x
329 return f1, f2
330 f1, f2 = f()
331 self.assertNotEqual(id(f1.__code__), id(f2.__code__))
332
333 def test_lambda_doc(self):
334 l = lambda: "foo"
335 self.assertIsNone(l.__doc__)
336
337 def test_encoding(self):
338 code = b'# -*- coding: badencoding -*-\npass\n'
339 self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec')
340 code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n'
341 compile(code, 'tmp', 'exec')
342 self.assertEqual(eval(code), '\xc2\xa4')
343 code = '"\xc2\xa4"\n'
344 self.assertEqual(eval(code), '\xc2\xa4')
345 code = b'"\xc2\xa4"\n'
346 self.assertEqual(eval(code), '\xa4')
347 code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n'
348 self.assertEqual(eval(code), '\xc2\xa4')
349 code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n'
350 self.assertEqual(eval(code), '\xa4')
351 code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n'
352 self.assertEqual(eval(code), '\xc2\u20ac')
353 code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
354 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4')
355 code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
356 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4')
357
358 def test_subscripts(self):
359 # SF bug 1448804
360 # Class to make testing subscript results easy
361 class str_map(object):
362 def __init__(self):
363 self.data = {}
364 def __getitem__(self, key):
365 return self.data[str(key)]
366 def __setitem__(self, key, value):
367 self.data[str(key)] = value
368 def __delitem__(self, key):
369 del self.data[str(key)]
370 def __contains__(self, key):
371 return str(key) in self.data
372 d = str_map()
373 # Index
374 d[1] = 1
375 self.assertEqual(d[1], 1)
376 d[1] += 1
377 self.assertEqual(d[1], 2)
378 del d[1]
379 self.assertNotIn(1, d)
380 # Tuple of indices
381 d[1, 1] = 1
382 self.assertEqual(d[1, 1], 1)
383 d[1, 1] += 1
384 self.assertEqual(d[1, 1], 2)
385 del d[1, 1]
386 self.assertNotIn((1, 1), d)
387 # Simple slice
388 d[1:2] = 1
389 self.assertEqual(d[1:2], 1)
390 d[1:2] += 1
391 self.assertEqual(d[1:2], 2)
392 del d[1:2]
393 self.assertNotIn(slice(1, 2), d)
394 # Tuple of simple slices
395 d[1:2, 1:2] = 1
396 self.assertEqual(d[1:2, 1:2], 1)
397 d[1:2, 1:2] += 1
398 self.assertEqual(d[1:2, 1:2], 2)
399 del d[1:2, 1:2]
400 self.assertNotIn((slice(1, 2), slice(1, 2)), d)
401 # Extended slice
402 d[1:2:3] = 1
403 self.assertEqual(d[1:2:3], 1)
404 d[1:2:3] += 1
405 self.assertEqual(d[1:2:3], 2)
406 del d[1:2:3]
407 self.assertNotIn(slice(1, 2, 3), d)
408 # Tuple of extended slices
409 d[1:2:3, 1:2:3] = 1
410 self.assertEqual(d[1:2:3, 1:2:3], 1)
411 d[1:2:3, 1:2:3] += 1
412 self.assertEqual(d[1:2:3, 1:2:3], 2)
413 del d[1:2:3, 1:2:3]
414 self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
415 # Ellipsis
416 d[...] = 1
417 self.assertEqual(d[...], 1)
418 d[...] += 1
419 self.assertEqual(d[...], 2)
420 del d[...]
421 self.assertNotIn(Ellipsis, d)
422 # Tuple of Ellipses
423 d[..., ...] = 1
424 self.assertEqual(d[..., ...], 1)
425 d[..., ...] += 1
426 self.assertEqual(d[..., ...], 2)
427 del d[..., ...]
428 self.assertNotIn((Ellipsis, Ellipsis), d)
429
430 def test_annotation_limit(self):
431 # more than 255 annotations, should compile ok
432 s = "def f(%s): pass"
433 s %= ', '.join('a%d:%d' % (i,i) for i in range(300))
434 compile(s, '?', 'exec')
435
436 def test_mangling(self):
437 class A:
438 def f():
439 __mangled = 1
440 __not_mangled__ = 2
441 import __mangled_mod
442 import __package__.module
443
444 self.assertIn("_A__mangled", A.f.__code__.co_varnames)
445 self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
446 self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
447 self.assertIn("__package__", A.f.__code__.co_varnames)
448
449 def test_compile_invalid_namedexpr(self):
450 # gh-109351
451 m = ast.Module(
452 body=[
453 ast.Expr(
454 value=ast.ListComp(
455 elt=ast.NamedExpr(
456 target=ast.Constant(value=1),
457 value=ast.Constant(value=3),
458 ),
459 generators=[
460 ast.comprehension(
461 target=ast.Name(id="x", ctx=ast.Store()),
462 iter=ast.Name(id="y", ctx=ast.Load()),
463 ifs=[],
464 is_async=0,
465 )
466 ],
467 )
468 )
469 ],
470 type_ignores=[],
471 )
472
473 with self.assertRaisesRegex(TypeError, "NamedExpr target must be a Name"):
474 compile(ast.fix_missing_locations(m), "<file>", "exec")
475
476 def test_compile_ast(self):
477 fname = __file__
478 if fname.lower().endswith('pyc'):
479 fname = fname[:-1]
480 with open(fname, encoding='utf-8') as f:
481 fcontents = f.read()
482 sample_code = [
483 ['<assign>', 'x = 5'],
484 ['<ifblock>', """if True:\n pass\n"""],
485 ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
486 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
487 [fname, fcontents],
488 ]
489
490 for fname, code in sample_code:
491 co1 = compile(code, '%s1' % fname, 'exec')
492 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
493 self.assertTrue(type(ast) == _ast.Module)
494 co2 = compile(ast, '%s3' % fname, 'exec')
495 self.assertEqual(co1, co2)
496 # the code object's filename comes from the second compilation step
497 self.assertEqual(co2.co_filename, '%s3' % fname)
498
499 # raise exception when node type doesn't match with compile mode
500 co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
501 self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
502
503 # raise exception when node type is no start node
504 self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
505
506 # raise exception when node has invalid children
507 ast = _ast.Module()
508 ast.body = [_ast.BoolOp()]
509 self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
510
511 def test_dict_evaluation_order(self):
512 i = 0
513
514 def f():
515 nonlocal i
516 i += 1
517 return i
518
519 d = {f(): f(), f(): f()}
520 self.assertEqual(d, {1: 2, 3: 4})
521
522 def test_compile_filename(self):
523 for filename in 'file.py', b'file.py':
524 code = compile('pass', filename, 'exec')
525 self.assertEqual(code.co_filename, 'file.py')
526 for filename in bytearray(b'file.py'), memoryview(b'file.py'):
527 with self.assertWarns(DeprecationWarning):
528 code = compile('pass', filename, 'exec')
529 self.assertEqual(code.co_filename, 'file.py')
530 self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
531
532 @support.cpython_only
533 def test_same_filename_used(self):
534 s = """def f(): pass\ndef g(): pass"""
535 c = compile(s, "myfile", "exec")
536 for obj in c.co_consts:
537 if isinstance(obj, types.CodeType):
538 self.assertIs(obj.co_filename, c.co_filename)
539
540 def test_single_statement(self):
541 self.compile_single("1 + 2")
542 self.compile_single("\n1 + 2")
543 self.compile_single("1 + 2\n")
544 self.compile_single("1 + 2\n\n")
545 self.compile_single("1 + 2\t\t\n")
546 self.compile_single("1 + 2\t\t\n ")
547 self.compile_single("1 + 2 # one plus two")
548 self.compile_single("1; 2")
549 self.compile_single("import sys; sys")
550 self.compile_single("def f():\n pass")
551 self.compile_single("while False:\n pass")
552 self.compile_single("if x:\n f(x)")
553 self.compile_single("if x:\n f(x)\nelse:\n g(x)")
554 self.compile_single("class T:\n pass")
555 self.compile_single("c = '''\na=1\nb=2\nc=3\n'''")
556
557 def test_bad_single_statement(self):
558 self.assertInvalidSingle('1\n2')
559 if sys.implementation.name != 'pypy':
560 # PyPy's single-mode compiler accepts inline compound statements
561 # (e.g. 'def f(): pass'), which also makes its REPL execute them
562 # immediately rather than prompting for a continuation line.
563 # This is a known behavioral difference from CPython.
564 self.assertInvalidSingle('def f(): pass')
565 self.assertInvalidSingle('a = 13\nb = 187')
566 self.assertInvalidSingle('del x\ndel y')
567 self.assertInvalidSingle('f()\ng()')
568 self.assertInvalidSingle('f()\n# blah\nblah()')
569 self.assertInvalidSingle('f()\nxy # blah\nblah()')
570 self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
571 self.assertInvalidSingle("c = '''\nd=1\n'''\na = 1\n\nb = 2\n")
572
573 def test_particularly_evil_undecodable(self):
574 # Issue 24022
575 src = b'0000\x00\n00000000000\n\x00\n\x9e\n'
576 with tempfile.TemporaryDirectory() as tmpd:
577 fn = os.path.join(tmpd, "bad.py")
578 with open(fn, "wb") as fp:
579 fp.write(src)
580 res = script_helper.run_python_until_end(fn)[0]
581 self.assertIn(b"source code cannot contain null bytes", res.err)
582
583 def test_yet_more_evil_still_undecodable(self):
584 # Issue #25388
585 src = b"#\x00\n#\xfd\n"
586 with tempfile.TemporaryDirectory() as tmpd:
587 fn = os.path.join(tmpd, "bad.py")
588 with open(fn, "wb") as fp:
589 fp.write(src)
590 res = script_helper.run_python_until_end(fn)[0]
591 self.assertIn(b"source code cannot contain null bytes", res.err)
592
593 @support.cpython_only
594 def test_compiler_recursion_limit(self):
595 # Expected limit is sys.getrecursionlimit() * the scaling factor
596 # in symtable.c (currently 3)
597 # We expect to fail *at* that limit, because we use up some of
598 # the stack depth limit in the test suite code
599 # So we check the expected limit and 75% of that
600 # XXX (ncoghlan): duplicating the scaling factor here is a little
601 # ugly. Perhaps it should be exposed somewhere...
602 fail_depth = sys.getrecursionlimit() * 3
603 crash_depth = sys.getrecursionlimit() * 300
604 success_depth = int(fail_depth * 0.75)
605
606 def check_limit(prefix, repeated, mode="single"):
607 expect_ok = prefix + repeated * success_depth
608 compile(expect_ok, '<test>', mode)
609 for depth in (fail_depth, crash_depth):
610 broken = prefix + repeated * depth
611 details = "Compiling ({!r} + {!r} * {})".format(
612 prefix, repeated, depth)
613 with self.assertRaises(RecursionError, msg=details):
614 compile(broken, '<test>', mode)
615
616 check_limit("a", "()")
617 check_limit("a", ".b")
618 check_limit("a", "[0]")
619 check_limit("a", "*a")
620 # XXX Crashes in the parser.
621 # check_limit("a", " if a else a")
622 # check_limit("if a: pass", "\nelif a: pass", mode="exec")
623
624 def test_null_terminated(self):
625 # The source code is null-terminated internally, but bytes-like
626 # objects are accepted, which could be not terminated.
627 with self.assertRaisesRegex(SyntaxError, "cannot contain null"):
628 compile("123\x00", "<dummy>", "eval")
629 with self.assertRaisesRegex(SyntaxError, "cannot contain null"):
630 compile(memoryview(b"123\x00"), "<dummy>", "eval")
631 code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
632 self.assertEqual(eval(code), 23)
633 code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval")
634 self.assertEqual(eval(code), 23)
635 code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval")
636 self.assertEqual(eval(code), 23)
637
638 # Also test when eval() and exec() do the compilation step
639 self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23)
640 namespace = dict()
641 exec(memoryview(b"ax = 123")[1:-1], namespace)
642 self.assertEqual(namespace['x'], 12)
643
644 def check_constant(self, func, expected):
645 for const in func.__code__.co_consts:
646 if repr(const) == repr(expected):
647 break
648 else:
649 self.fail("unable to find constant %r in %r"
650 % (expected, func.__code__.co_consts))
651
652 # Merging equal constants is not a strict requirement for the Python
653 # semantics, it's a more an implementation detail.
654 @support.cpython_only
655 def test_merge_constants(self):
656 # Issue #25843: compile() must merge constants which are equal
657 # and have the same type.
658
659 def check_same_constant(const):
660 ns = {}
661 code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
662 exec(code, ns)
663 f1 = ns['f1']
664 f2 = ns['f2']
665 self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
666 self.check_constant(f1, const)
667 self.assertEqual(repr(f1()), repr(const))
668
669 check_same_constant(None)
670 check_same_constant(0)
671 check_same_constant(0.0)
672 check_same_constant(b'abc')
673 check_same_constant('abc')
674
675 # Note: "lambda: ..." emits "LOAD_CONST Ellipsis",
676 # whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis"
677 f1, f2 = lambda: ..., lambda: ...
678 self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
679 self.check_constant(f1, Ellipsis)
680 self.assertEqual(repr(f1()), repr(Ellipsis))
681
682 # Merge constants in tuple or frozenset
683 f1, f2 = lambda: "not a name", lambda: ("not a name",)
684 f3 = lambda x: x in {("not a name",)}
685 self.assertIs(f1.__code__.co_consts[1],
686 f2.__code__.co_consts[1][0])
687 self.assertIs(next(iter(f3.__code__.co_consts[1])),
688 f2.__code__.co_consts[1])
689
690 # {0} is converted to a constant frozenset({0}) by the peephole
691 # optimizer
692 f1, f2 = lambda x: x in {0}, lambda x: x in {0}
693 self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
694 self.check_constant(f1, frozenset({0}))
695 self.assertTrue(f1(0))
696
697 # Merging equal co_linetable is not a strict requirement
698 # for the Python semantics, it's a more an implementation detail.
699 @support.cpython_only
700 def test_merge_code_attrs(self):
701 # See https://bugs.python.org/issue42217
702 f1 = lambda x: x.y.z
703 f2 = lambda a: a.b.c
704
705 self.assertIs(f1.__code__.co_linetable, f2.__code__.co_linetable)
706
707 # Stripping unused constants is not a strict requirement for the
708 # Python semantics, it's a more an implementation detail.
709 @support.cpython_only
710 def test_strip_unused_consts(self):
711 # Python 3.10rc1 appended None to co_consts when None is not used
712 # at all. See bpo-45056.
713 def f1():
714 "docstring"
715 return 42
716 self.assertEqual(f1.__code__.co_consts, (f1.__doc__, 42))
717
718 # This is a regression test for a CPython specific peephole optimizer
719 # implementation bug present in a few releases. It's assertion verifies
720 # that peephole optimization was actually done though that isn't an
721 # indication of the bugs presence or not (crashing is).
722 @support.cpython_only
723 def test_peephole_opt_unreachable_code_array_access_in_bounds(self):
724 """Regression test for issue35193 when run under clang msan."""
725 def unused_code_at_end():
726 return 3
727 raise RuntimeError("unreachable")
728 # The above function definition will trigger the out of bounds
729 # bug in the peephole optimizer as it scans opcodes past the
730 # RETURN_VALUE opcode. This does not always crash an interpreter.
731 # When you build with the clang memory sanitizer it reliably aborts.
732 self.assertEqual(
733 'RETURN_VALUE',
734 list(dis.get_instructions(unused_code_at_end))[-1].opname)
735
736 def test_dont_merge_constants(self):
737 # Issue #25843: compile() must not merge constants which are equal
738 # but have a different type.
739
740 def check_different_constants(const1, const2):
741 ns = {}
742 exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
743 f1 = ns['f1']
744 f2 = ns['f2']
745 self.assertIsNot(f1.__code__, f2.__code__)
746 self.assertNotEqual(f1.__code__, f2.__code__)
747 self.check_constant(f1, const1)
748 self.check_constant(f2, const2)
749 self.assertEqual(repr(f1()), repr(const1))
750 self.assertEqual(repr(f2()), repr(const2))
751
752 check_different_constants(0, 0.0)
753 check_different_constants(+0.0, -0.0)
754 check_different_constants((0,), (0.0,))
755 check_different_constants('a', b'a')
756 check_different_constants(('a',), (b'a',))
757
758 # check_different_constants() cannot be used because repr(-0j) is
759 # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
760 f1, f2 = lambda: +0.0j, lambda: -0.0j
761 self.assertIsNot(f1.__code__, f2.__code__)
762 self.check_constant(f1, +0.0j)
763 self.check_constant(f2, -0.0j)
764 self.assertEqual(repr(f1()), repr(+0.0j))
765 self.assertEqual(repr(f2()), repr(-0.0j))
766
767 # {0} is converted to a constant frozenset({0}) by the peephole
768 # optimizer
769 f1, f2 = lambda x: x in {0}, lambda x: x in {0.0}
770 self.assertIsNot(f1.__code__, f2.__code__)
771 self.check_constant(f1, frozenset({0}))
772 self.check_constant(f2, frozenset({0.0}))
773 self.assertTrue(f1(0))
774 self.assertTrue(f2(0.0))
775
776 def test_path_like_objects(self):
777 # An implicit test for PyUnicode_FSDecoder().
778 compile("42", FakePath("test_compile_pathlike"), "single")
779
780 @support.requires_resource('cpu')
781 def test_stack_overflow(self):
782 # bpo-31113: Stack overflow when compile a long sequence of
783 # complex statements.
784 compile("if a: b\n" * 200000, "<dummy>", "exec")
785
786 # Multiple users rely on the fact that CPython does not generate
787 # bytecode for dead code blocks. See bpo-37500 for more context.
788 @support.cpython_only
789 def test_dead_blocks_do_not_generate_bytecode(self):
790 def unused_block_if():
791 if 0:
792 return 42
793
794 def unused_block_while():
795 while 0:
796 return 42
797
798 def unused_block_if_else():
799 if 1:
800 return None
801 else:
802 return 42
803
804 def unused_block_while_else():
805 while 1:
806 return None
807 else:
808 return 42
809
810 funcs = [unused_block_if, unused_block_while,
811 unused_block_if_else, unused_block_while_else]
812
813 for func in funcs:
814 opcodes = list(dis.get_instructions(func))
815 self.assertLessEqual(len(opcodes), 4)
816 self.assertEqual('LOAD_CONST', opcodes[-2].opname)
817 self.assertEqual(None, opcodes[-2].argval)
818 self.assertEqual('RETURN_VALUE', opcodes[-1].opname)
819
820 def test_false_while_loop(self):
821 def break_in_while():
822 while False:
823 break
824
825 def continue_in_while():
826 while False:
827 continue
828
829 funcs = [break_in_while, continue_in_while]
830
831 # Check that we did not raise but we also don't generate bytecode
832 for func in funcs:
833 opcodes = list(dis.get_instructions(func))
834 if sys.implementation.name == 'pypy':
835 # PyPy omits the RESUME opcode that CPython 3.11 emits at
836 # function entry, so there are 2 opcodes instead of 3.
837 self.assertEqual(2, len(opcodes))
838 self.assertEqual('LOAD_CONST', opcodes[0].opname)
839 self.assertEqual(None, opcodes[0].argval)
840 self.assertEqual('RETURN_VALUE', opcodes[1].opname)
841 else:
842 self.assertEqual(3, len(opcodes))
843 self.assertEqual('LOAD_CONST', opcodes[1].opname)
844 self.assertEqual(None, opcodes[1].argval)
845 self.assertEqual('RETURN_VALUE', opcodes[2].opname)
846
847 def test_consts_in_conditionals(self):
848 def and_true(x):
849 return True and x
850
851 def and_false(x):
852 return False and x
853
854 def or_true(x):
855 return True or x
856
857 def or_false(x):
858 return False or x
859
860 funcs = [and_true, and_false, or_true, or_false]
861
862 # Check that condition is removed.
863 for func in funcs:
864 with self.subTest(func=func):
865 opcodes = list(dis.get_instructions(func))
866 self.assertLessEqual(len(opcodes), 3)
867 self.assertIn('LOAD_', opcodes[-2].opname)
868 self.assertEqual('RETURN_VALUE', opcodes[-1].opname)
869
870 def test_imported_load_method(self):
871 sources = [
872 """\
873 import os
874 def foo():
875 return os.uname()
876 """,
877 """\
878 import os as operating_system
879 def foo():
880 return operating_system.uname()
881 """,
882 """\
883 from os import path
884 def foo(x):
885 return path.join(x)
886 """,
887 """\
888 from os import path as os_path
889 def foo(x):
890 return os_path.join(x)
891 """
892 ]
893 for source in sources:
894 namespace = {}
895 exec(textwrap.dedent(source), namespace)
896 func = namespace['foo']
897 with self.subTest(func=func.__name__):
898 opcodes = list(dis.get_instructions(func))
899 instructions = [opcode.opname for opcode in opcodes]
900 if sys.implementation.name == 'pypy':
901 # PyPy still uses LOAD_METHOD + CALL_METHOD for attribute calls.
902 self.assertIn('LOAD_METHOD', instructions)
903 self.assertIn('CALL_METHOD', instructions)
904 self.assertNotIn('PRECALL', instructions)
905 else:
906 self.assertNotIn('LOAD_METHOD', instructions)
907 self.assertIn('LOAD_ATTR', instructions)
908 self.assertIn('PRECALL', instructions)
909
910 def test_lineno_procedure_call(self):
911 def call():
912 (
913 print()
914 )
915 line1 = call.__code__.co_firstlineno + 1
916 assert line1 not in [line for (_, _, line) in call.__code__.co_lines()]
917
918 def test_lineno_after_implicit_return(self):
919 TRUE = True
920 # Don't use constant True or False, as compiler will remove test
921 def if1(x):
922 x()
923 if TRUE:
924 pass
925 def if2(x):
926 x()
927 if TRUE:
928 pass
929 else:
930 pass
931 def if3(x):
932 x()
933 if TRUE:
934 pass
935 else:
936 return None
937 def if4(x):
938 x()
939 if not TRUE:
940 pass
941 funcs = [ if1, if2, if3, if4]
942 lastlines = [ 3, 3, 3, 2]
943 frame = None
944 def save_caller_frame():
945 nonlocal frame
946 frame = sys._getframe(1)
947 for func, lastline in zip(funcs, lastlines, strict=True):
948 with self.subTest(func=func):
949 func(save_caller_frame)
950 self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, lastline)
951
952 def test_lineno_after_no_code(self):
953 def no_code1():
954 "doc string"
955
956 def no_code2():
957 a: int
958
959 for func in (no_code1, no_code2):
960 with self.subTest(func=func):
961 if func is no_code1 and no_code1.__doc__ is None:
962 continue
963 code = func.__code__
964 lines = list(code.co_lines())
965 start, end, line = lines[0]
966 self.assertEqual(start, 0)
967 self.assertEqual(line, code.co_firstlineno)
968
969 def get_code_lines(self, code):
970 last_line = -2
971 res = []
972 for _, _, line in code.co_lines():
973 if line is not None and line != last_line:
974 res.append(line - code.co_firstlineno)
975 last_line = line
976 return res
977
978 def test_lineno_attribute(self):
979 def load_attr():
980 return (
981 o.
982 a
983 )
984 if sys.implementation.name == 'pypy':
985 load_attr_lines = [ 2, 3, 1 ]
986 else:
987 load_attr_lines = [ 0, 2, 3, 1 ]
988
989 def load_method():
990 return (
991 o.
992 m(
993 0
994 )
995 )
996 if sys.implementation.name == 'pypy':
997 load_method_lines = [ 2, 3, 4, 3, 1 ]
998 else:
999 load_method_lines = [ 0, 2, 3, 4, 3, 1 ]
1000
1001 def store_attr():
1002 (
1003 o.
1004 a
1005 ) = (
1006 v
1007 )
1008 if sys.implementation.name == 'pypy':
1009 store_attr_lines = [ 5, 2, 3 ]
1010 else:
1011 store_attr_lines = [ 0, 5, 2, 3 ]
1012
1013 def aug_store_attr():
1014 (
1015 o.
1016 a
1017 ) += (
1018 v
1019 )
1020 if sys.implementation.name == 'pypy':
1021 # PyPy's DUP_TOP for augmented attr assignment is emitted before
1022 # LOAD_ATTR (picking up the target's opening-paren line), whereas
1023 # CPython's equivalent instruction appears later, after loading v.
1024 aug_store_attr_lines = [ 2, 1, 3, 5, 3 ]
1025 else:
1026 aug_store_attr_lines = [ 0, 2, 3, 5, 1, 3 ]
1027
1028 funcs = [ load_attr, load_method, store_attr, aug_store_attr]
1029 func_lines = [ load_attr_lines, load_method_lines,
1030 store_attr_lines, aug_store_attr_lines]
1031
1032 for func, lines in zip(funcs, func_lines, strict=True):
1033 with self.subTest(func=func):
1034 code_lines = self.get_code_lines(func.__code__)
1035 self.assertEqual(lines, code_lines)
1036
1037 def test_line_number_genexp(self):
1038
1039 def return_genexp():
1040 return (1
1041 for
1042 x
1043 in
1044 y)
1045 genexp_lines = [0, 2, 0]
1046
1047 genexp_code = return_genexp.__code__.co_consts[1]
1048 code_lines = self.get_code_lines(genexp_code)
1049 self.assertEqual(genexp_lines, code_lines)
1050
1051 def test_line_number_implicit_return_after_async_for(self):
1052
1053 async def test(aseq):
1054 async for i in aseq:
1055 body
1056
1057 if sys.implementation.name == 'pypy':
1058 expected_lines = [1, 2, 1]
1059 else:
1060 expected_lines = [0, 1, 2, 1]
1061 code_lines = self.get_code_lines(test.__code__)
1062 self.assertEqual(expected_lines, code_lines)
1063
1064 def test_big_dict_literal(self):
1065 # The compiler has a flushing point in "compiler_dict" that calls compiles
1066 # a portion of the dictionary literal when the loop that iterates over the items
1067 # reaches 0xFFFF elements but the code was not including the boundary element,
1068 # dropping the key at position 0xFFFF. See bpo-41531 for more information
1069
1070 dict_size = 0xFFFF + 1
1071 the_dict = "{" + ",".join(f"{x}:{x}" for x in range(dict_size)) + "}"
1072 self.assertEqual(len(eval(the_dict)), dict_size)
1073
1074 def test_redundant_jump_in_if_else_break(self):
1075 # Check if bytecode containing jumps that simply point to the next line
1076 # is generated around if-else-break style structures. See bpo-42615.
1077
1078 def if_else_break():
1079 val = 1
1080 while True:
1081 if val > 0:
1082 val -= 1
1083 else:
1084 break
1085 val = -1
1086
1087 INSTR_SIZE = 2
1088 HANDLED_JUMPS = (
1089 'POP_JUMP_IF_FALSE',
1090 'POP_JUMP_IF_TRUE',
1091 'JUMP_ABSOLUTE',
1092 'JUMP_FORWARD',
1093 )
1094
1095 for line, instr in enumerate(
1096 dis.Bytecode(if_else_break, show_caches=True)
1097 ):
1098 if instr.opname == 'JUMP_FORWARD':
1099 self.assertNotEqual(instr.arg, 0)
1100 elif instr.opname in HANDLED_JUMPS:
1101 self.assertNotEqual(instr.arg, (line + 1)*INSTR_SIZE)
1102
1103 def test_no_wraparound_jump(self):
1104 # See https://bugs.python.org/issue46724
1105
1106 def while_not_chained(a, b, c):
1107 while not (a < b < c):
1108 pass
1109
1110 for instr in dis.Bytecode(while_not_chained):
1111 self.assertNotEqual(instr.opname, "EXTENDED_ARG")
1112
1113 def test_compare_positions(self):
1114 for opname, op in [
1115 ("COMPARE_OP", "<"),
1116 ("COMPARE_OP", "<="),
1117 ("COMPARE_OP", ">"),
1118 ("COMPARE_OP", ">="),
1119 ("CONTAINS_OP", "in"),
1120 ("CONTAINS_OP", "not in"),
1121 ("IS_OP", "is"),
1122 ("IS_OP", "is not"),
1123 ]:
1124 expr = f'a {op} b {op} c'
1125 expected_positions = 2 * [(2, 2, 0, len(expr))]
1126 for source in [
1127 f"\\\n{expr}", f'if \\\n{expr}: x', f"x if \\\n{expr} else y"
1128 ]:
1129 code = compile(source, "<test>", "exec")
1130 actual_positions = [
1131 instruction.positions
1132 for instruction in dis.get_instructions(code)
1133 if instruction.opname == opname
1134 ]
1135 with self.subTest(source):
1136 self.assertEqual(actual_positions, expected_positions)
1137
1138 def test_apply_static_swaps(self):
1139 def f(x, y):
1140 a, a = x, y
1141 return a
1142 self.assertEqual(f("x", "y"), "y")
1143
1144 def test_apply_static_swaps_2(self):
1145 def f(x, y, z):
1146 a, b, a = x, y, z
1147 return a
1148 self.assertEqual(f("x", "y", "z"), "z")
1149
1150 def test_apply_static_swaps_3(self):
1151 def f(x, y, z):
1152 a, a, b = x, y, z
1153 return a
1154 self.assertEqual(f("x", "y", "z"), "y")
1155
1156
1157 @requires_debug_ranges()
1158 class TestSourcePositions(unittest.TestCase):
1159 # Ensure that compiled code snippets have correct line and column numbers
1160 # in `co_positions()`.
1161
1162 def check_positions_against_ast(self, snippet):
1163 # Basic check that makes sure each line and column is at least present
1164 # in one of the AST nodes of the source code.
1165 code = compile(snippet, 'test_compile.py', 'exec')
1166 ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST)
1167 self.assertTrue(type(ast_tree) == _ast.Module)
1168
1169 # Use an AST visitor that notes all the offsets.
1170 lines, end_lines, columns, end_columns = set(), set(), set(), set()
1171 class SourceOffsetVisitor(ast.NodeVisitor):
1172 def generic_visit(self, node):
1173 super().generic_visit(node)
1174 if not isinstance(node, ast.expr) and not isinstance(node, ast.stmt):
1175 return
1176 lines.add(node.lineno)
1177 end_lines.add(node.end_lineno)
1178 columns.add(node.col_offset)
1179 end_columns.add(node.end_col_offset)
1180
1181 SourceOffsetVisitor().visit(ast_tree)
1182
1183 # Check against the positions in the code object.
1184 for (line, end_line, col, end_col) in code.co_positions():
1185 if line == 0:
1186 continue # This is an artificial module-start line
1187 # If the offset is not None (indicating missing data), ensure that
1188 # it was part of one of the AST nodes.
1189 if line is not None:
1190 self.assertIn(line, lines)
1191 if end_line is not None:
1192 self.assertIn(end_line, end_lines)
1193 if col is not None:
1194 self.assertIn(col, columns)
1195 if end_col is not None:
1196 self.assertIn(end_col, end_columns)
1197
1198 return code, ast_tree
1199
1200 def assertOpcodeSourcePositionIs(self, code, opcode,
1201 line, end_line, column, end_column, occurrence=1):
1202
1203 for instr, position in zip(
1204 dis.Bytecode(code, show_caches=True), code.co_positions(), strict=True
1205 ):
1206 if instr.opname == opcode:
1207 occurrence -= 1
1208 if not occurrence:
1209 self.assertEqual(position[0], line)
1210 self.assertEqual(position[1], end_line)
1211 self.assertEqual(position[2], column)
1212 self.assertEqual(position[3], end_column)
1213 return
1214
1215 self.fail(f"Opcode {opcode} not found in code")
1216
1217 def test_simple_assignment(self):
1218 snippet = "x = 1"
1219 self.check_positions_against_ast(snippet)
1220
1221 def test_compiles_to_extended_op_arg(self):
1222 # Make sure we still have valid positions when the code compiles to an
1223 # EXTENDED_ARG by performing a loop which needs a JUMP_ABSOLUTE after
1224 # a bunch of opcodes.
1225 snippet = "x = x\n" * 10_000
1226 snippet += ("while x != 0:\n"
1227 " x -= 1\n"
1228 "while x != 0:\n"
1229 " x += 1\n"
1230 )
1231
1232 compiled_code, _ = self.check_positions_against_ast(snippet)
1233
1234 # PyPy uses specific opcodes; CPython 3.11 uses the generic BINARY_OP.
1235 if sys.implementation.name == 'pypy':
1236 sub_opcode, add_opcode, add_occurrence = 'INPLACE_SUBTRACT', 'INPLACE_ADD', 1
1237 else:
1238 sub_opcode, add_opcode, add_occurrence = 'BINARY_OP', 'BINARY_OP', 2
1239 self.assertOpcodeSourcePositionIs(compiled_code, sub_opcode,
1240 line=10_000 + 2, end_line=10_000 + 2,
1241 column=2, end_column=8, occurrence=1)
1242 self.assertOpcodeSourcePositionIs(compiled_code, add_opcode,
1243 line=10_000 + 4, end_line=10_000 + 4,
1244 column=2, end_column=9, occurrence=add_occurrence)
1245
1246 def test_multiline_expression(self):
1247 snippet = """\
1248 f(
1249 1, 2, 3, 4
1250 )
1251 """
1252 compiled_code, _ = self.check_positions_against_ast(snippet)
1253 call_opcode = 'CALL_FUNCTION' if sys.implementation.name == 'pypy' else 'CALL'
1254 self.assertOpcodeSourcePositionIs(compiled_code, call_opcode,
1255 line=1, end_line=3, column=0, end_column=1)
1256
1257 def test_very_long_line_end_offset(self):
1258 # Make sure we get the correct column offset for offsets
1259 # too large to store in a byte.
1260 long_string = "a" * 1000
1261 snippet = f"g('{long_string}')"
1262
1263 compiled_code, _ = self.check_positions_against_ast(snippet)
1264 if sys.implementation.name == 'pypy':
1265 # PyPy cannot represent column offsets beyond its storage limit and
1266 # returns None for end_line/column/end_column in that case.
1267 call_opcode = 'CALL_FUNCTION'
1268 call_end_line, call_col, call_end_col = None, None, None
1269 else:
1270 call_opcode = 'CALL'
1271 call_end_line, call_col, call_end_col = 1, 0, 1005
1272 self.assertOpcodeSourcePositionIs(compiled_code, call_opcode,
1273 line=1, end_line=call_end_line, column=call_col, end_column=call_end_col)
1274
1275 def test_complex_single_line_expression(self):
1276 snippet = "a - b @ (c * x['key'] + 23)"
1277
1278 compiled_code, _ = self.check_positions_against_ast(snippet)
1279 self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_SUBSCR',
1280 line=1, end_line=1, column=13, end_column=21)
1281 # PyPy uses specific opcodes; CPython 3.11 folds all binary ops into BINARY_OP.
1282 # The expression is: a - b @ (c * x['key'] + 23)
1283 if sys.implementation.name == 'pypy':
1284 mul_op, add_op, mat_op, sub_op = ('BINARY_MULTIPLY', 'BINARY_ADD',
1285 'BINARY_MATRIX_MULTIPLY', 'BINARY_SUBTRACT')
1286 mul_occ = add_occ = mat_occ = sub_occ = 1
1287 else:
1288 mul_op = add_op = mat_op = sub_op = 'BINARY_OP'
1289 mul_occ, add_occ, mat_occ, sub_occ = 1, 2, 3, 4
1290 self.assertOpcodeSourcePositionIs(compiled_code, mul_op,
1291 line=1, end_line=1, column=9, end_column=21, occurrence=mul_occ)
1292 self.assertOpcodeSourcePositionIs(compiled_code, add_op,
1293 line=1, end_line=1, column=9, end_column=26, occurrence=add_occ)
1294 self.assertOpcodeSourcePositionIs(compiled_code, mat_op,
1295 line=1, end_line=1, column=4, end_column=27, occurrence=mat_occ)
1296 self.assertOpcodeSourcePositionIs(compiled_code, sub_op,
1297 line=1, end_line=1, column=0, end_column=27, occurrence=sub_occ)
1298
1299 def test_multiline_assert_rewritten_as_method_call(self):
1300 # GH-94694: Don't crash if pytest rewrites a multiline assert as a
1301 # method call with the same location information:
1302 tree = ast.parse("assert (\n42\n)")
1303 old_node = tree.body[0]
1304 new_node = ast.Expr(
1305 ast.Call(
1306 ast.Attribute(
1307 ast.Name("spam", ast.Load()),
1308 "eggs",
1309 ast.Load(),
1310 ),
1311 [],
1312 [],
1313 )
1314 )
1315 ast.copy_location(new_node, old_node)
1316 ast.fix_missing_locations(new_node)
1317 tree.body[0] = new_node
1318 compile(tree, "<test>", "exec")
1319
1320 def test_push_null_load_global_positions(self):
1321 source_template = """
1322 import abc, dis
1323 import ast as art
1324
1325 abc = None
1326 dix = dis
1327 ast = art
1328
1329 def f():
1330 {}
1331 """
1332 for body in [
1333 " abc.a()",
1334 " art.a()",
1335 " ast.a()",
1336 " dis.a()",
1337 " dix.a()",
1338 " abc[...]()",
1339 " art()()",
1340 " (ast or ...)()",
1341 " [dis]()",
1342 " (dix + ...)()",
1343 ]:
1344 with self.subTest(body):
1345 namespace = {}
1346 source = textwrap.dedent(source_template.format(body))
1347 exec(source, namespace)
1348 code = namespace["f"].__code__
1349 self.assertOpcodeSourcePositionIs(
1350 code,
1351 "LOAD_GLOBAL",
1352 line=10,
1353 end_line=10,
1354 column=4,
1355 end_column=7,
1356 )
1357
1358 def test_attribute_augassign(self):
1359 source = "(\n lhs \n . \n rhs \n ) += 42"
1360 code = compile(source, "<test>", "exec")
1361 self.assertOpcodeSourcePositionIs(
1362 code, "LOAD_ATTR", line=4, end_line=4, column=5, end_column=8
1363 )
1364 self.assertOpcodeSourcePositionIs(
1365 code, "STORE_ATTR", line=4, end_line=4, column=5, end_column=8
1366 )
1367
1368 def test_attribute_del(self):
1369 source = "del (\n lhs \n . \n rhs \n )"
1370 code = compile(source, "<test>", "exec")
1371 self.assertOpcodeSourcePositionIs(
1372 code, "DELETE_ATTR", line=4, end_line=4, column=5, end_column=8
1373 )
1374
1375 def test_attribute_load(self):
1376 source = "(\n lhs \n . \n rhs \n )"
1377 code = compile(source, "<test>", "exec")
1378 self.assertOpcodeSourcePositionIs(
1379 code, "LOAD_ATTR", line=4, end_line=4, column=5, end_column=8
1380 )
1381
1382 def test_attribute_store(self):
1383 source = "(\n lhs \n . \n rhs \n ) = 42"
1384 code = compile(source, "<test>", "exec")
1385 self.assertOpcodeSourcePositionIs(
1386 code, "STORE_ATTR", line=4, end_line=4, column=5, end_column=8
1387 )
1388
1389 def test_method_call(self):
1390 source = "(\n lhs \n . \n rhs \n )()"
1391 code = compile(source, "<test>", "exec")
1392 self.assertOpcodeSourcePositionIs(
1393 code, "LOAD_METHOD", line=4, end_line=4, column=5, end_column=8
1394 )
1395 if sys.implementation.name == 'pypy':
1396 # PyPy assigns CALL_METHOD the position of the attribute access
1397 # (same as LOAD_METHOD), not the full call expression span.
1398 call_opcode, call_end_line, call_end_col = 'CALL_METHOD', 4, 8
1399 else:
1400 call_opcode, call_end_line, call_end_col = 'CALL', 5, 10
1401 self.assertOpcodeSourcePositionIs(
1402 code, call_opcode, line=4, end_line=call_end_line, column=5, end_column=call_end_col
1403 )
1404
1405 def test_weird_attribute_position_regressions(self):
1406 def f():
1407 (bar.
1408 baz)
1409 (bar.
1410 baz(
1411 ))
1412 files().setdefault(
1413 0
1414 ).setdefault(
1415 0
1416 )
1417 for line, end_line, column, end_column in f.__code__.co_positions():
1418 self.assertIsNotNone(line)
1419 self.assertIsNotNone(end_line)
1420 self.assertIsNotNone(column)
1421 self.assertIsNotNone(end_column)
1422 self.assertLessEqual((line, column), (end_line, end_column))
1423
1424 @support.cpython_only
1425 def test_column_offset_deduplication(self):
1426 # GH-95150: Code with different column offsets shouldn't be merged!
1427 for source in [
1428 "lambda: a",
1429 "(a for b in c)",
1430 "[a for b in c]",
1431 "{a for b in c}",
1432 "{a: b for c in d}",
1433 ]:
1434 with self.subTest(source):
1435 code = compile(f"{source}, {source}", "<test>", "eval")
1436 self.assertEqual(len(code.co_consts), 2)
1437 self.assertIsInstance(code.co_consts[0], types.CodeType)
1438 self.assertIsInstance(code.co_consts[1], types.CodeType)
1439 self.assertNotEqual(code.co_consts[0], code.co_consts[1])
1440 self.assertNotEqual(
1441 list(code.co_consts[0].co_positions()),
1442 list(code.co_consts[1].co_positions()),
1443 )
1444
1445
1446 class TestExpressionStackSize(unittest.TestCase):
1447 # These tests check that the computed stack size for a code object
1448 # stays within reasonable bounds (see issue #21523 for an example
1449 # dysfunction).
1450 N = 100
1451
1452 def check_stack_size(self, code):
1453 # To assert that the alleged stack size is not O(N), we
1454 # check that it is smaller than log(N).
1455 if isinstance(code, str):
1456 code = compile(code, "<foo>", "single")
1457 if sys.implementation.name == 'pypy':
1458 # PyPy bytecode lacks CPython 3.11 inline caches, so len(co_code)
1459 # is much smaller and log(len(co_code)) is too tight a bound.
1460 # Instead verify the stack size is not pathologically large (> N).
1461 max_size = self.N + 10
1462 else:
1463 max_size = math.ceil(math.log(len(code.co_code)))
1464 self.assertLessEqual(code.co_stacksize, max_size)
1465
1466 def test_and(self):
1467 self.check_stack_size("x and " * self.N + "x")
1468
1469 def test_or(self):
1470 self.check_stack_size("x or " * self.N + "x")
1471
1472 def test_and_or(self):
1473 self.check_stack_size("x and x or " * self.N + "x")
1474
1475 def test_chained_comparison(self):
1476 self.check_stack_size("x < " * self.N + "x")
1477
1478 def test_if_else(self):
1479 self.check_stack_size("x if x else " * self.N + "x")
1480
1481 def test_binop(self):
1482 self.check_stack_size("x + " * self.N + "x")
1483
1484 def test_list(self):
1485 self.check_stack_size("[" + "x, " * self.N + "x]")
1486
1487 def test_tuple(self):
1488 self.check_stack_size("(" + "x, " * self.N + "x)")
1489
1490 def test_set(self):
1491 self.check_stack_size("{" + "x, " * self.N + "x}")
1492
1493 def test_dict(self):
1494 self.check_stack_size("{" + "x:x, " * self.N + "x:x}")
1495
1496 def test_func_args(self):
1497 self.check_stack_size("f(" + "x, " * self.N + ")")
1498
1499 def test_func_kwargs(self):
1500 kwargs = (f'a{i}=x' for i in range(self.N))
1501 self.check_stack_size("f(" + ", ".join(kwargs) + ")")
1502
1503 def test_meth_args(self):
1504 self.check_stack_size("o.m(" + "x, " * self.N + ")")
1505
1506 def test_meth_kwargs(self):
1507 kwargs = (f'a{i}=x' for i in range(self.N))
1508 self.check_stack_size("o.m(" + ", ".join(kwargs) + ")")
1509
1510 def test_func_and(self):
1511 code = "def f(x):\n"
1512 code += " x and x\n" * self.N
1513 self.check_stack_size(code)
1514
1515 def test_stack_3050(self):
1516 M = 3050
1517 code = "x," * M + "=t"
1518 # This raised on 3.10.0 to 3.10.5
1519 compile(code, "<foo>", "single")
1520
1521 def test_stack_3050_2(self):
1522 M = 3050
1523 args = ", ".join(f"arg{i}:type{i}" for i in range(M))
1524 code = f"def f({args}):\n pass"
1525 # This raised on 3.10.0 to 3.10.5
1526 compile(code, "<foo>", "single")
1527
1528
1529 class TestStackSizeStability(unittest.TestCase):
1530 # Check that repeating certain snippets doesn't increase the stack size
1531 # beyond what a single snippet requires.
1532
1533 def check_stack_size(self, snippet, async_=False):
1534 def compile_snippet(i):
1535 ns = {}
1536 script = """def func():\n""" + i * snippet
1537 if async_:
1538 script = "async " + script
1539 code = compile(script, "<script>", "exec")
1540 exec(code, ns, ns)
1541 return ns['func'].__code__
1542
1543 sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)]
1544 if len(set(sizes)) != 1:
1545 import dis, io
1546 out = io.StringIO()
1547 dis.dis(compile_snippet(1), file=out)
1548 self.fail("stack sizes diverge with # of consecutive snippets: "
1549 "%s\n%s\n%s" % (sizes, snippet, out.getvalue()))
1550
1551 def test_if(self):
1552 snippet = """
1553 if x:
1554 a
1555 """
1556 self.check_stack_size(snippet)
1557
1558 def test_if_else(self):
1559 snippet = """
1560 if x:
1561 a
1562 elif y:
1563 b
1564 else:
1565 c
1566 """
1567 self.check_stack_size(snippet)
1568
1569 def test_try_except_bare(self):
1570 snippet = """
1571 try:
1572 a
1573 except:
1574 b
1575 """
1576 self.check_stack_size(snippet)
1577
1578 def test_try_except_qualified(self):
1579 snippet = """
1580 try:
1581 a
1582 except ImportError:
1583 b
1584 except:
1585 c
1586 else:
1587 d
1588 """
1589 self.check_stack_size(snippet)
1590
1591 def test_try_except_as(self):
1592 snippet = """
1593 try:
1594 a
1595 except ImportError as e:
1596 b
1597 except:
1598 c
1599 else:
1600 d
1601 """
1602 self.check_stack_size(snippet)
1603
1604 def test_try_except_star_qualified(self):
1605 snippet = """
1606 try:
1607 a
1608 except* ImportError:
1609 b
1610 else:
1611 c
1612 """
1613 self.check_stack_size(snippet)
1614
1615 def test_try_except_star_as(self):
1616 snippet = """
1617 try:
1618 a
1619 except* ImportError as e:
1620 b
1621 else:
1622 c
1623 """
1624 self.check_stack_size(snippet)
1625
1626 def test_try_except_star_finally(self):
1627 snippet = """
1628 try:
1629 a
1630 except* A:
1631 b
1632 finally:
1633 c
1634 """
1635 self.check_stack_size(snippet)
1636
1637 def test_try_finally(self):
1638 snippet = """
1639 try:
1640 a
1641 finally:
1642 b
1643 """
1644 self.check_stack_size(snippet)
1645
1646 def test_with(self):
1647 snippet = """
1648 with x as y:
1649 a
1650 """
1651 self.check_stack_size(snippet)
1652
1653 def test_while_else(self):
1654 snippet = """
1655 while x:
1656 a
1657 else:
1658 b
1659 """
1660 self.check_stack_size(snippet)
1661
1662 def test_for(self):
1663 snippet = """
1664 for x in y:
1665 a
1666 """
1667 self.check_stack_size(snippet)
1668
1669 def test_for_else(self):
1670 snippet = """
1671 for x in y:
1672 a
1673 else:
1674 b
1675 """
1676 self.check_stack_size(snippet)
1677
1678 def test_for_break_continue(self):
1679 snippet = """
1680 for x in y:
1681 if z:
1682 break
1683 elif u:
1684 continue
1685 else:
1686 a
1687 else:
1688 b
1689 """
1690 self.check_stack_size(snippet)
1691
1692 def test_for_break_continue_inside_try_finally_block(self):
1693 snippet = """
1694 for x in y:
1695 try:
1696 if z:
1697 break
1698 elif u:
1699 continue
1700 else:
1701 a
1702 finally:
1703 f
1704 else:
1705 b
1706 """
1707 self.check_stack_size(snippet)
1708
1709 def test_for_break_continue_inside_finally_block(self):
1710 snippet = """
1711 for x in y:
1712 try:
1713 t
1714 finally:
1715 if z:
1716 break
1717 elif u:
1718 continue
1719 else:
1720 a
1721 else:
1722 b
1723 """
1724 self.check_stack_size(snippet)
1725
1726 def test_for_break_continue_inside_except_block(self):
1727 snippet = """
1728 for x in y:
1729 try:
1730 t
1731 except:
1732 if z:
1733 break
1734 elif u:
1735 continue
1736 else:
1737 a
1738 else:
1739 b
1740 """
1741 self.check_stack_size(snippet)
1742
1743 def test_for_break_continue_inside_with_block(self):
1744 snippet = """
1745 for x in y:
1746 with c:
1747 if z:
1748 break
1749 elif u:
1750 continue
1751 else:
1752 a
1753 else:
1754 b
1755 """
1756 self.check_stack_size(snippet)
1757
1758 def test_return_inside_try_finally_block(self):
1759 snippet = """
1760 try:
1761 if z:
1762 return
1763 else:
1764 a
1765 finally:
1766 f
1767 """
1768 self.check_stack_size(snippet)
1769
1770 def test_return_inside_finally_block(self):
1771 snippet = """
1772 try:
1773 t
1774 finally:
1775 if z:
1776 return
1777 else:
1778 a
1779 """
1780 self.check_stack_size(snippet)
1781
1782 def test_return_inside_except_block(self):
1783 snippet = """
1784 try:
1785 t
1786 except:
1787 if z:
1788 return
1789 else:
1790 a
1791 """
1792 self.check_stack_size(snippet)
1793
1794 def test_return_inside_with_block(self):
1795 snippet = """
1796 with c:
1797 if z:
1798 return
1799 else:
1800 a
1801 """
1802 self.check_stack_size(snippet)
1803
1804 def test_async_with(self):
1805 snippet = """
1806 async with x as y:
1807 a
1808 """
1809 self.check_stack_size(snippet, async_=True)
1810
1811 def test_async_for(self):
1812 snippet = """
1813 async for x in y:
1814 a
1815 """
1816 self.check_stack_size(snippet, async_=True)
1817
1818 def test_async_for_else(self):
1819 snippet = """
1820 async for x in y:
1821 a
1822 else:
1823 b
1824 """
1825 self.check_stack_size(snippet, async_=True)
1826
1827 def test_for_break_continue_inside_async_with_block(self):
1828 snippet = """
1829 for x in y:
1830 async with c:
1831 if z:
1832 break
1833 elif u:
1834 continue
1835 else:
1836 a
1837 else:
1838 b
1839 """
1840 self.check_stack_size(snippet, async_=True)
1841
1842 def test_return_inside_async_with_block(self):
1843 snippet = """
1844 async with c:
1845 if z:
1846 return
1847 else:
1848 a
1849 """
1850 self.check_stack_size(snippet, async_=True)
1851
1852
1853 if __name__ == "__main__":
1854 unittest.main()