Debian Codegraph @

pypy/interpreter/astcompiler/test/test_compiler.py

raw symbols SCIP
1 from __future__ import division
2 import py, sys
3 from pytest import raises
4 import pytest
5 from pypy.interpreter.astcompiler import codegen, symtable, optimize
6 from pypy.interpreter.pyparser import pyparse
7 from pypy.interpreter.pyparser.test import expressions
8 from pypy.interpreter.pycode import PyCode
9 from pypy.interpreter.pyparser.error import SyntaxError, IndentationError
10 from pypy.interpreter.error import OperationError
11 from pypy.tool import stdlib_opcode as ops
12
13 def compile_with_astcompiler(expr, mode, space, set_debug_flag=False):
14 p = pyparse.PegParser(space)
15 info = pyparse.CompileInfo("<test>", mode)
16 ast = p.parse_source(expr, info)
17 mod = optimize.optimize_ast(space, ast, info)
18 return codegen.compile_ast(space, mod, info, set_debug_flag)
19
20 def generate_function_code(expr, space):
21 from pypy.interpreter.astcompiler.ast import FunctionDef
22 p = pyparse.PegParser(space)
23 info = pyparse.CompileInfo("<test>", 'exec')
24 ast = p.parse_source(expr, info)
25 function_ast = optimize.optimize_ast(space, ast.body[0], info)
26 function_ast = ast.body[0]
27 assert isinstance(function_ast, FunctionDef)
28 symbols = symtable.SymtableBuilder(space, ast, info)
29 generator = codegen.FunctionCodeGenerator(
30 space, 'function', function_ast, 1, symbols, info, qualname='function')
31 blocks, size = generator._finalize_blocks()
32 return generator, blocks
33
34 class BaseTestCompiler:
35 """These tests compile snippets of code and check them by
36 running them with our own interpreter. These are thus not
37 completely *unit* tests, but given that our interpreter is
38 pretty stable now it is the best way I could find to check
39 the compiler.
40 """
41
42 def run(self, source):
43 import sys
44 source = str(py.code.Source(source))
45 space = self.space
46 code = compile_with_astcompiler(source, 'exec', space)
47 # 3.2 bytecode is too different, the standard `dis` module crashes
48 # on older cpython versions
49 if sys.version_info >= (3, 2):
50 # this will only (maybe) work in the far future, when we run pypy
51 # on top of Python 3. For now, it's just disabled
52 print
53 code.dump()
54 w_dict = space.newdict()
55 code.exec_code(space, w_dict, w_dict)
56 return w_dict
57
58 # on Python3 some reprs are different than Python2. Here is a collection
59 # of how the repr should be on on Python3 for some objects
60 PY3_REPR = {
61 int: "<class 'int'>",
62 float: "<class 'float'>",
63 }
64
65 def get_py3_repr(self, val):
66 try:
67 return self.PY3_REPR.get(val, repr(val))
68 except TypeError:
69 # e.g., for unhashable types
70 return repr(val)
71
72 def check(self, w_dict, evalexpr, expected):
73 # for now, we compile evalexpr with CPython's compiler but run
74 # it with our own interpreter to extract the data from w_dict
75 space = self.space
76 pyco_expr = space.createnewcompiler().compile(evalexpr, '<evalexpr>', 'eval', 0)
77 w_res = space.exec_(pyco_expr, w_dict, w_dict)
78 res = space.text_w(space.repr(w_res))
79 expected_repr = self.get_py3_repr(expected)
80 if isinstance(expected, float):
81 # Float representation can vary a bit between interpreter
82 # versions, compare the numbers instead.
83 assert eval(res) == expected
84 elif isinstance(expected, long):
85 assert expected_repr.endswith('L')
86 assert res == expected_repr[:-1] # in py3 we don't have the L suffix
87 else:
88 assert res == expected_repr
89
90 def simple_test(self, source, evalexpr, expected):
91 w_g = self.run(source)
92 self.check(w_g, evalexpr, expected)
93
94 st = simple_test
95
96 def error_test(self, source, exc_type, msg_part=""):
97 excinfo = py.test.raises(exc_type, self.simple_test, source, None, None)
98 assert msg_part in excinfo.value.msg
99 return excinfo.value
100
101
102 class TestCompiler(BaseTestCompiler):
103
104 def test_issue_713(self):
105 func = "def f(_=2): return (_ if _ else _) if False else _"
106 yield self.st, func, "f()", 2
107
108 def test_return(self):
109 for input in ("class x: return", "return"):
110 yield self.error_test, input, SyntaxError, "return outside function"
111
112 def test_long_jump(self):
113 func = """def f(x):
114 y = 0
115 if x:
116 %s return 1
117 else:
118 return 0""" % (" y += 1\n" * 6700,)
119 yield self.st, func, "f(1)", 1
120 yield self.st, func, "f(0)", 0
121
122 def test_argtuple(self):
123 yield (self.error_test, "def f( x, (y,z) ): return x,y,z",
124 SyntaxError)
125 yield (self.error_test, "def f( x, (y,(z,t)) ): return x,y,z,t",
126 SyntaxError)
127 yield (self.error_test, "def f(((((x,),y),z),t),u): return x,y,z,t,u",
128 SyntaxError)
129
130 def test_constants(self):
131 for c in expressions.constants:
132 yield (self.simple_test, "x="+c, "x", eval(c))
133
134 def test_literals_with_leading_zeros(self):
135 # adapted from similar test in lib-python/3/test/test_compiler.py
136 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
137 "080000000000000", "000000000000009", "000000000000008",
138 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
139 "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0777",
140 "000777", "000000000000007"]:
141 yield(self.error_test, "x=%s" % arg, SyntaxError)
142 yield(self.simple_test, "x=0xff", "x", 255)
143 yield(self.simple_test, "x=0777.", "x", 777.0)
144 yield(self.simple_test, "x=0777.0", "x", 777.0)
145 yield(self.simple_test, "x=000000000000000000000000000000000000000000000000000777e0", "x", 777.0)
146 yield(self.simple_test, "x=0777e1", "x", 7770.0)
147 yield(self.simple_test, "x=0e0", "x", 0.0)
148 yield(self.simple_test, "x=0000e-012", "x", 0.0)
149 yield(self.simple_test, "x=09.5", "x", 9.5)
150 yield(self.simple_test, "x=0777j", "x", 777j)
151 yield(self.simple_test, "x=000", "x", 0)
152 yield(self.simple_test, "x=00j", "x", 0j)
153 yield(self.simple_test, "x=00.0", "x", 0.0)
154 yield(self.simple_test, "x=0e3", "x", 0.0)
155 yield(self.simple_test, "x=090000000000000.", "x", 90000000000000.)
156 yield(self.simple_test, "x=090000000000000.0000000000000000000000", "x", 90000000000000.)
157 yield(self.simple_test, "x=090000000000000e0", "x", 90000000000000.)
158 yield(self.simple_test, "x=090000000000000e-0", "x", 90000000000000.)
159 yield(self.simple_test, "x=090000000000000j", "x", 90000000000000j)
160 yield(self.simple_test, "x=000000000000008.", "x", 8.)
161 yield(self.simple_test, "x=000000000000009.", "x", 9.)
162 yield(self.simple_test, "x=0b101010", "x", 42)
163 yield(self.simple_test, "x=-0b000000000010", "x", -2)
164 yield(self.simple_test, "x=0o777", "x", 511)
165 yield(self.simple_test, "x=-0o0000010", "x", -8)
166 yield (self.simple_test, "x=0_0_0", "x", 0)
167 yield (self.simple_test, "x=0b_1_1", "x", 3)
168 yield (self.simple_test, "x=0o_1_1", "x", 9)
169 yield (self.simple_test, "x=0X_1_1", "x", 17)
170
171
172 def test_int_limit(self):
173 yield (self.simple_test, "x=0E0", "x", 0.0)
174 from pypy.module.sys.system import DEFAULT_MAX_STR_DIGITS
175 max_str_digits = DEFAULT_MAX_STR_DIGITS
176 yield(self.error_test, "x=%s" % ('1' * (max_str_digits + 1)), SyntaxError)
177
178 def test_const_underscore(self):
179 yield (self.simple_test, "x=0xffff_ffff_ff20_0000", "x", 0xffffffffff200000)
180
181 def test_neg_sys_maxint(self):
182 import sys
183 stmt = "x = %s" % (-sys.maxint-1)
184 self.simple_test(stmt, "type(x)", int)
185
186 def test_tuple_assign(self):
187 yield self.simple_test, "() = []", "1", 1
188 yield self.simple_test, "x,= 1,", "x", 1
189 yield self.simple_test, "x,y = 1,2", "x,y", (1, 2)
190 yield self.simple_test, "x,y,z = 1,2,3", "x,y,z", (1, 2, 3)
191 yield self.simple_test, "x,y,z,t = 1,2,3,4", "x,y,z,t", (1, 2, 3, 4)
192 yield self.simple_test, "x,y,x,t = 1,2,3,4", "x,y,t", (3, 2, 4)
193 yield self.simple_test, "[] = []", "1", 1
194 yield self.simple_test, "[x]= 1,", "x", 1
195 yield self.simple_test, "[x,y] = [1,2]", "x,y", (1, 2)
196 yield self.simple_test, "[x,y,z] = 1,2,3", "x,y,z", (1, 2, 3)
197 yield self.simple_test, "[x,y,z,t] = [1,2,3,4]", "x,y,z,t", (1, 2, 3,4)
198 yield self.simple_test, "[x,y,x,t] = 1,2,3,4", "x,y,t", (3, 2, 4)
199
200 def test_tuple_assign_order(self):
201 decl = py.code.Source("""
202 class A:
203 def __getattr__(self, name):
204 global seen
205 seen += name
206 return name
207 def __setattr__(self, name, value):
208 global seen
209 seen += '%s=%s' % (name, value)
210 seen = ''
211 a = A()
212 """)
213 decl = str(decl) + '\n'
214 yield self.st, decl+"a.x,= a.a,", 'seen', 'ax=a'
215 yield self.st, decl+"a.x,a.y = a.a,a.b", 'seen', 'abx=ay=b'
216 yield self.st, decl+"a.x,a.y,a.z = a.a,a.b,a.c", 'seen', 'abcx=ay=bz=c'
217 yield self.st, decl+"a.x,a.y,a.x,a.t = a.a,a.b,a.c,a.d", 'seen', \
218 'abcdx=ay=bx=ct=d'
219 yield self.st, decl+"[a.x] = [a.a]", 'seen', 'ax=a'
220 yield self.st, decl+"[a.x,a.y] = a.a,a.b", 'seen', 'abx=ay=b'
221 yield self.st, decl+"[a.x,a.y,a.z] = [a.a,a.b,a.c]", 'seen', \
222 'abcx=ay=bz=c'
223 yield self.st, decl+"[a.x,a.y,a.x,a.t] = a.a,a.b,a.c,a.d", 'seen', \
224 'abcdx=ay=bx=ct=d'
225
226 def test_binary_operator(self):
227 for operator in ['+', '-', '*', '**', '/', '&', '|', '^', '//',
228 '<<', '>>', 'and', 'or', '<', '>', '<=', '>=',
229 'is', 'is not']:
230 expected = eval("17 %s 5" % operator)
231 yield self.simple_test, "x = 17 %s 5" % operator, "x", expected
232 expected = eval("0 %s 11" % operator)
233 yield self.simple_test, "x = 0 %s 11" % operator, "x", expected
234
235 def test_compare(self):
236 yield self.st, "x = 2; y = 5; y; h = 1 < x >= 3 < x", "h", False
237
238 def test_augmented_assignment(self):
239 for operator in ['+', '-', '*', '**', '/', '&', '|', '^', '//',
240 '<<', '>>']:
241 expected = eval("17 %s 5" % operator)
242 yield self.simple_test, "x = 17; x %s= 5" % operator, "x", expected
243
244 def test_subscript(self):
245 yield self.simple_test, "d={2:3}; x=d[2]", "x", 3
246 yield self.simple_test, "d={(2,):3}; x=d[2,]", "x", 3
247 yield self.simple_test, "d={}; d[1]=len(d); x=d[len(d)]", "x", 0
248 yield self.simple_test, "d={}; d[1]=3; del d[1]", "len(d)", 0
249
250 def test_attribute(self):
251 yield self.simple_test, """
252 class A:
253 pass
254 a1 = A()
255 a2 = A()
256 a1.bc = A()
257 a1.bc.de = a2
258 a2.see = 4
259 a1.bc.de.see += 3
260 x = a1.bc.de.see
261 """, 'x', 7
262
263 def test_slice(self):
264 decl = py.code.Source("""
265 class A(object):
266 def __getitem__(self, x):
267 global got
268 got = x
269 def __setitem__(self, x, y):
270 global set
271 set = x
272 def __delitem__(self, x):
273 global deleted
274 deleted = x
275 a = A()
276 """)
277 decl = str(decl) + '\n'
278 testcases = ['[:]', '[:,9]', '[8,:]',
279 '[2:]', '[2:,9]', '[8,2:]',
280 '[:2]', '[:2,9]', '[8,:2]',
281 '[4:7]', '[4:7,9]', '[8,4:7]',
282 '[::]', '[::,9]', '[8,::]',
283 '[2::]', '[2::,9]', '[8,2::]',
284 '[:2:]', '[:2:,9]', '[8,:2:]',
285 '[4:7:]', '[4:7:,9]', '[8,4:7:]',
286 '[::3]', '[::3,9]', '[8,::3]',
287 '[2::3]', '[2::3,9]', '[8,2::3]',
288 '[:2:3]', '[:2:3,9]', '[8,:2:3]',
289 '[4:7:3]','[4:7:3,9]','[8,4:7:3]',
290 ]
291 class Checker(object):
292 def __getitem__(self, x):
293 self.got = x
294 checker = Checker()
295 for testcase in testcases:
296 exec "checker" + testcase
297 yield self.st, decl + "a" + testcase, "got", checker.got
298 yield self.st, decl + "a" + testcase + ' = 5', "set", checker.got
299 yield self.st, decl + "del a" + testcase, "deleted", checker.got
300
301 def test_funccalls(self):
302 decl = py.code.Source("""
303 def f(*args, **kwds):
304 kwds = sorted(kwds.items())
305 return list(args) + kwds
306 """)
307 decl = str(decl) + '\n'
308 yield self.st, decl + "x=f()", "x", []
309 yield self.st, decl + "x=f(5)", "x", [5]
310 yield self.st, decl + "x=f(5, 6, 7, 8)", "x", [5, 6, 7, 8]
311 yield self.st, decl + "x=f(a=2, b=5)", "x", [('a',2), ('b',5)]
312 yield self.st, decl + "x=f(5, b=2, *[6,7])", "x", [5, 6, 7, ('b', 2)]
313 yield self.st, decl + "x=f(5, b=2, **{'a': 8})", "x", [5, ('a', 8),
314 ('b', 2)]
315
316 def test_funccalls_all_combinations(self):
317 decl = """
318 def f(*args, **kwds):
319 kwds = sorted(kwds.items())
320 return list(args) + kwds
321
322 class A:
323 def f(self, *args, **kwds):
324 kwds = sorted(kwds.items())
325 return ["meth"] + list(args) + kwds
326 a = A()
327 """
328 allres = []
329 allcalls = []
330 for meth in [False, True]:
331 for starstarargs in [
332 [],
333 [[('x', 1), ('y', 12)]],
334 [[('w1', 1), ('w2', 12)], [('x1', 1), ('x2', -12)], [('y1', 10), ('y2', 123)]]
335 ]:
336 for starargs in [[], [(2, 3)], [(2, 3), (4, 19), (23, 54, 123)]]:
337 for kwargs in [[], [('m', 1)], [('n', 1), ('o', 2), ('p', 3)]]:
338 for args in [(), (1, ), (1, 4, 5)]:
339 if not meth:
340 call = "f("
341 res = []
342 else:
343 call = "a.f("
344 res = ["meth"]
345 if args:
346 call += ", ".join(str(arg) for arg in args) + ","
347 res.extend(args)
348 if starargs:
349 for stararg in starargs:
350 call += "*" + str(stararg) + ","
351 res.extend(stararg)
352 if kwargs:
353 call += ", ".join("%s=%s" % (kw, arg) for (kw, arg) in kwargs) + ", "
354 res.extend(kwargs)
355 if starstarargs:
356 for starstar in starstarargs:
357 call += "**dict(%s)" % starstar + ","
358 res.extend(sum(starstarargs, []))
359 call += ")"
360 allcalls.append(call)
361 allres.append(res)
362 print call
363 print res
364 self.st(decl + "x=[" + "\n,".join(allcalls) + "]", "x", allres)
365
366
367 def test_kwonly(self):
368 decl = py.code.Source("""
369 def f(a, *, b):
370 return a, b
371 """)
372 decl = str(decl) + '\n'
373 self.st(decl + "x=f(1, b=2)", "x", (1, 2))
374 operr = py.test.raises(OperationError, 'self.st(decl + "x=f(1, 2)", "x", (1, 2))')
375 assert operr.value.w_type is self.space.w_TypeError
376
377 def test_listmakers(self):
378 yield (self.st,
379 "l = [(j, i) for j in range(10) for i in range(j)"
380 + " if (i+j)%2 == 0 and i%3 == 0]",
381 "l",
382 [(2, 0), (4, 0), (5, 3), (6, 0),
383 (7, 3), (8, 0), (8, 6), (9, 3)])
384
385 def test_genexprs(self):
386 yield (self.st,
387 "l = list((j, i) for j in range(10) for i in range(j)"
388 + " if (i+j)%2 == 0 and i%3 == 0)",
389 "l",
390 [(2, 0), (4, 0), (5, 3), (6, 0),
391 (7, 3), (8, 0), (8, 6), (9, 3)])
392
393 def test_comparisons(self):
394 yield self.st, "x = 3 in {3: 5}", "x", True
395 yield self.st, "x = 3 not in {3: 5}", "x", False
396 yield self.st, "t = True; x = t is True", "x", True
397 yield self.st, "t = True; x = t is False", "x", False
398 yield self.st, "t = True; x = t is None", "x", False
399 yield self.st, "n = None; x = n is True", "x", False
400 yield self.st, "n = None; x = n is False", "x", False
401 yield self.st, "n = None; x = n is None", "x", True
402 yield self.st, "t = True; x = t is not True", "x", False
403 yield self.st, "t = True; x = t is not False", "x", True
404 yield self.st, "t = True; x = t is not None", "x", True
405 yield self.st, "n = None; x = n is not True", "x", True
406 yield self.st, "n = None; x = n is not False", "x", True
407 yield self.st, "n = None; x = n is not None", "x", False
408
409 yield self.st, "x = not (3 in {3: 5})", "x", False
410 yield self.st, "x = not (3 not in {3: 5})", "x", True
411 yield self.st, "t = True; x = not (t is True)", "x", False
412 yield self.st, "t = True; x = not (t is False)", "x", True
413 yield self.st, "t = True; x = not (t is None)", "x", True
414 yield self.st, "n = None; x = not (n is True)", "x", True
415 yield self.st, "n = None; x = not (n is False)", "x", True
416 yield self.st, "n = None; x = not (n is None)", "x", False
417 yield self.st, "t = True; x = not (t is not True)", "x", True
418 yield self.st, "t = True; x = not (t is not False)", "x", False
419 yield self.st, "t = True; x = not (t is not None)", "x", False
420 yield self.st, "n = None; x = not (n is not True)", "x", False
421 yield self.st, "n = None; x = not (n is not False)", "x", False
422 yield self.st, "n = None; x = not (n is not None)", "x", True
423
424 def test_multiexpr(self):
425 yield self.st, "z = 2+3; x = y = z", "x,y,z", (5,5,5)
426
427 def test_imports(self):
428 import os
429 yield self.st, "import sys", "sys.__name__", "sys"
430 yield self.st, "import sys as y", "y.__name__", "sys"
431 yield (self.st, "import sys, os",
432 "sys.__name__, os.__name__", ("sys", "os"))
433 yield (self.st, "import sys as x, os.path as y",
434 "x.__name__, y.__name__", ("sys", os.path.__name__))
435 yield self.st, 'import os.path', "os.path.__name__", os.path.__name__
436 yield (self.st, 'import os.path, sys',
437 "os.path.__name__, sys.__name__", (os.path.__name__, "sys"))
438 yield (self.st, 'import sys, os.path as osp',
439 "osp.__name__, sys.__name__", (os.path.__name__, "sys"))
440 yield (self.st, 'import os.path as osp',
441 "osp.__name__", os.path.__name__)
442 yield (self.st, 'from os import path',
443 "path.__name__", os.path.__name__)
444 yield (self.st, 'from os import path, sep',
445 "path.__name__, sep", (os.path.__name__, os.sep))
446 yield (self.st, 'from os import path as p',
447 "p.__name__", os.path.__name__)
448 yield (self.st, 'from os import *',
449 "path.__name__, sep", (os.path.__name__, os.sep))
450 yield (self.st, '''
451 class A(object):
452 def m(self):
453 from __foo__.bar import x
454 try:
455 A().m()
456 except ImportError as e:
457 msg = str(e)
458 ''', "msg", "No module named '__foo__'")
459
460 def test_if_stmts(self):
461 yield self.st, "a = 42\nif a > 10: a += 2", "a", 44
462 yield self.st, "a=5\nif 0: a=7", "a", 5
463 yield self.st, "a=5\nif 1: a=7", "a", 7
464 yield self.st, "a=5\nif a and not not (a<10): a=7", "a", 7
465 yield self.st, """
466 lst = []
467 for a in range(10):
468 if a < 3:
469 a += 20
470 elif a > 3 and a < 8:
471 a += 30
472 else:
473 a += 40
474 lst.append(a)
475 """, "lst", [20, 21, 22, 43, 34, 35, 36, 37, 48, 49]
476 yield self.st, """
477 lst = []
478 for a in range(10):
479 b = (a & 7) ^ 1
480 if a or 1 or b: lst.append('A')
481 if a or 0 or b: lst.append('B')
482 if a and 1 and b: lst.append('C')
483 if a and 0 and b: lst.append('D')
484 if not (a or 1 or b): lst.append('-A')
485 if not (a or 0 or b): lst.append('-B')
486 if not (a and 1 and b): lst.append('-C')
487 if not (a and 0 and b): lst.append('-D')
488 if (not a) or (not 1) or (not b): lst.append('A')
489 if (not a) or (not 0) or (not b): lst.append('B')
490 if (not a) and (not 1) and (not b): lst.append('C')
491 if (not a) and (not 0) and (not b): lst.append('D')
492 """, "lst", ['A', 'B', '-C', '-D', 'A', 'B', 'A', 'B', '-C',
493 '-D', 'A', 'B', 'A', 'B', 'C', '-D', 'B', 'A', 'B',
494 'C', '-D', 'B', 'A', 'B', 'C', '-D', 'B', 'A', 'B',
495 'C', '-D', 'B', 'A', 'B', 'C', '-D', 'B', 'A', 'B',
496 'C', '-D', 'B', 'A', 'B', 'C', '-D', 'B', 'A', 'B',
497 '-C', '-D', 'A', 'B']
498
499 def test_docstrings(self):
500 for source, expected in [
501 ('''def foo(): return 1''', None),
502 ('''class foo: pass''', None),
503 ('''foo = lambda: 4''', None),
504 ('''foo = lambda: "foo"''', None),
505 ('''def foo(): 4''', None),
506 ('''class foo: "foo"''', "foo"),
507 ('''def foo():
508 """foo docstring"""
509 return 1
510 ''', "foo docstring"),
511 ('''def foo():
512 """foo docstring"""
513 a = 1
514 """bar"""
515 return a
516 ''', "foo docstring"),
517 ('''def foo():
518 """doc"""; assert 1
519 a=1
520 ''', "doc"),
521 ('''
522 class Foo(object): pass
523 foo = Foo()
524 exec("'moduledoc'", foo.__dict__)
525 ''', "moduledoc"),
526 ('''def foo(): f"abc"''', None),
527 ]:
528 yield self.simple_test, source, "foo.__doc__", expected
529
530 def test_in(self):
531 yield self.st, "n = 5; x = n in [3,4,5]", 'x', True
532 yield self.st, "n = 5; x = n in [3,4,6]", 'x', False
533 yield self.st, "n = 5; x = n in [3,4,n]", 'x', True
534 yield self.st, "n = 5; x = n in [3,4,n+1]", 'x', False
535 yield self.st, "n = 5; x = n in (3,4,5)", 'x', True
536 yield self.st, "n = 5; x = n in (3,4,6)", 'x', False
537 yield self.st, "n = 5; x = n in (3,4,n)", 'x', True
538 yield self.st, "n = 5; x = n in (3,4,n+1)", 'x', False
539
540 def test_for_loops(self):
541 yield self.st, """
542 total = 0
543 for i in [2, 7, 5]:
544 total += i
545 """, 'total', 2 + 7 + 5
546 yield self.st, """
547 total = 0
548 for i in (2, 7, 5):
549 total += i
550 """, 'total', 2 + 7 + 5
551 yield self.st, """
552 total = 0
553 for i in [2, 7, total+5]:
554 total += i
555 """, 'total', 2 + 7 + 5
556 yield self.st, "x = sum([n+2 for n in [6, 1, 2]])", 'x', 15
557 yield self.st, "x = sum([n+2 for n in (6, 1, 2)])", 'x', 15
558 yield self.st, "k=2; x = sum([n+2 for n in [6, 1, k]])", 'x', 15
559 yield self.st, "k=2; x = sum([n+2 for n in (6, 1, k)])", 'x', 15
560 yield self.st, "x = sum(n+2 for n in [6, 1, 2])", 'x', 15
561 yield self.st, "x = sum(n+2 for n in (6, 1, 2))", 'x', 15
562 yield self.st, "k=2; x = sum(n+2 for n in [6, 1, k])", 'x', 15
563 yield self.st, "k=2; x = sum(n+2 for n in (6, 1, k))", 'x', 15
564
565 def test_closure(self):
566 decl = py.code.Source("""
567 def make_adder(n):
568 def add(m):
569 return n + m
570 return add
571 """)
572 decl = str(decl) + "\n"
573 yield self.st, decl + "x = make_adder(40)(2)", 'x', 42
574
575 decl = py.code.Source("""
576 def f(a, g, e, c):
577 def b(n, d):
578 return (a, c, d, g, n)
579 def f(b, a):
580 return (a, b, c, g)
581 return (a, g, e, c, b, f)
582 A, G, E, C, B, F = f(6, 2, 8, 5)
583 A1, C1, D1, G1, N1 = B(7, 3)
584 A2, B2, C2, G2 = F(1, 4)
585 """)
586 decl = str(decl) + "\n"
587 yield self.st, decl, 'A,A1,A2,B2,C,C1,C2,D1,E,G,G1,G2,N1', \
588 (6,6 ,4 ,1 ,5,5 ,5 ,3 ,8,2,2 ,2 ,7 )
589
590 def test_try_except(self):
591 yield self.simple_test, """
592 x = 42
593 try:
594 pass
595 except:
596 x = 0
597 """, 'x', 42
598
599 def test_try_finally_bug(self):
600 yield self.simple_test, """
601 x = 0
602 try:
603 pass
604 finally:
605 x = 6
606 print(None, None, None, None)
607 x *= 7
608 """, 'x', 42
609
610 def test_with_stacksize_bug(self):
611 compile_with_astcompiler("with a:\n pass", 'exec', self.space)
612
613 def test_with_bug(self):
614 yield self.simple_test, """
615 class ContextManager:
616 def __enter__(self, *args):
617 return self
618 def __exit__(self, *args):
619 pass
620
621 x = 0
622 with ContextManager():
623 x = 6
624 print(None, None, None, None)
625 x *= 7
626 """, 'x', 42
627
628 def test_while_loop(self):
629 yield self.simple_test, """
630 comments = [42]
631 comment = '# foo'
632 while comment[:1] == '#':
633 comments[:0] = [comment]
634 comment = ''
635 """, 'comments', ['# foo', 42]
636 yield self.simple_test, """
637 while 0:
638 pass
639 else:
640 x = 1
641 """, "x", 1
642
643 def test_type_of_constants(self):
644 yield self.simple_test, "x=[0, 0.]", 'type(x[1])', float
645 yield self.simple_test, "x=[(1,0), (1,0.)]", 'type(x[1][1])', float
646 yield self.simple_test, "x=['2?-', '2?-']", 'id(x[0])==id(x[1])', True
647
648 def test_pprint(self):
649 # a larger example that showed a bug with jumps
650 # over more than 256 bytes
651 decl = py.code.Source("""
652 def _safe_repr(object, context, maxlevels, level):
653 typ = type(object)
654 if typ is str:
655 if 'locale' not in _sys.modules:
656 return repr(object), True, False
657 if "'" in object and '"' not in object:
658 closure = '"'
659 quotes = {'"': '\\"'}
660 else:
661 closure = "'"
662 quotes = {"'": "\\'"}
663 qget = quotes.get
664 sio = _StringIO()
665 write = sio.write
666 for char in object:
667 if char.isalpha():
668 write(char)
669 else:
670 write(qget(char, repr(char)[1:-1]))
671 return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
672
673 r = getattr(typ, "__repr__", None)
674 if issubclass(typ, dict) and r is dict.__repr__:
675 if not object:
676 return "{}", True, False
677 objid = id(object)
678 if maxlevels and level > maxlevels:
679 return "{...}", False, objid in context
680 if objid in context:
681 return _recursion(object), False, True
682 context[objid] = 1
683 readable = True
684 recursive = False
685 components = []
686 append = components.append
687 level += 1
688 saferepr = _safe_repr
689 for k, v in object.items():
690 krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
691 vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
692 append("%s: %s" % (krepr, vrepr))
693 readable = readable and kreadable and vreadable
694 if krecur or vrecur:
695 recursive = True
696 del context[objid]
697 return "{%s}" % ', '.join(components), readable, recursive
698
699 if (issubclass(typ, list) and r is list.__repr__) or \
700 (issubclass(typ, tuple) and r is tuple.__repr__):
701 if issubclass(typ, list):
702 if not object:
703 return "[]", True, False
704 format = "[%s]"
705 elif _len(object) == 1:
706 format = "(%s,)"
707 else:
708 if not object:
709 return "()", True, False
710 format = "(%s)"
711 objid = id(object)
712 if maxlevels and level > maxlevels:
713 return format % "...", False, objid in context
714 if objid in context:
715 return _recursion(object), False, True
716 context[objid] = 1
717 readable = True
718 recursive = False
719 components = []
720 append = components.append
721 level += 1
722 for o in object:
723 orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
724 append(orepr)
725 if not oreadable:
726 readable = False
727 if orecur:
728 recursive = True
729 del context[objid]
730 return format % ', '.join(components), readable, recursive
731
732 rep = repr(object)
733 return rep, (rep and not rep.startswith('<')), False
734 """)
735 decl = str(decl) + '\n'
736 g = {}
737 exec decl in g
738 expected = g['_safe_repr']([5], {}, 3, 0)
739 yield self.st, decl + 'x=_safe_repr([5], {}, 3, 0)', 'x', expected
740
741 def test_mapping_test(self):
742 decl = py.code.Source("""
743 class X(object):
744 reference = {1:2, "key1":"value1", "key2":(1,2,3)}
745 key, value = reference.popitem()
746 other = {key:value}
747 key, value = reference.popitem()
748 inmapping = {key:value}
749 reference[key] = value
750 def _empty_mapping(self):
751 return {}
752 _full_mapping = dict
753 def assertEqual(self, x, y):
754 assert x == y
755 failUnlessRaises = staticmethod(raises)
756 def assert_(self, x):
757 assert x
758 def failIf(self, x):
759 assert not x
760
761 def test_read(self):
762 # Test for read only operations on mapping
763 p = self._empty_mapping()
764 p1 = dict(p) #workaround for singleton objects
765 d = self._full_mapping(self.reference)
766 if d is p:
767 p = p1
768 #Indexing
769 for key, value in self.reference.items():
770 self.assertEqual(d[key], value)
771 knownkey = next(iter(self.other))
772 self.failUnlessRaises(KeyError, lambda:d[knownkey])
773 #len
774 self.assertEqual(len(p), 0)
775 self.assertEqual(len(d), len(self.reference))
776 #has_key
777 for k in self.reference:
778 self.assert_(k in d)
779 for k in self.other:
780 self.failIf(k in d)
781 #cmp
782 self.assert_(p == p)
783 self.assert_(d == d)
784 self.failUnlessRaises(TypeError, lambda: p < d)
785 self.failUnlessRaises(TypeError, lambda: d > p)
786 #__non__zero__
787 if p: self.fail("Empty mapping must compare to False")
788 if not d: self.fail("Full mapping must compare to True")
789 # keys(), items(), iterkeys() ...
790 def check_iterandlist(iter, lst, ref):
791 self.assert_(hasattr(iter, '__next__'))
792 self.assert_(hasattr(iter, '__iter__'))
793 x = list(iter)
794 self.assert_(set(x)==set(lst)==set(ref))
795 check_iterandlist(iter(d.keys()), d.keys(), self.reference.keys())
796 check_iterandlist(iter(d), d.keys(), self.reference.keys())
797 check_iterandlist(iter(d.values()), d.values(), self.reference.values())
798 check_iterandlist(iter(d.items()), d.items(), self.reference.items())
799 #get
800 key, value = next(iter(d.items()))
801 knownkey, knownvalue = next(iter(self.other.items()))
802 self.assertEqual(d.get(key, knownvalue), value)
803 self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
804 self.failIf(knownkey in d)
805 return 42
806 """)
807 decl = str(decl) + '\n'
808 yield self.simple_test, decl + 'r = test_read(X())', 'r', 42
809
810 def test_stack_depth_bug(self):
811 decl = py.code.Source("""
812 class A:
813 def initialize(self):
814 # install all the MultiMethods into the space instance
815 if isinstance(mm, object):
816 def make_boundmethod(func=func):
817 def boundmethod(*args):
818 return func(self, *args)
819 r = None
820 """)
821 decl = str(decl) + '\n'
822 yield self.simple_test, decl, 'r', None
823
824 def test_assert(self):
825 decl = py.code.Source("""
826 try:
827 assert 0, 'hi'
828 except AssertionError as e:
829 msg = str(e)
830 """)
831 yield self.simple_test, decl, 'msg', 'hi'
832
833 def test_indentation_error(self):
834 source = py.code.Source("""
835 x
836 y
837 """)
838 try:
839 self.simple_test(source, None, None)
840 except IndentationError as e:
841 assert e.msg == 'unexpected indent'
842 else:
843 raise Exception("DID NOT RAISE")
844
845 def test_no_indent(self):
846 source = py.code.Source("""
847 def f():
848 xxx
849 """)
850 try:
851 self.simple_test(source, None, None)
852 except IndentationError as e:
853 assert e.msg == 'expected an indented block after function definition on line 2'
854 else:
855 raise Exception("DID NOT RAISE")
856
857 def test_indent_error_filename(self):
858 source = py.code.Source("""
859 def f():
860 x
861 y
862 """)
863 try:
864 self.simple_test(source, None, None)
865 except IndentationError as e:
866 assert e.filename == '<test>'
867 else:
868 raise Exception("DID NOT RAISE")
869
870 def test_kwargs_last(self):
871 py.test.raises(SyntaxError, self.simple_test, "int(base=10, '2')",
872 None, None)
873
874 def test_starargs_after_starargs(self):
875 #allowed since PEP 448 "Additional Unpacking Generalizations"
876 source = py.code.Source("""
877 def call(*arg):
878 ret = []
879 for i in arg:
880 ret.append(i)
881 return ret
882
883 args = [4,5,6]
884 res = call(*args, *args)
885 """)
886 self.simple_test(source, 'res', [4,5,6,4,5,6])
887
888 def test_not_a_name(self):
889 source = "call(a, b, c, 3=3)"
890 py.test.raises(SyntaxError, self.simple_test, source, None, None)
891
892 def test_assignment_to_call_func(self):
893 source = "call(a, b, c) = 3"
894 py.test.raises(SyntaxError, self.simple_test, source, None, None)
895
896 def test_augassig_to_sequence(self):
897 source = "a, b += 3"
898 py.test.raises(SyntaxError, self.simple_test, source, None, None)
899
900 def test_broken_setups(self):
901 source = """if 1:
902 try:
903 break
904 finally:
905 pass
906 """
907 py.test.raises(SyntaxError, self.simple_test, source, None, None)
908
909 def test_bare_except_not_last(self):
910 source = """if 1:
911 try:
912 pass
913 except:
914 pass
915 except ValueError:
916 pass
917 """
918 with py.test.raises(SyntaxError):
919 self.simple_test(source, None, None)
920
921 def test_unpack_singletuple(self):
922 source = """if 1:
923 l = []
924 for x, in [(1,), (2,)]:
925 l.append(x)
926 """
927 self.simple_test(source, 'l', [1, 2])
928
929 def test_unpack_wrong_stackeffect(self):
930 source = """if 1:
931 l = [1, 2]
932 a, b = l
933 a, b = l
934 a, b = l
935 a, b = l
936 a, b = l
937 a, b = l
938 """
939 code = compile_with_astcompiler(source, 'exec', self.space)
940 assert code.co_stacksize == 2
941
942 def test_stackeffect_bug3(self):
943 source = """if 1:
944 try: pass
945 finally: pass
946 try: pass
947 finally: pass
948 try: pass
949 finally: pass
950 try: pass
951 finally: pass
952 try: pass
953 finally: pass
954 try: pass
955 finally: pass
956 """
957 code = compile_with_astcompiler(source, 'exec', self.space)
958 assert code.co_stacksize == 4 # outer_cleanup block needs depth 3, COPY pushes to 4
959
960 def test_stackeffect_bug4(self):
961 source = """if 1:
962 with a: pass
963 with a: pass
964 with a: pass
965 with a: pass
966 with a: pass
967 with a: pass
968 with a: pass
969 """
970 code = compile_with_astcompiler(source, 'exec', self.space)
971 assert code.co_stacksize == 6 # matches CPython 3.11; no systematic leak
972
973 def test_stackeffect_bug5(self):
974 source = """if 1:
975 a[:]; a[:]; a[:]; a[:]; a[:]; a[:]
976 a[1:]; a[1:]; a[1:]; a[1:]; a[1:]; a[1:]
977 a[:2]; a[:2]; a[:2]; a[:2]; a[:2]; a[:2]
978 a[1:2]; a[1:2]; a[1:2]; a[1:2]; a[1:2]; a[1:2]
979 """
980 code = compile_with_astcompiler(source, 'exec', self.space)
981 assert code.co_stacksize == 3
982
983 def test_stackeffect_bug6(self):
984 source = """if 1:
985 {1}; {1}; {1}; {1}; {1}; {1}; {1}
986 """
987 code = compile_with_astcompiler(source, 'exec', self.space)
988 assert code.co_stacksize == 1
989
990 def test_stackeffect_bug7(self):
991 source = '''def f():
992 for i in a:
993 return
994 '''
995 code = compile_with_astcompiler(source, 'exec', self.space)
996
997 def test_stackeffect_try_except_precision(self):
998 source = """if 1:
999 try:
1000 g()
1001 except TypeError as e:
1002 h(i(e))
1003 if j:
1004 raise
1005 print(6)
1006 """
1007 code = compile_with_astcompiler(source, 'exec', self.space)
1008 assert code.co_stacksize == 4 # used to be 6, then 5
1009
1010 def test_lambda(self):
1011 yield self.st, "y = lambda x: x", "y(4)", 4
1012
1013 def test_backquote_repr(self):
1014 py.test.raises(SyntaxError, self.simple_test, "y = `0`", None, None)
1015
1016 def test_deleting_attributes(self):
1017 test = """if 1:
1018 class X():
1019 x = 3
1020 del X.x
1021 try:
1022 X.x
1023 except AttributeError:
1024 pass
1025 else:
1026 raise AssertionError("attribute not removed")"""
1027 yield self.st, test, "X.__name__", "X"
1028
1029 def test_nonlocal(self):
1030 test = """if 1:
1031 def f():
1032 y = 0
1033 def g(x):
1034 nonlocal y
1035 y = x + 1
1036 g(3)
1037 return y"""
1038 yield self.st, test, "f()", 4
1039
1040 def test_nonlocal_from_arg(self):
1041 test = """if 1:
1042 def test1(x):
1043 def test2():
1044 nonlocal x
1045 def test3():
1046 return x
1047 return test3()
1048 return test2()"""
1049 yield self.st, test, "test1(2)", 2
1050
1051 def test_class_nonlocal_from_arg(self):
1052 test = """if 1:
1053 def f(x):
1054 class c:
1055 nonlocal x
1056 x += 1
1057 def get(self):
1058 return x
1059 return c().get(), x"""
1060 yield self.st, test, "f(3)", (4, 4)
1061
1062 def test_lots_of_loops(self):
1063 source = "for x in y: pass\n" * 1000
1064 compile_with_astcompiler(source, 'exec', self.space)
1065
1066 def test_assign_to_empty_list_1(self):
1067 source = """if 1:
1068 for i in range(5):
1069 del []
1070 [] = ()
1071 [] = []
1072 [] = [] = []
1073 ok = 1
1074 """
1075 self.simple_test(source, 'ok', 1)
1076
1077 def test_assign_to_empty_list_2(self):
1078 source = """if 1:
1079 for i in range(5):
1080 try: [] = 1, 2, 3
1081 except ValueError: pass
1082 else: raise AssertionError
1083 try: [] = a = 1
1084 except TypeError: pass
1085 else: raise AssertionError
1086 try: [] = _ = iter(['foo'])
1087 except ValueError: pass
1088 else: raise AssertionError
1089 try: [], _ = iter(['foo']), 1
1090 except ValueError: pass
1091 else: raise AssertionError
1092 ok = 1
1093 """
1094 self.simple_test(source, 'ok', 1)
1095
1096 @py.test.mark.parametrize('expr, result', [
1097 ("f1.__doc__", None),
1098 ("f2.__doc__", 'docstring'),
1099 ("f2()", 'docstring'),
1100 ("f3.__doc__", None),
1101 ("f3()", 'bar'),
1102 ("C1.__doc__", None),
1103 ("C2.__doc__", 'docstring'),
1104 ("C3.field", 'not docstring'),
1105 ("C4.field", 'docstring'),
1106 ("C4.__doc__", 'docstring'),
1107 ("C4.__doc__", 'docstring'),
1108 ("__doc__", None),])
1109
1110 def test_remove_docstring(self, expr, result):
1111 source = '"module_docstring"\n' + """if 1:
1112 def f1():
1113 'docstring'
1114 def f2():
1115 'docstring'
1116 return 'docstring'
1117 def f3():
1118 'foo'
1119 return 'bar'
1120 class C1():
1121 'docstring'
1122 class C2():
1123 __doc__ = 'docstring'
1124 class C3():
1125 field = 'not docstring'
1126 class C4():
1127 'docstring'
1128 field = 'docstring'
1129 """
1130 code_w = compile_with_astcompiler(source, 'exec', self.space)
1131 code_w.remove_docstrings(self.space)
1132 dict_w = self.space.newdict();
1133 code_w.exec_code(self.space, dict_w, dict_w)
1134 self.check(dict_w, expr, result)
1135
1136 def test_dont_fold_equal_code_objects(self):
1137 yield self.st, "f=lambda:1;g=lambda:1.0;x=g()", 'type(x)', float
1138 yield (self.st, "x=(lambda: (-0.0, 0.0), lambda: (0.0, -0.0))[1]()",
1139 'repr(x)', '(0.0, -0.0)')
1140
1141 def test_raise_from(self):
1142 test = """if 1:
1143 def f():
1144 try:
1145 raise TypeError() from ValueError()
1146 except TypeError as e:
1147 assert isinstance(e.__cause__, ValueError)
1148 return 42
1149 """
1150 yield self.st, test, "f()", 42
1151 test = """if 1:
1152 def f():
1153 try:
1154 raise TypeError from ValueError
1155 except TypeError as e:
1156 assert isinstance(e.__cause__, ValueError)
1157 return 42
1158 """
1159 yield self.st, test, "f()", 42
1160 # This line is needed for py.code to find the source.
1161
1162 def test_extended_unpacking(self):
1163 func = """def f():
1164 (a, *b, c) = 1, 2, 3, 4, 5
1165 return a, b, c
1166 """
1167 yield self.st, func, "f()", (1, [2, 3, 4], 5)
1168 func = """def f():
1169 [a, *b, c] = 1, 2, 3, 4, 5
1170 return a, b, c
1171 """
1172 yield self.st, func, "f()", (1, [2, 3, 4], 5)
1173 func = """def f():
1174 *a, = [1, 2, 3]
1175 return a
1176 """
1177 yield self.st, func, "f()", [1, 2, 3]
1178 func = """def f():
1179 for a, *b, c in [(1, 2, 3, 4)]:
1180 return a, b, c
1181 """
1182 yield self.st, func, "f()", (1, [2, 3], 4)
1183
1184 def test_unpacking_while_building(self):
1185 func = """def f():
1186 b = [4,5,6]
1187 a = (*b, 7)
1188 return a
1189 """
1190 yield self.st, func, "f()", (4, 5, 6, 7)
1191
1192 func = """def f():
1193 b = [4,5,6]
1194 a = [*b, 7]
1195 return a
1196 """
1197 yield self.st, func, "f()", [4, 5, 6, 7]
1198
1199 func = """def f():
1200 b = [4,]
1201 x, y = (*b, 7)
1202 return x
1203 """
1204 yield self.st, func, "f()", 4
1205
1206
1207 def test_extended_unpacking_fail(self):
1208 exc = py.test.raises(SyntaxError, self.simple_test, "*a, *b = [1, 2]",
1209 None, None).value
1210 assert exc.msg == "multiple starred expressions in assignment"
1211 exc = py.test.raises(SyntaxError, self.simple_test,
1212 "[*b, *c] = range(10)", None, None).value
1213 assert exc.msg == "multiple starred expressions in assignment"
1214 assert exc.offset == 6
1215
1216 exc = py.test.raises(SyntaxError, self.simple_test, "for *a in x: pass",
1217 None, None).value
1218 assert exc.msg == "starred assignment target must be in a list or tuple"
1219
1220 s = ", ".join("a%d" % i for i in range(1<<8)) + ", *rest = range(1<<8 + 1)"
1221 exc = py.test.raises(SyntaxError, self.simple_test, s, None,
1222 None).value
1223 assert exc.msg == "too many expressions in star-unpacking assignment"
1224 s = ", ".join("a%d" % i for i in range(1<<8 + 1)) + ", *rest = range(1<<8 + 2)"
1225 exc = py.test.raises(SyntaxError, self.simple_test, s, None,
1226 None).value
1227 assert exc.msg == "too many expressions in star-unpacking assignment"
1228
1229 def test_list_compr_or(self):
1230 yield self.st, 'x = list(d for d in [1] or [])', 'x', [1]
1231 yield self.st, 'y = [d for d in [1] or []]', 'y', [1]
1232
1233 def test_yield_from(self):
1234 test = """if 1:
1235 def f():
1236 yield from range(3)
1237 def g():
1238 return list(f())
1239 """
1240 yield self.st, test, "g()", range(3)
1241
1242 def test__class__global(self):
1243 source = """if 1:
1244 class X:
1245 global __class__
1246 """
1247 py.test.raises(SyntaxError, self.simple_test, source, None, None)
1248 # XXX this raises "'global __class__' inside a class statement
1249 # is not implemented in PyPy". The reason it is not is that it
1250 # seems we need to refactor some things to implement it exactly
1251 # like CPython, and I seriously don't think there is a point
1252 #
1253 # Another case which so far works on CPython but not on PyPy:
1254 #class X:
1255 # __class__ = 42
1256 # def f(self):
1257 # return __class__
1258 #assert X.__dict__['__class__'] == 42
1259 #assert X().f() is X
1260
1261 def test_error_message_1(self):
1262 source = """if 1:
1263 async def f():
1264 {await a for a in b}
1265 """
1266 self.simple_test(source, "None", None)
1267
1268 def test_await_in_nested(self):
1269 source = """if 1:
1270 async def foo():
1271 def bar():
1272 [i for i in await items]
1273 """
1274 e = py.test.raises(SyntaxError, self.simple_test, source, "None", None)
1275
1276 def test_async_in_nested(self):
1277 source = """if 1:
1278 async def foo():
1279 def bar():
1280 [i async for i in items]
1281 """
1282 e = py.test.raises(SyntaxError, self.simple_test, source, "None", None)
1283 source = """if 1:
1284 async def foo():
1285 def bar():
1286 {i async for i in items}
1287 """
1288 e = py.test.raises(SyntaxError, self.simple_test, source, "None", None)
1289 source = """if 1:
1290 async def foo():
1291 def bar():
1292 {i: i+1 async for i in items}
1293 """
1294 e = py.test.raises(SyntaxError, self.simple_test, source, "None", None)
1295 source = """if 1:
1296 async def foo():
1297 def bar():
1298 (i async for i in items)
1299 """
1300 # ok!
1301 self.simple_test(source, "None", None)
1302
1303 def test_not_async_function_error(self):
1304 source = """
1305 async with x:
1306 pass
1307 """
1308 with py.test.raises(SyntaxError):
1309 self.simple_test(source, "None", None)
1310
1311 source = """
1312 async for i in x:
1313 pass
1314 """
1315 with py.test.raises(SyntaxError):
1316 self.simple_test(source, "None", None)
1317
1318 source = """
1319 def f():
1320 async with x:
1321 pass
1322 """
1323 with py.test.raises(SyntaxError):
1324 self.simple_test(source, "None", None)
1325
1326 source = """
1327 def f():
1328 async for i in x:
1329 pass
1330 """
1331 with py.test.raises(SyntaxError):
1332 self.simple_test(source, "None", None)
1333
1334 def test_load_classderef(self):
1335 source = """if 1:
1336 def f():
1337 x = 42
1338 class X:
1339 locals()["x"] = 43
1340 y = x
1341 return X.y
1342 """
1343 yield self.st, source, "f()", 43
1344
1345 def test_fstring(self):
1346 yield self.st, """x = 42; z = f'ab{x}cd'""", 'z', 'ab42cd'
1347 yield self.st, """z = f'{{'""", 'z', '{'
1348 yield self.st, """z = f'}}'""", 'z', '}'
1349 yield self.st, """z = f'x{{y'""", 'z', 'x{y'
1350 yield self.st, """z = f'x}}y'""", 'z', 'x}y'
1351 yield self.st, """z = f'{{{4*10}}}'""", 'z', '{40}'
1352 yield self.st, r"""z = fr'x={4*10}\n'""", 'z', 'x=40\\n'
1353
1354 yield self.st, """x = 'hi'; z = f'{x}'""", 'z', 'hi'
1355 yield self.st, """x = 'hi'; z = f'{x!s}'""", 'z', 'hi'
1356 yield self.st, """x = 'hi'; z = f'{x!r}'""", 'z', "'hi'"
1357 yield self.st, """x = 'hi'; z = f'{x!a}'""", 'z', "'hi'"
1358
1359 yield self.st, """x = 'hi'; z = f'''{\nx}'''""", 'z', 'hi'
1360
1361 yield self.st, """x = 'hi'; z = f'{x:5}'""", 'z', 'hi '
1362 yield self.st, """x = 42; z = f'{x:5}'""", 'z', ' 42'
1363 yield self.st, """x = 2; z = f'{5:{x:+1}0}'""", 'z', (' ' * 18 + '+5')
1364
1365 yield self.st, """z=f'{"}"}'""", 'z', '}'
1366
1367 yield self.st, """z=f'{f"{0}"*3}'""", 'z', '000'
1368
1369 def test_fstring_debugging(self):
1370 yield self.st, """x = 1;z = f'T: {x = }'""", 'z', 'T: x = 1'
1371
1372 def test_fstring_error(self):
1373 py.test.raises(SyntaxError, self.run, "f'{}'")
1374 py.test.raises(SyntaxError, self.run, "f'{ \t }'")
1375 py.test.raises(SyntaxError, self.run, "f'{5#}'")
1376 py.test.raises(SyntaxError, self.run, "f'{5)#}'")
1377 py.test.raises(SyntaxError, self.run, "f'''{5)\n#}'''")
1378 py.test.raises(SyntaxError, self.run, "f'\\x'")
1379
1380 def test_fstring_encoding(self):
1381 src = """# -*- coding: latin-1 -*-\nz=ord(f'{"\xd8"}')\n"""
1382 yield self.st, src, 'z', 0xd8
1383 src = """# -*- coding: utf-8 -*-\nz=ord(f'{"\xc3\x98"}')\n"""
1384 yield self.st, src, 'z', 0xd8
1385
1386 src = """z=ord(f'\\xd8')"""
1387 yield self.st, src, 'z', 0xd8
1388 src = """z=ord(f'\\u00d8')"""
1389 yield self.st, src, 'z', 0xd8
1390
1391 src = """# -*- coding: latin-1 -*-\nz=ord(f'\xd8')\n"""
1392 yield self.st, src, 'z', 0xd8
1393 src = """# -*- coding: utf-8 -*-\nz=ord(f'\xc3\x98')\n"""
1394 yield self.st, src, 'z', 0xd8
1395
1396 def test_fstring_encoding_r(self):
1397 src = """# -*- coding: latin-1 -*-\nz=ord(fr'{"\xd8"}')\n"""
1398 yield self.st, src, 'z', 0xd8
1399 src = """# -*- coding: utf-8 -*-\nz=ord(rf'{"\xc3\x98"}')\n"""
1400 yield self.st, src, 'z', 0xd8
1401
1402 src = """z=fr'\\xd8'"""
1403 yield self.st, src, 'z', "\\xd8"
1404 src = """z=rf'\\u00d8'"""
1405 yield self.st, src, 'z', "\\u00d8"
1406
1407 src = """# -*- coding: latin-1 -*-\nz=ord(rf'\xd8')\n"""
1408 yield self.st, src, 'z', 0xd8
1409 src = """# -*- coding: utf-8 -*-\nz=ord(fr'\xc3\x98')\n"""
1410 yield self.st, src, 'z', 0xd8
1411
1412 def test_fstring_bug(self):
1413 yield self.st, "count=5; x = f'time{\"s\" if count > 1 else \"\"}'", "x", "times"
1414
1415 def test_func_defaults_lineno(self):
1416 # like CPython 3.6.9 (at least), check that '''def f(
1417 # x = 5,
1418 # y = 6,
1419 # ):'''
1420 # generates the tuple (5, 6) as a constant for the defaults,
1421 # but with the lineno for the last item (here the 6). There
1422 # is no lineno for the other items, of course, because the
1423 # complete tuple is loaded with just one LOAD_CONST.
1424 yield self.simple_test, """\
1425 def fdl(): # line 1
1426 def f( # line 2
1427 x = 5, # line 3
1428 y = 6 # line 4
1429 ): # line 5
1430 pass # line 6
1431 import dis
1432 co = fdl.__code__
1433 x = [y for (x, y) in dis.findlinestarts(co)]
1434 """, 'x', [4]
1435
1436 def test_instruction_positions(self):
1437 yield self.simple_test, """\
1438 def function():
1439 return (
1440 a +
1441 b +
1442 c * (
1443 d + 2
1444 )
1445 )
1446
1447 co = function.__code__
1448 positions = co.co_positions()
1449 """, 'positions', [
1450 (3, 3, 8, 9),
1451 (4, 4, 8, 9),
1452 (3, 4, 8, 9),
1453 (5, 5, 11, 12),
1454 (6, 6, 12, 13),
1455 (6, 6, 16, 17),
1456 (6, 6, 12, 17),
1457 (5, 7, 11, 12),
1458 (3, 7, 8, 12),
1459 (2, 8, 4, 5)
1460 ]
1461
1462 def test_attribute_position_multiline(self):
1463 # LOAD_ATTR should get the position of the attribute name,
1464 # not the position of the object it's accessed on
1465 yield self.simple_test, """\
1466 def function():
1467 return (
1468 o.
1469 a
1470 )
1471 co = function.__code__
1472 result = list(co.co_positions())[1]
1473 """, 'result', (4, 4, 8, 9)
1474
1475 def test_load_method_position_multiline(self):
1476 # LOAD_METHOD should get the position of the method name,
1477 # not the position of the object
1478 yield self.simple_test, """\
1479 def fmeth(): # line 1
1480 ( # line 2
1481 o. # line 3
1482 m # line 4
1483 )() # line 5
1484 import dis
1485 co = fmeth.__code__
1486 opcodes = [i.opname for i in dis.get_instructions(co)]
1487 positions = list(co.co_positions())
1488 result = positions[opcodes.index('LOAD_METHOD')]
1489 """, 'result', (4, 4, 8, 9)
1490
1491 def test_augassign_attribute_position_multiline(self):
1492 # LOAD_ATTR and STORE_ATTR in augmented assignment should get the
1493 # position of the attribute name, not the object
1494 yield self.simple_test, """\
1495 def faug(): # line 1
1496 ( # line 2
1497 o. # line 3
1498 a # line 4
1499 ) += 1 # line 5
1500 import dis
1501 co = faug.__code__
1502 opcodes = [i.opname for i in dis.get_instructions(co)]
1503 positions = list(co.co_positions())
1504 load_idx = opcodes.index('LOAD_ATTR')
1505 store_idx = opcodes.index('STORE_ATTR')
1506 result = (positions[load_idx], positions[store_idx])
1507 """, 'result', ((4, 4, 8, 9), (4, 4, 8, 9))
1508
1509 def test_many_args(self):
1510 args = ["a%i" % i for i in range(300)]
1511 argdef = ", ".join(args)
1512 res = "+".join(args)
1513 callargs = ", ".join(str(i) for i in range(300))
1514
1515 source1 = """def f(%s):
1516 return %s
1517 x = f(%s)
1518 """ % (argdef, res, callargs)
1519 source2 = """def f(%s):
1520 return %s
1521 x = f(*(%s))
1522 """ % (argdef, res, callargs)
1523
1524 yield self.simple_test, source1, 'x', sum(range(300))
1525 yield self.simple_test, source2, 'x', sum(range(300))
1526
1527 def test_bug_crash_annotations(self):
1528 yield self.simple_test, """\
1529 def func():
1530 bar = None
1531 class Foo:
1532 bar: int = 0 # removing type annotation make the error disappear
1533 def get_bar(self):
1534 return bar
1535 """, '1', 1
1536
1537 def test_walrus_operator(self):
1538 yield (self.simple_test, "(x := 1)", "x", 1)
1539 yield (self.simple_test, "y = (x := 1) + 5", "x+y", 7)
1540 yield (self.simple_test, "len(foobar := [])", "foobar", [])
1541
1542 yield (self.error_test, "(l[1] := 5)", SyntaxError)
1543
1544 yield (self.simple_test, """\
1545 def foo():
1546 [(y := x) for x in range(5)]
1547 return y
1548 """, "foo()", 4)
1549
1550 yield (self.simple_test, """\
1551 def foo():
1552 global y
1553 [(y := x) for x in range(5)]
1554 return y
1555 """, "foo() + y", 8)
1556
1557 yield (self.simple_test, """\
1558 [(y := x) for x in range(5)]
1559 """, "y", 4)
1560
1561 yield (self.error_test, """\
1562 class A:
1563 [(y := x) for y in range(5)]""", SyntaxError)
1564
1565 yield (self.error_test, "[(x := 5) for x in range(5)]", SyntaxError)
1566
1567 yield (self.error_test, "[i for i in range(5) if (j := 0) for j in range(5)]", SyntaxError)
1568
1569 yield (self.error_test, "[i for i in (i := range(5))]", SyntaxError)
1570
1571 def test_walrus_operator_error_msg(self):
1572 with raises(SyntaxError) as info:
1573 self.simple_test("(() := 1)", None, None)
1574 assert info.value.msg == "cannot use assignment expressions with tuple"
1575 with raises(SyntaxError) as info:
1576 self.simple_test("((lambda : 1) := 1)", None, None)
1577 assert info.value.msg == "cannot use assignment expressions with lambda"
1578
1579 def test_extended_unpacking_on_flow_statements(self):
1580 yield (self.simple_test, """\
1581 def foo(*args):
1582 return 1, *args
1583 """, "foo(2, 3)", (1, 2, 3))
1584 yield (self.simple_test, """\
1585 def foo(*args):
1586 yield 1, *args
1587 """, "next(foo(2, 3))", (1, 2, 3))
1588
1589 def test_extended_unpacking_on_flow_statements_invalid(self):
1590 with raises(SyntaxError) as info:
1591 self.simple_test("""\
1592 def foo(*args):
1593 yield from 1, *args
1594 """, None, None)
1595
1596 def test_dict_comprehension_evaluation_order(self):
1597 yield (self.simple_test, """\
1598 def f():
1599 l = [1, 2, 3, 4, 5, 6]
1600 return {l.pop() : l.pop() for i in range(3)}
1601 """, "f()", {6: 5, 4: 3, 2: 1})
1602
1603 def test_var_annot_rhs(self):
1604 yield (self.simple_test, "x: tuple = 1, 2", "x", (1, 2))
1605 yield (self.simple_test, """\
1606 def f():
1607 x: int = yield 'hel'
1608 yield x
1609
1610 gen = f()
1611 """, "next(gen) + gen.send('lo')", "hello")
1612 yield (self.simple_test, """\
1613 rest = 2, 3
1614 x: tuple = 1, *rest, 4
1615 """, "x", (1, 2, 3, 4))
1616
1617 def test_newbytecode_for_loop(self):
1618 func = """def f():
1619 res = 0
1620 for i in range(10):
1621 res += i
1622 return res
1623 """
1624 yield self.st, func, "f()", 45
1625
1626 def test_newbytecode_for_loop_break(self):
1627 func = """def f():
1628 res = 0
1629 for i in range(10000):
1630 if i >= 10:
1631 break
1632 res += i
1633 return res
1634 """
1635 yield self.st, func, "f()", 45
1636
1637 def test_newbytecode_for_loop_continue(self):
1638 func = """def f():
1639 res = 0
1640 for i in range(20):
1641 if i >= 10:
1642 continue
1643 res += i
1644 return res
1645 """
1646 yield self.st, func, "f()", 45
1647
1648 def test_newbytecode_while_loop_break(self):
1649 func = """def f():
1650 res = 0
1651 i = 0
1652 while i < 10000:
1653 if i >= 10:
1654 break
1655 res += i
1656 i += 1
1657 return res
1658 """
1659 yield self.st, func, "f()", 45
1660
1661 def test_newbytecode_for_loop_return(self):
1662 func = """def f():
1663 res = 0
1664 for i in range(10000):
1665 if i >= 10:
1666 return res
1667 res += i
1668 """
1669 yield self.st, func, "f()", 45
1670
1671 def test_newbytecode_finally(self):
1672 func = """def f():
1673 global a
1674 try:
1675 return
1676 finally:
1677 a = 5
1678
1679 def g():
1680 f()
1681 return a
1682 """
1683 yield self.st, func, "g()", 5
1684
1685 def test_newbytecode_finally_exception(self):
1686 func = """def f():
1687 global a
1688 try:
1689 raise ValueError
1690 finally:
1691 a = 5
1692
1693 def g():
1694 try:
1695 f()
1696 except Exception:
1697 pass
1698 return a
1699 """
1700 yield self.st, func, "g()", 5
1701
1702 def test_newbytecode_break_in_except(self):
1703 func = """def g():
1704 res = 0
1705 for i in range(100):
1706 try:
1707 h(i)
1708 except ValueError:
1709 break
1710 res += i
1711 return res
1712
1713 def h(i):
1714 if i >= 10:
1715 raise ValueError
1716 """
1717 yield self.st, func, "g()", 45
1718
1719 def test_newbytecode_break_in_except_named(self):
1720 func = """def g():
1721 res = 0
1722 for i in range(100):
1723 try:
1724 h(i)
1725 except ValueError as e:
1726 break
1727 res += i
1728 return res
1729
1730 def h(i):
1731 if i >= 10:
1732 raise ValueError
1733 """
1734 yield self.st, func, "g()", 45
1735
1736 def test_newbytecode_return_in_except(self):
1737 func = """def g():
1738 res = 0
1739 for i in range(100):
1740 try:
1741 h(i)
1742 except ValueError:
1743 return res
1744 res += i
1745
1746 def h(i):
1747 if i >= 10:
1748 raise ValueError
1749 """
1750 yield self.st, func, "g()", 45
1751
1752 def test_newbytecode_return_in_except_named(self):
1753 func = """def g():
1754 res = 0
1755 for i in range(100):
1756 try:
1757 h(i)
1758 except ValueError as e:
1759 return res
1760 res += i
1761 return res
1762
1763 def h(i):
1764 if i >= 10:
1765 raise ValueError
1766 """
1767 yield self.st, func, "g()", 45
1768
1769 def test_newbytecode_return_in_except_body(self):
1770 func = """def g():
1771 res = 0
1772 for i in range(20):
1773 try:
1774 return i
1775 except:
1776 pass
1777 return res
1778 """
1779 yield self.st, func, "g()", 0
1780
1781 def test_newbytecode_continue_in_try_finally(self):
1782 func = """def g():
1783 res = 0
1784 for i in range(20):
1785 try:
1786 continue
1787 finally:
1788 res += i
1789 return res
1790 """
1791 yield self.st, func, "g()", 190
1792
1793 def test_newbytecode_continue_in_finally(self):
1794 func = """def g():
1795 res = 0
1796 for i in range(20):
1797 try:
1798 h(i)
1799 finally:
1800 res += i
1801 continue
1802 return res
1803
1804 def h(i):
1805 if i >= 10:
1806 raise ValueError
1807 """
1808 yield self.st, func, "g()", 190
1809
1810 def test_newbytecode_blocktype_try2(self):
1811 func = """def g():
1812 res = 0
1813 for i in range(20):
1814 try:
1815 return res
1816 finally:
1817 res += i
1818 if i < 10:
1819 continue
1820 return res
1821 """
1822 yield self.st, func, "g()", 45
1823
1824 def test_newbytecode_named_try_bug(self):
1825 func = """def g():
1826 try:
1827 raise StopIteration
1828 except StopIteration as e:
1829 assert 1
1830 """
1831 self.st(func, "g()", None)
1832
1833 def test_newbytecode_with_basic(self):
1834 func = """def g():
1835 class ContextManager:
1836 def __enter__(self, *args):
1837 return self
1838 def __exit__(self, *args):
1839 pass
1840
1841 x = 0
1842 with ContextManager():
1843 x = 6
1844 return x
1845 """
1846 self.st(func, "g()", 6)
1847
1848 def test_newbytecode_with_return(self):
1849 func = """class ContextManager:
1850 def __enter__(self, *args):
1851 return self
1852 def __exit__(self, *args):
1853 pass
1854
1855 def g():
1856 with ContextManager():
1857 return 8
1858 """
1859 self.st(func, "g()", 8)
1860
1861 def test_newbytecode_with_continue(self):
1862 func = """def g():
1863 class ContextManager:
1864 def __enter__(self, *args):
1865 return self
1866 def __exit__(self, typ, val, tb):
1867 nonlocal res
1868 res += i
1869 res = 0
1870 for i in range(20):
1871 with ContextManager() as b:
1872 continue
1873 return res
1874 """
1875 self.st(func, "g()", 190)
1876
1877 def test_newbytecode_async_for_break(self):
1878 func = """def g():
1879 class X:
1880 def __aiter__(self):
1881 return MyAIter()
1882
1883 class MyAIter:
1884 async def __anext__(self):
1885 return 42
1886 async def f(x):
1887 sum = 0
1888 async for a in x:
1889 sum += a
1890 if sum > 100:
1891 break
1892 return sum
1893 cr = f(X())
1894 try:
1895 cr.send(None)
1896 except StopIteration as e:
1897 return e.value
1898 else:
1899 assert False, "should have raised"
1900 """
1901 self.st(func, "g()", 3 * 42)
1902
1903 def test_newbytecode_async_for(self):
1904 func = """def g():
1905 class X:
1906 def __aiter__(self):
1907 return MyAIter()
1908 class MyAIter:
1909 count = 0
1910 async def __anext__(self):
1911 if self.count == 3:
1912 raise StopAsyncIteration
1913 self.count += 1
1914 return 42
1915 async def f(x):
1916 sum = 0
1917 async for a in x:
1918 sum += a
1919 return sum
1920 cr = f(X())
1921 try:
1922 cr.send(None)
1923 except StopIteration as e:
1924 assert e.value == 42 * 3
1925 else:
1926 assert False, "should have raised"
1927 """
1928 self.st(func, "g()", None)
1929
1930 def test_newbytecode_async_for_other_exception(self):
1931 func = """def g():
1932 class X:
1933 def __aiter__(self):
1934 return MyAIter()
1935 class MyAIter:
1936 count = 0
1937 async def __anext__(self):
1938 if self.count == 3:
1939 1/0
1940 self.count += 1
1941 return 42
1942 async def f(x):
1943 sum = 0
1944 async for a in x:
1945 sum += a
1946 return sum
1947 cr = f(X())
1948 try:
1949 cr.send(None)
1950 except ZeroDivisionError:
1951 pass
1952 else:
1953 assert False, "should have raised"
1954 """
1955 self.st(func, "g()", None)
1956
1957 def test_newbytecode_async_genexpr(self):
1958 func = """def g():
1959 def run_async(coro):
1960 buffer = []
1961 result = None
1962 while True:
1963 try:
1964 buffer.append(coro.send(None))
1965 except StopIteration as ex:
1966 result = ex.args[0] if ex.args else None
1967 break
1968 return buffer, result
1969
1970 async def f(it):
1971 for i in it:
1972 yield i
1973
1974 async def run_gen():
1975 gen = (i + 1 async for i in f([10, 20]))
1976 return [g + 100 async for g in gen]
1977
1978 assert run_async(run_gen()) == ([], [111, 121])
1979 """
1980 self.st(func, "g()", None)
1981
1982 def test_newbytecode_async_with(self):
1983 func = """def g():
1984 seen = []
1985 class X:
1986 async def __aenter__(self):
1987 seen.append('aenter')
1988 async def __aexit__(self, *args):
1989 seen.append('aexit')
1990 async def f(x):
1991 async with x:
1992 return 42
1993 c = f(X())
1994 try:
1995 c.send(None)
1996 except StopIteration as e:
1997 assert e.value == 42
1998 else:
1999 assert False, "should have raised"
2000 assert seen == ['aenter', 'aexit']
2001 """
2002 self.st(func, "g()", None)
2003
2004 def test_newbytecode_async_with_bad_aenter(self):
2005 # GET_AWAITABLE oparg=1: error message should mention __aenter__
2006 space = self.space
2007 w_err = py.test.raises(OperationError, space.appexec, [], r"""():
2008 class CM:
2009 def __aenter__(self): return 123
2010 def __aexit__(self, *e): return 456
2011 async def f():
2012 async with CM(): pass
2013 c = f()
2014 c.send(None)
2015 """)
2016 assert w_err.value.match(space, space.w_TypeError)
2017 msg = w_err.value.errorstr(space)
2018 assert "__aenter__" in msg
2019 assert "does not implement __await__" in msg
2020
2021 def test_newbytecode_async_with_bad_aexit(self):
2022 # GET_AWAITABLE oparg=2: error message should mention __aexit__
2023 space = self.space
2024 w_err = py.test.raises(OperationError, space.appexec, [], r"""():
2025 class CM:
2026 async def __aenter__(self): return self
2027 def __aexit__(self, *e): return 456
2028 async def f():
2029 async with CM(): pass
2030 c = f()
2031 try: c.send(None)
2032 except StopIteration: c.send(None)
2033 """)
2034 assert w_err.value.match(space, space.w_TypeError)
2035 msg = w_err.value.errorstr(space)
2036 assert "__aexit__" in msg
2037 assert "does not implement __await__" in msg
2038
2039 def test_newbytecode_reraise_no_match(self):
2040 space = self.space
2041 space.raises_w(space.w_KeyError,
2042 space.appexec, [], r"""():
2043 try:
2044 {}[1]
2045 except TypeError:
2046 return 2
2047 return 1
2048 """)
2049
2050 def test_newbytecode_reraise_finally(self):
2051 space = self.space
2052 space.raises_w(space.w_KeyError,
2053 space.appexec, [], r"""():
2054 try:
2055 raise KeyError
2056 finally:
2057 pass
2058 return 4
2059 """)
2060
2061 def test_newbytecode_reraise_return(self):
2062 space = self.space
2063 w_res = space.appexec([], r"""():
2064 try:
2065 raise KeyError
2066 finally:
2067 x = 7
2068 return x + 1 # swallow exception
2069 return 4
2070 """)
2071 assert space.int_w(w_res) == 8
2072
2073 def test_newbytecode_reraise_named_except_finally(self):
2074 space = self.space
2075 space.raises_w(space.w_KeyError,
2076 space.appexec, [], r"""():
2077 try:
2078 raise KeyError
2079 except KeyError as e:
2080 raise
2081 return 4
2082 """)
2083
2084 def test_newbytecode_raise_in_except_bug(self):
2085 space = self.space
2086 w_res = space.appexec([], r"""():
2087 try:
2088 try:
2089 raise KeyError
2090 except TypeError:
2091 for i in range(10):
2092 pass
2093 else:
2094 raise KeyError
2095 except KeyError:
2096 return 10
2097 return 0""")
2098 assert space.int_w(w_res) == 10
2099
2100 def test_newbytecode_syntaxerror_attrs(self):
2101 w_args = self.space.appexec([], r"""():
2102 try:
2103 exec('if 1:\n x\n y\n')
2104 except SyntaxError as e:
2105 return e.args
2106 """)
2107 assert self.space.unwrap(w_args) == (
2108 'unindent does not match any outer indentation level',
2109 ('<string>', 3, 2, ' y\n', None, None)) # XXX this could be , 3, 2 as well
2110
2111 def test_finally_lineno_wrong(self):
2112 func = """def f(x): # 1
2113 def f(func):
2114 return func
2115 return f
2116
2117 @f(1)
2118 def finally_wrong_lineno():
2119 try: # 8
2120 return print(1) # 9
2121 finally:
2122 print(2) # 11
2123 print(3) # 12
2124 import dis
2125 co = finally_wrong_lineno.__code__
2126 linestarts = list(dis.findlinestarts(co))
2127 x = [lineno for addr, lineno in linestarts]
2128 """
2129 self.st(func, "x", [8, 9, 11])
2130
2131 def test_lineno1_eval_bug(self):
2132 func = """c = compile('z', '<string>', 'eval')
2133 import dis
2134 x = [lineno for addr, lineno in dis.findlinestarts(c)]
2135 """
2136 self.st(func, "x", [1])
2137
2138 def test_with_lineno_wrong(self):
2139 func = """def with_wrong_lineno():
2140 with ABC():
2141 g()
2142 import dis
2143 co = with_wrong_lineno.__code__
2144 linestarts = list(dis.findlinestarts(co))
2145 x = [lineno for addr, lineno in linestarts]
2146 """
2147 self.st(func, "x", [2, 3, 2])
2148
2149
2150 def test_error_in_dead_code(self):
2151 self.error_test("if 0: break", SyntaxError)
2152 self.error_test("while 0: lambda x, x: 1", SyntaxError)
2153 self.error_test("if 0:\n if 0:\n [x async for x in b]", SyntaxError)
2154 self.error_test("[(i, j) for i in range(5) for j in range(5) if True or (i:=10)]", SyntaxError)
2155
2156 def test_bug_lnotab(self):
2157 func = """
2158 def buggy_lnotab():
2159 for i in x:
2160
2161
2162
2163
2164
2165
2166
2167 1
2168 x = [c for c in buggy_lnotab.__code__.co_lnotab]
2169 """
2170 self.st(func, "x", [0, 1, 8, 8, 2, 248])
2171
2172 def test_lnotab_backwards_in_expr(self):
2173 func = """
2174 def expr_lines(x):
2175 return (x +
2176 1)
2177 x = [c for c in expr_lines.__code__.co_lnotab]
2178 """
2179 self.st(func, "x", [0, 1, 2, 1, 2, 255])
2180
2181 def test_lineno_docstring_class(self):
2182 func = """
2183 def expr_lines(x):
2184 class A:
2185 "abc"
2186 x = [c for c in expr_lines.__code__.co_consts[1].co_lnotab]
2187 """
2188 self.st(func, "x", [8, 1])
2189
2190 def test_lineno_funcdef(self):
2191 func = '''def f():
2192 @decorator
2193 def my_function(
2194 x=x
2195 ):
2196 pass
2197 x = [c for c in f.__code__.co_lnotab]
2198 '''
2199 self.st(func, 'x', [0, 1, 2, 2, 2, 255, 6, 255, 2, 1])
2200
2201 def test_lineno_crash(self):
2202 func = '''
2203 def ie(c, r, fg, cc):
2204 tc = True if cc is False else c in Cc and r in Rc
2205 if tc:
2206 (print("wut") if fg is not None
2207 else None)
2208 import dis
2209 co = ie.__code__
2210 linestarts = list(dis.findlinestarts(co))
2211 x = [lineno for addr, lineno in linestarts]
2212 '''
2213 self.st(func, 'x', [3, 4, 5, 6, 4])
2214
2215
2216 def test_revdb_metavar(self):
2217 self.error_test("7 * $0", SyntaxError)
2218
2219 def test_bug_arguments(self):
2220 func = """
2221 def brokenargs(a=1, /, b=2, *, c):
2222 return [a, b, c]
2223 x = brokenargs(c=3)
2224 """
2225 self.st(func, "x", [1, 2, 3])
2226
2227 def test_keyword_repeated(self):
2228 yield self.error_test, "f(a=c, a=d)", SyntaxError, "keyword argument repeated: a"
2229 yield self.error_test, "class A(metaclass=c, metaclass=d): pass", SyntaxError, "keyword argument repeated: metaclass"
2230
2231 def test_while_false_break(self):
2232 self.st("x=1\nwhile False: break", "x", 1)
2233
2234 def test_cant_annotate_debug(self):
2235 self.error_test("__debug__ : int", SyntaxError, "cannot assign to __debug__")
2236 self.error_test("object.__debug__ : int", SyntaxError, "cannot assign to __debug__")
2237
2238 def test_match(self):
2239 func = """
2240 def f(x):
2241 class A:
2242 y = 13
2243 match x:
2244 case 1.1+2.2j: return "???"
2245 case True: return "True"
2246 case 1: return "hello"
2247 case 3 | 4: return "3 | 4"
2248 case [True]: return "[True]"
2249 case [1,2,3]: return "list[1,2,3]"
2250 case [1]: return "list[1]"
2251 case []: return "emptylist"
2252 case [_]: return "list"
2253 case True | False as b: return b
2254 case a if a: return a
2255 case A.y as z: return z
2256
2257 res=(
2258 f(1),
2259 f(2),
2260 f(['']),
2261 f([1]),
2262 f([1,2,3]),
2263 f([1,2,4]),
2264 f([1,3,4]),
2265 f([2,3,4]),
2266 f([1, 2]),
2267 f([]),
2268 f(True),
2269 f(3),
2270 f(0),
2271 f(False),
2272 f(13),
2273 f(1.1+2.2j),
2274 f([True]),
2275 )
2276 """
2277 self.st(func, "res", (
2278 "hello",
2279 2,
2280 "list",
2281 "list[1]",
2282 "list[1,2,3]",
2283 [1,2,4],
2284 [1,3,4],
2285 [2,3,4],
2286 [1,2],
2287 "emptylist",
2288 "True",
2289 "3 | 4",
2290 None,
2291 False,
2292 13,
2293 '???',
2294 '[True]',
2295 ))
2296
2297 def test_match_sequence_star(self):
2298 func = """
2299 def f(x):
2300 match x:
2301 case [1, *rest, 4, 5]: return rest
2302 case [1, *rest]: return rest
2303 case [*rest, 5]: return rest
2304 case [*rest]: return rest
2305 res=(
2306 f([1, 2, 3, 4, 5]),
2307 f([1, 2, 3]),
2308 f([3, 4, 5]),
2309 f([2, 3, 4]),
2310 )
2311 """
2312 self.st(func, "res", (
2313 [2, 3],
2314 [2, 3],
2315 [3, 4],
2316 [2, 3, 4],
2317 ))
2318
2319 def test_match_mapping(self):
2320 func = """
2321 def f(x):
2322 match x:
2323 case {'x': 42, 'y': 13}: return "{'x': 42, 'y': 13}"
2324 case {'x': 13, **rest}: return rest
2325 case {'x': 7}: return "{'x': 7}"
2326 case {True: 7}: return "{True: 7}"
2327 case {}: return "{}"
2328 case _: return "_"
2329 res=(
2330 f([]), # not a dict: _
2331 f({}), # empty: {}
2332 f({'y': 42}), # no match for key: {}
2333 f({'x': 21}), # no match for value: {}
2334 f({'x': 42, 'y': 7}), # no match for second member's value: {}
2335 f({'x': 42, 'y': 13}), # successful match with 2 members: {'x': 42, 'y': 13}
2336 f({'x': 42, 'y': 13, 'z': 0}), # successful match with 2 members extraneous property: {'x': 42, 'y': 13}
2337 f({'x': 7}), # successful match with a single member: {'x': 7}
2338 f({'x': 7, 'y': 13}), # successful match with a single member and extraneous property: {'x': 7}
2339 f({'x': 13, 'y': 7}), # successful match with rest capture: {'y': 7}
2340 f({True: 7})
2341 )
2342 """
2343 self.st(func, "res", (
2344 "_",
2345 "{}",
2346 "{}",
2347 "{}",
2348 "{}",
2349 "{'x': 42, 'y': 13}",
2350 "{'x': 42, 'y': 13}",
2351 "{'x': 7}",
2352 "{'x': 7}",
2353 {'y': 7},
2354 "{True: 7}",
2355 ))
2356
2357 def test_match_mapping_more(self):
2358 func = """
2359 def f(x):
2360 match x:
2361 case {f.x: 42}: return "self-attribute"
2362 case _: return "_"
2363 f.x = "u"
2364
2365 res=(
2366 f({"u": 42}),
2367 )
2368 """
2369 self.st(func, "res", (
2370 "self-attribute",
2371 ))
2372
2373
2374 def test_match_class(self):
2375 func = """
2376 class C:
2377 def __init__(self, x):
2378 self.x = x
2379 C.__match_args__ = ('x',)
2380
2381 def f(x):
2382 match x:
2383 case C(x) if x is True: return "C(True)"
2384 case C(x=y) if y is False: return "C(False)"
2385 case C(x=z): return "C(x={})".format(z)
2386 case bool(b) if b: return "True"
2387 case bool(): return "False"
2388 res=(
2389 f(True),
2390 f(False),
2391 f(C(True)),
2392 f(C(False)),
2393 f(C(None)),
2394 )
2395 """
2396 self.st(func, "res", (
2397 "True",
2398 "False",
2399 "C(True)",
2400 "C(False)",
2401 "C(x=None)",
2402 ))
2403
2404 def test_match_class_attribute_missing(self):
2405 func = """
2406 class C: pass
2407
2408 def f(x):
2409 match x:
2410 case C(attr=y): return y
2411 c1 = C()
2412 c2 = C()
2413 c2.attr = 12
2414 res=(
2415 f(c1),
2416 f(c2),
2417 )
2418 """
2419 self.st(func, "res", (
2420 None,
2421 12,
2422 ))
2423
2424 def test_match_complex(self):
2425 func = """
2426 class C: pass
2427
2428 def f(x):
2429 match x:
2430 case 0 + 0j:
2431 return 1
2432 res=(
2433 f(0+0j),
2434 f(1+0j),
2435 )
2436 """
2437 self.st(func, "res", (
2438 1,
2439 None,
2440 ))
2441
2442 def test_match_errors(self):
2443 self.error_test("""
2444 match x:
2445 case a: pass
2446 case 1: pass
2447 """, SyntaxError, "name capture 'a' makes remaining patterns unreachable")
2448
2449 def test_kwonly_crash(self):
2450 exc = self.error_test("def f(p1, *k1, k1=100): pass", SyntaxError)
2451 if exc:
2452 assert exc.offset == 12
2453 assert exc.end_offset == 14
2454
2455 def test_unpack_stararg_msg(self):
2456 exc = self.error_test("(*abc) = 1", SyntaxError, "cannot")
2457
2458 def test_intliteral_as_it_always_was(self):
2459 self.st("x = [0x1for x in [1, 2]]", "x", [31])
2460
2461 def test_bug_comprehension_optimization(self):
2462 self.st("x = sorted({j*k for i in range(4) for j, k in [(i+1, i+2)]})", "x", [2, 6, 12, 20])
2463 self.st("x = sorted({j*k for i in range(4) for j in [i+1] for k in [j+1]})", "x", [2, 6, 12, 20])
2464 self.st("[*x] = (j*k for i in range(4) for j in [i+1] for k in [j+1])", "x", [2, 6, 12, 20])
2465
2466 def test_type_with_star_311(self):
2467 self.st("def func1(*args: *(1, )): pass", "func1.__annotations__['args']", 1)
2468
2469 class TestLinenoChanges310(object):
2470 def get_line_numbers(self, source, expected, function=False):
2471 from pypy.tool.dis3 import findlinestarts
2472 space = self.space
2473 code = compile_with_astcompiler(source, 'exec', space, set_debug_flag=False)
2474 if function:
2475 code = code.co_consts[0]
2476 lines = [line for (start, line) in findlinestarts(code)]
2477 min_line = min(lines) - function
2478 got = [line - min_line for line in lines]
2479 # check that there are no two nops with the same lineno
2480 assert got == expected
2481 return code
2482
2483 def test_linestarts_pass(self):
2484 code = self.get_line_numbers("""if x:
2485 pass; pass; pass; pass
2486 else:
2487 pass; pass; pass; pass; pass; pass; pass
2488 pass; pass; pass; pass; pass; pass; pass
2489 pass; pass; pass; pass
2490 pass""", [0, 1, 3, 4, 5, 6])
2491 assert len(code.co_code) == 16 # check that the NOPs have been reduced
2492
2493 def test_while_1(self):
2494 code = self.get_line_numbers("""while 1:
2495 if f(x):
2496 pass
2497 else:
2498 pass
2499 """, [0, 1, 2, 4])
2500 assert len(code.co_code) <= 20 # check that the NOPs have been reduced
2501
2502 def test_duplicate_returns(self):
2503 code = self.get_line_numbers("""
2504 if x:
2505 pass
2506 else:
2507 pass
2508 """, [0, 1, 3])
2509
2510 def test_duplicate_reraise(self):
2511 code = self.get_line_numbers("""
2512 try:
2513 g()
2514 finally:
2515 if h():
2516 pass
2517 else:
2518 pass
2519 """, [0, 1, 3, 4, 6, 3, 4, 6])
2520
2521 def test_loop_return(self):
2522 code = self.get_line_numbers("""
2523 x = 1 # 0
2524 for a in range(2): # 1
2525 if a: # 2
2526 x = 1 # 3
2527 else: # 4
2528 x = 1 # 5
2529 """, [0, 1, 2, 3, 5, 1])
2530
2531 def test_dont_propage_through_exception_handler(self):
2532 code = self.get_line_numbers("""
2533 try:
2534 raise Exception("abc")
2535 except Exception as e:
2536 if reraise:
2537 raise
2538 print("after raise")
2539 """, [0, 1, 2, 3, 4, 5, 2])
2540
2541 def test_nop_for_if0_if1(self):
2542 code = self.get_line_numbers("""
2543 x = 1
2544 while 0:
2545 pass
2546 if 0:
2547 pass
2548 if 1:
2549 pass
2550 while 1:
2551 break
2552 x = 2
2553 """, [0, 1, 3, 5, 6, 7, 8, 9])
2554
2555 def test_async_for(self):
2556 code = self.get_line_numbers("""
2557 async def doit_async():
2558 async for letter in AsyncIteratorWrapper("abc"):
2559 x = letter
2560 y = 42
2561 """, [1, 2, 1, 3], function=True)
2562
2563 def test_break_in_finally(self):
2564 code = self.get_line_numbers("""
2565 for i in range(3):
2566 try:
2567 break # line 7
2568 finally:
2569 f()
2570 """, [0, 1, 2, 4, 0])
2571
2572 def test_return_in_finally(self):
2573 code = self.get_line_numbers("""
2574 def return_in_finally():
2575 try:
2576 return
2577 finally:
2578 f()
2579 """, [1, 2, 4], function=True)
2580
2581 def test_break_to_break(self):
2582 code = self.get_line_numbers("""
2583 TRUE = 1
2584 while TRUE:
2585 while TRUE:
2586 break
2587 break
2588 """, [0, 1, 2, 3, 4, 1])
2589
2590 def test_dead_code_shouldnt_impact_positions(self):
2591 code = self.get_line_numbers("""
2592 def func():
2593 try:
2594 if False:
2595 pass
2596 except Exception:
2597 X
2598 """, [1, 2, 4, 5, 4], function=True)
2599
2600 def test_nested_if_confusion(self):
2601 code = self.get_line_numbers("""
2602 if p:
2603 if a:
2604 if z:
2605 pass
2606 else:
2607 pass
2608 else:
2609 pass
2610 """, [0, 1, 2, 3, 5, 7, 1])
2611
2612 def test_nested_for(self):
2613 code = self.get_line_numbers("""
2614 for i in range(2):
2615 for j in range(3):
2616 x += i * j
2617 print(x)
2618 """, [0, 1, 2, 1, 3])
2619
2620 def test_ignored_const_produces_lineno(self):
2621 code = self.get_line_numbers("""
2622 1
2623 'abc'
2624 (1, 2, 3, None)
2625 """, [0, 1, 2])
2626
2627 def test_assert_bug(self):
2628 code = self.get_line_numbers("""
2629 try:
2630 assert 0, 'hi'
2631 except AssertionError as e:
2632 msg = str(e)
2633 """, [0, 1, 2, 3, 2])
2634
2635 def test_assert_looks_at_constants(self):
2636 code = self.get_line_numbers("""
2637 assert 0,\\
2638 "abc"
2639 pass
2640 """, [0, 1, 0])
2641
2642 def test_match_optimized(self):
2643 code = self.get_line_numbers("""
2644 match x:
2645 case 1 if (
2646
2647 True):
2648 pass
2649 case _:
2650 pass
2651 print()
2652 """, [0, 1, 3, 1, 4, 5, 6, 7])
2653
2654 def test_return_in_with(self):
2655 code = self.get_line_numbers("""
2656 def withreturn():
2657 with C():
2658 return
2659 """, [1, 2, 1], function=True)
2660
2661 def test_func_without_code(self):
2662 code = self.get_line_numbers("""def emptybody():
2663 'abc'
2664 """, [1], function=True)
2665
2666 def test_assignment(self):
2667 code = self.get_line_numbers("""(
2668
2669
2670
2671
2672 o.
2673 a
2674 ) = (
2675 v + w
2676 )
2677 """, [3, 0, 1])
2678
2679 class TestErrorPositions(BaseTestCompiler):
2680 def test_import_star_in_function_position(self):
2681 src = "def f(): from _ import *"
2682 exc = self.error_test(src, SyntaxError)
2683 assert exc.offset == src.find("*") + 1
2684
2685 def test_pos_inner_node_nonsense_walrus(self):
2686 exc = self.error_test("[i for i in range(5) if (juhuu := 0) for juhuu in range(5)]", SyntaxError)
2687 assert exc.offset == 42
2688 assert exc.end_offset == 47
2689
2690 class TestDeadCodeGetsRemoved(TestCompiler):
2691 # check that there is no code emitted when putting all kinds of code into an "if 0:" block
2692 def simple_test(self, source, evalexpr, expected):
2693 from pypy.tool import dis3
2694 c = py.code.Source(source)
2695 source = "if 0:\n" + str(c.indent())
2696
2697 space = self.space
2698 code = compile_with_astcompiler(source, 'exec', space)
2699 dis3.dis(code)
2700 assert len(code.co_code) == 4 # load None, return
2701 assert len(code.co_consts_w) == 1
2702
2703 st = simple_test
2704
2705 def error_test(self, *args):
2706 pass
2707
2708 test_fstring_encoding = test_fstring_encoding_r = test_kwonly = \
2709 test_no_indent = test_many_args = test_var_annot_rhs = \
2710 test_extended_unpacking_fail = lambda self: None
2711
2712 class TestCompilerRevDB(BaseTestCompiler):
2713 spaceconfig = {"translation.reverse_debugger": True}
2714
2715 def test_revdb_metavar(self):
2716 from pypy.interpreter.reverse_debugging import dbstate, setup_revdb
2717 self.space.reverse_debugging = True
2718 try:
2719 setup_revdb(self.space)
2720 dbstate.standard_code = False
2721 dbstate.metavars = [self.space.wrap(6)]
2722 self.simple_test("x = 7*$0", "x", 42)
2723 dbstate.standard_code = True
2724 self.error_test("x = 7*$0", SyntaxError)
2725 finally:
2726 self.space.reverse_debugging = False
2727
2728
2729 class AppTestCompiler:
2730
2731 def test_docstring_not_loaded(self):
2732 import io, dis, sys
2733 ns = {}
2734 exec("def f():\n 'hi'", ns)
2735 f = ns["f"]
2736 save = sys.stdout
2737 sys.stdout = output = io.StringIO()
2738 try:
2739 dis.dis(f)
2740 finally:
2741 sys.stdout = save
2742 assert "0 ('hi')" not in output.getvalue()
2743
2744 def test_assert_with_tuple_arg(self):
2745 try:
2746 assert False, (3,)
2747 except AssertionError as e:
2748 assert str(e) == "(3,)"
2749
2750 # BUILD_LIST_FROM_ARG is PyPy specific
2751 @py.test.mark.skipif('config.option.runappdirect')
2752 def test_build_list_from_arg_length_hint(self):
2753 hint_called = [False]
2754 class Foo(object):
2755 def __iter__(self):
2756 return FooIter()
2757 class FooIter:
2758 def __init__(self):
2759 self.i = 0
2760 def __length_hint__(self):
2761 hint_called[0] = True
2762 return 5
2763 def __iter__(self):
2764 return self
2765 def __next__(self):
2766 if self.i < 5:
2767 res = self.i
2768 self.i += 1
2769 return res
2770 raise StopIteration
2771 l = [a for a in Foo()]
2772 assert hint_called[0]
2773 assert l == list(range(5))
2774
2775 def test_unicode_in_source(self):
2776 import sys
2777 d = {}
2778 exec('# -*- coding: utf-8 -*-\n\nu = "\xf0\x9f\x92\x8b"', d)
2779 assert len(d['u']) == 4
2780
2781 def test_kw_defaults_None(self):
2782 import _ast
2783 source = "def foo(self, *args, name): pass"
2784 ast = compile(source, '', 'exec', _ast.PyCF_ONLY_AST)
2785 # compiling the produced AST previously triggered a crash
2786 compile(ast, '', 'exec')
2787
2788 def test_error_yield(self):
2789 # These are OK!
2790 compile("def g(): [x for x in [(yield 1)]]", "<test case>", "exec")
2791 compile("def g(): [x for x in [(yield from ())]]", "<test case>", "exec")
2792
2793 def check(snippet, error_msg, offset=-1, end_offset=-1):
2794 try:
2795 compile(snippet, "<test case>", "exec")
2796 except SyntaxError as exc:
2797 assert exc.msg == error_msg
2798 assert exc.lineno == 1
2799 if offset != -1:
2800 assert exc.offset == offset
2801 if end_offset != -1:
2802 assert exc.end_offset == end_offset
2803 else:
2804 assert False, snippet
2805
2806 check("def g(): [(yield x) for x in ()]",
2807 "'yield' inside list comprehension", 12, 19)
2808 check("def g(): [x for x in () if not (yield x)]",
2809 "'yield' inside list comprehension", 33, 40)
2810 check("def g(): [y for x in () for y in [(yield x)]]",
2811 "'yield' inside list comprehension", 36, 43)
2812 check("def g(): {(yield x) for x in ()}",
2813 "'yield' inside set comprehension", 12, 19)
2814 check("def g(): {(yield x): x for x in ()}",
2815 "'yield' inside dict comprehension", 12, 19)
2816 check("def g(): {x: (yield x) for x in ()}",
2817 "'yield' inside dict comprehension", 15, 22)
2818 check("def g(): ((yield x) for x in ())",
2819 "'yield' inside generator expression", 12, 19)
2820 check("def g(): [(yield from x) for x in ()]",
2821 "'yield' inside list comprehension", 12, 24)
2822 check("class C: [(yield x) for x in ()]",
2823 "'yield' inside list comprehension", 12, 19)
2824 check("[(yield abcdefghi) for abcdefghi in ()]",
2825 "'yield' inside list comprehension", 3, 18)
2826
2827 def test_syntax_warnings_missing_comma(self):
2828 import warnings
2829
2830 cases = [
2831 '[(1, 2) (3, 4)]',
2832 '[[1, 2] (3, 4)]',
2833 '[{1, 2} (3, 4)]',
2834 '[{1: 2} (3, 4)]',
2835 '[[i for i in range(5)] (3, 4)]',
2836 '[{i for i in range(5)} (3, 4)]',
2837 '[(i for i in range(5)) (3, 4)]',
2838 '[{i: i for i in range(5)} (3, 4)]',
2839 '[f"{1}" (3, 4)]',
2840 '["abc" (3, 4)]',
2841 '[b"abc" (3, 4)]',
2842 '[123 (3, 4)]',
2843 '[12.3 (3, 4)]',
2844 '[12.3j (3, 4)]',
2845 '[None (3, 4)]',
2846 '[True (3, 4)]',
2847 '[... (3, 4)]',
2848 '[{1, 2} [i, j]]',
2849 '[{i for i in range(5)} [i, j]]',
2850 '[(i for i in range(5)) [i, j]]',
2851 '[(lambda x, y: x) [i, j]]',
2852 '[123 [i, j]]',
2853 '[12.3 [i, j]]',
2854 '[12.3j [i, j]]',
2855 '[None [i, j]]',
2856 '[True [i, j]]',
2857 '[... [i, j]]',
2858 '(1,2,3)[...]'
2859 ]
2860 for case in cases:
2861 with warnings.catch_warnings(record=True) as w:
2862 ns = {'i': 1, 'j': 1}
2863 exec("def foo(): %s" % case, ns)
2864 try:
2865 ns['foo']()
2866 except TypeError as exc:
2867 exc_message = exc.args[0]
2868 else:
2869 exc_message = None
2870
2871 assert len(w) == 1, case
2872 assert issubclass(w[-1].category, SyntaxWarning)
2873 assert exc_message is not None
2874 initial_part, _, info_part = w[-1].message.args[0].partition("not ")
2875 assert initial_part in exc_message
2876
2877 def test_syntax_warnings_is_with_literal(self):
2878 import warnings
2879
2880 cases = [
2881 ("x is 1", "is"),
2882 ("x is 'thing'", "is"),
2883 ("1 is x", "is"),
2884 ("x is y is 1", "is"),
2885 ("x is not 1", "is not")
2886 ]
2887 for case, operator in cases:
2888 with warnings.catch_warnings(record=True) as w:
2889 compile(case, '<testcase>', 'eval')
2890 assert len(w) == 1, case
2891 assert issubclass(w[-1].category, SyntaxWarning)
2892 assert operator in w[-1].message.args[0]
2893
2894 def test_syntax_warnings_assertions(self):
2895 import warnings
2896 with warnings.catch_warnings(record=True) as w:
2897 compile("assert (a, b)", '<testcase>', 'exec')
2898 assert len(w) == 1, case
2899 assert issubclass(w[-1].category, SyntaxWarning)
2900 assert "assertion is always true" in w[-1].message.args[0]
2901
2902 def test_syntax_warnings_invalid_literal_as_error(self):
2903 import warnings
2904 with warnings.catch_warnings():
2905 warnings.filterwarnings('error', category=SyntaxWarning)
2906 raises(SyntaxError, compile, '9and x', '<testcase>', 'exec')
2907
2908 def test_syntax_warnings_false_positives(self):
2909 import warnings
2910
2911 with warnings.catch_warnings():
2912 warnings.filterwarnings('error', category=SyntaxWarning)
2913 compile('[(lambda x, y: x) (3, 4)]', '<testcase>', 'exec')
2914 compile('[[1, 2] [i]]', '<testcase>', 'exec')
2915 compile('[[1, 2] [0]]', '<testcase>', 'exec')
2916 compile('[[1, 2] [True]]', '<testcase>', 'exec')
2917 compile('[[1, 2] [1:2]]', '<testcase>', 'exec')
2918 compile('[{(1, 2): 3} [i, j]]', '<testcase>', 'exec')
2919 compile('x is some_other_stuff', '<testcase>', 'exec')
2920 compile('x is True', '<testcase>', 'exec')
2921 compile('None is x', '<testcase>', 'exec')
2922 compile('x is y is False', '<testcase>', 'exec')
2923 compile('x is y is ...', '<testcase>', 'exec')
2924 compile('assert a, b', '<testcase>', 'exec')
2925 compile('assert (), b', '<testcase>', 'exec')
2926
2927 def test_top_level_async(self):
2928 import _ast
2929 import inspect
2930 import textwrap
2931
2932 statements = [
2933 """
2934 await x
2935 """,
2936 """
2937 foo = bar(await x)
2938 """,
2939 """
2940 async for x in y:
2941 print(x)
2942 """,
2943 """
2944 async with bar as baz:
2945 print(await baz.show())
2946 """,
2947 """
2948 [x async for x in y]
2949 foo = await bar(x async for x in y)
2950 baz = {x async for x in z} | {x: y async for x, y in z.items()}.keys()
2951 """,
2952 ]
2953 for statement in statements:
2954 code = compile(
2955 textwrap.dedent(statement),
2956 '<testcast>',
2957 'exec',
2958 flags=_ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
2959 )
2960 assert code.co_flags & inspect.CO_COROUTINE
2961
2962 for statement in statements:
2963 try:
2964 code = compile(
2965 textwrap.dedent(statement),
2966 '<test case>',
2967 'exec'
2968 )
2969 except SyntaxError as exc:
2970 pass
2971 else:
2972 assert False, "this case shouldn't compile: %s" % statement
2973
2974 def test_top_level_async_invalid_cases(self):
2975 import _ast
2976 import textwrap
2977
2978 statements = [
2979 """def f(): await arange(10)\n""",
2980 """def f(): [x async for x in arange(10)]\n""",
2981 """def f(): [await x async for x in arange(10)]\n""",
2982 """def f():
2983 async for i in arange(1):
2984 a = 1
2985 """,
2986 """def f():
2987 async with asyncio.Lock() as l:
2988 a = 1
2989 """,
2990 ]
2991
2992 for flags in [0, _ast.PyCF_ALLOW_TOP_LEVEL_AWAIT]:
2993 for statement in statements:
2994 try:
2995 code = compile(
2996 textwrap.dedent(statement),
2997 '<test case>',
2998 'exec',
2999 flags=flags
3000 )
3001 except SyntaxError as exc:
3002 pass
3003 else:
3004 assert False, "this case shouldn't compile: %s" % statement
3005
3006 def test_top_level_async_ensure_generator(self):
3007 import _ast
3008 import textwrap
3009 from types import AsyncGeneratorType
3010
3011 source = textwrap.dedent("""
3012 async def ticker():
3013 for i in range(10):
3014 yield i
3015 await asyncio.sleep(0)
3016 """)
3017
3018 code = compile(
3019 source,
3020 '<test case>',
3021 'exec',
3022 flags=_ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
3023 )
3024 namespace = {}
3025 exec(code, namespace)
3026 ticker = namespace['ticker']
3027 assert isinstance(ticker(), AsyncGeneratorType)
3028
3029 def test_bug_hanging_compiler(self):
3030 source = '''
3031 def endless_looping():
3032 while True: continue
3033 '''
3034 compile(source, '<test>', 'exec')
3035
3036
3037 class TestOptimizations:
3038 def count_instructions(self, source):
3039 code, blocks = generate_function_code(source, self.space)
3040 self._code = code
3041 self._blocks = blocks
3042 instrs = []
3043 for block in blocks:
3044 instrs.extend(block.instructions)
3045 # print instrs
3046 counts = {}
3047 for instr in instrs:
3048 counts[instr.opcode] = counts.get(instr.opcode, 0) + 1
3049 return counts
3050
3051 def test_forward_cond_jump_to_jump(self):
3052 source1 = """def jumpymcjumpface():
3053 if a:
3054 if (c
3055 or d):
3056 foo()
3057 else:
3058 baz()
3059 return
3060 """
3061 source2 = """def springer():
3062 while a:
3063 # Intentionally use two-line expression to test issue37213.
3064 if (c
3065 or d):
3066 a = foo()
3067 return
3068 """
3069 for source in source1, source2:
3070 code, blocks = generate_function_code(source, self.space)
3071 instrs = []
3072 for block in blocks:
3073 instrs.extend(block.instructions)
3074 offset = 0
3075 offsets = {}
3076 for instr in instrs:
3077 offsets[offset] = instr
3078 offset += instr.size()
3079 for instr in instrs:
3080 if instr.opcode == ops.POP_JUMP_IF_FALSE:
3081 if instr.arg * 2 == offset: # points to end, return will be inserted later
3082 continue
3083 target = offsets[instr.arg * 2]
3084 assert target.opcode != ops.JUMP_FORWARD and target.opcode != ops.JUMP_ABSOLUTE
3085
3086 def test_const_fold_subscr(self):
3087 source = """def f():
3088 return (0, 1)[0]
3089 """
3090 counts = self.count_instructions(source)
3091 assert counts == {ops.LOAD_CONST: 1, ops.RETURN_VALUE: 1}
3092
3093 source = """def f():
3094 return (0, 1)[:2]
3095 """
3096 # Just checking this doesn't crash out
3097 self.count_instructions(source)
3098
3099 def test_const_fold_unicode_subscr(self, monkeypatch):
3100 source = """def f():
3101 return "abc"[0]
3102 """
3103 counts = self.count_instructions(source)
3104 if 0: # xxx later?
3105 assert counts == {ops.LOAD_CONST: 1, ops.RETURN_VALUE: 1}
3106
3107 # getitem outside of the BMP should not be optimized
3108 source = """def f():
3109 return "\U00012345"[0]
3110 """
3111 counts = self.count_instructions(source)
3112 assert counts == {ops.LOAD_CONST: 2, ops.BINARY_SUBSCR: 1,
3113 ops.RETURN_VALUE: 1}
3114
3115 source = """def f():
3116 return "\U00012345abcdef"[3]
3117 """
3118 counts = self.count_instructions(source)
3119 assert counts == {ops.LOAD_CONST: 2, ops.BINARY_SUBSCR: 1,
3120 ops.RETURN_VALUE: 1}
3121
3122 monkeypatch.setattr(optimize, "MAXUNICODE", 0xFFFF)
3123 source = """def f():
3124 return "\uE01F"[0]
3125 """
3126 counts = self.count_instructions(source)
3127 if 0: # xxx later?
3128 assert counts == {ops.LOAD_CONST: 1, ops.RETURN_VALUE: 1}
3129 monkeypatch.undo()
3130
3131 # getslice is not yet optimized.
3132 # Still, check a case which yields the empty string.
3133 source = """def f():
3134 return "abc"[:0]
3135 """
3136 counts = self.count_instructions(source)
3137 assert counts == {ops.LOAD_CONST: 3, ops.BUILD_SLICE: 1,
3138 ops.BINARY_SUBSCR: 1, ops.RETURN_VALUE: 1}
3139
3140 def test_remove_dead_code(self):
3141 source = """def f(x):
3142 return 5
3143 x += 1
3144 """
3145 counts = self.count_instructions(source)
3146 assert counts == {ops.LOAD_CONST:1, ops.RETURN_VALUE: 1}
3147
3148 def test_remove_dead_code_after_raise(self):
3149 source = """def f(x):
3150 raise ValueError
3151 x += 1
3152 """
3153 counts = self.count_instructions(source)
3154 assert counts == {ops.LOAD_GLOBAL:1, ops.RAISE_VARARGS: 1}
3155
3156
3157 def test_remove_dead_jump_after_return(self):
3158 source = """def f(x, y, z):
3159 if x:
3160 return y
3161 else:
3162 return z
3163 """
3164 counts = self.count_instructions(source)
3165 assert counts == {ops.LOAD_FAST: 3,
3166 ops.POP_JUMP_IF_FALSE: 1,
3167 ops.RETURN_VALUE: 2}
3168
3169 def test_remove_dead_yield(self):
3170 source = """def f(x):
3171 return
3172 yield 6
3173 """
3174 counts = self.count_instructions(source)
3175 assert counts == {ops.LOAD_CONST:1, ops.RETURN_VALUE: 1}
3176 #
3177 space = self.space
3178 w_generator = space.appexec([], """():
3179 d = {}
3180 exec('''def f(x):
3181 return
3182 yield 6
3183 ''', d)
3184 return d['f'](5)
3185 """)
3186 assert 'generator' in space.text_w(space.repr(w_generator))
3187
3188 def test_folding_of_list_constants(self):
3189 for source in (
3190 # in/not in constants with BUILD_LIST should be folded to a tuple:
3191 'a in [1,2,3]',
3192 'a not in ["a","b","c"]',
3193 'a in [None, 1, None]',
3194 'a not in [(1, 2), 3, 4]',
3195 ):
3196 source = 'def f(): %s' % source
3197 counts = self.count_instructions(source)
3198 assert ops.BUILD_LIST not in counts
3199 assert ops.LOAD_CONST in counts
3200
3201 def test_folding_of_set_constants(self):
3202 for source in (
3203 # in/not in constants with BUILD_SET should be folded to a frozenset:
3204 'a in {1,2,3}',
3205 'a not in {"a","b","c"}',
3206 'a in {None, 1, None}',
3207 'a not in {(1, 2), 3, 4}',
3208 'a in {1, 2, 3, 3, 2, 1}',
3209 ):
3210 source = 'def f(): %s' % source
3211 counts = self.count_instructions(source)
3212 assert ops.BUILD_SET not in counts
3213 assert ops.LOAD_CONST in counts
3214
3215 def test_dont_fold_huge_powers(self):
3216 for source, op in (
3217 ("2 ** 3000", ops.BINARY_POWER), # not constant-folded: too big
3218 ("(-2) ** 3000", ops.BINARY_POWER),
3219 ("5 << 1000", ops.BINARY_LSHIFT),
3220 ):
3221 source = 'def f(): %s' % source
3222 counts = self.count_instructions(source)
3223 assert op in counts
3224
3225 for source in (
3226 "2 ** 2000", # constant-folded
3227 "2 ** -3000",
3228 "1.001 ** 3000",
3229 "1 ** 3000.0",
3230 ):
3231 source = 'def f(): %s' % source
3232 counts = self.count_instructions(source)
3233 assert ops.BINARY_POWER not in counts
3234
3235 def test_call_function_var(self):
3236 source = """def f():
3237 call(*me)
3238 """
3239 code, blocks = generate_function_code(source, self.space)
3240 # there is a stack computation error
3241 assert blocks[0].instructions[3].arg == 0
3242
3243 def test_fstring(self):
3244 source = """def f(x):
3245 return f'ab{x}cd'
3246 """
3247 code, blocks = generate_function_code(source, self.space)
3248
3249 def test_empty_tuple_target(self):
3250 source = """def f():
3251 () = ()
3252 del ()
3253 [] = []
3254 del []
3255 """
3256 generate_function_code(source, self.space)
3257
3258 def test_make_constant_map(self):
3259 source = """def f():
3260 return {"A": 1, "b": 2}
3261 """
3262 counts = self.count_instructions(source)
3263 assert ops.BUILD_MAP not in counts
3264 source = """def f():
3265 return {"a": 1, "b": {}, 1: {"a": x}}
3266 """
3267 counts = self.count_instructions(source)
3268 assert counts[ops.BUILD_MAP] == 1 # the empty dict
3269 assert counts[ops.BUILD_CONST_KEY_MAP] == 2
3270
3271 def test_annotation_issue2884(self):
3272 source = """def f():
3273 a: list = [j for j in range(10)]
3274 """
3275 generate_function_code(source, self.space)
3276
3277 def test_constant_tuples(self):
3278 source = """def f():
3279 return ((u"a", 1), 2)
3280 """
3281 counts = self.count_instructions(source)
3282 assert ops.BUILD_TUPLE not in counts
3283 # also for bytes
3284 source = """def f():
3285 return ((b"a", 5), 5, 7, 8)
3286 """
3287 counts = self.count_instructions(source)
3288 assert ops.BUILD_TUPLE not in counts
3289
3290 def test_fold_defaults_tuple(self):
3291 source = """def f():
3292 def g(a, b=2, c=None, d='foo'):
3293 return None
3294 return g
3295 """
3296 counts = self.count_instructions(source)
3297 assert ops.BUILD_TUPLE not in counts
3298
3299 source = """def f():
3300 g = lambda a, b=2, c=None, d='foo': None
3301 return g
3302 """
3303 counts = self.count_instructions(source)
3304 assert ops.BUILD_TUPLE not in counts
3305
3306 source = """def f():
3307 def g(a, b=2, c=None, d=[]):
3308 return None
3309 return g
3310 """
3311 counts = self.count_instructions(source)
3312 assert counts[ops.BUILD_TUPLE] == 1
3313
3314 def test_constant_tuples_star(self):
3315 source = """def f(a, c):
3316 return (u"a", 1, *a, 3, 5, 3, *c)
3317 """
3318 counts = self.count_instructions(source)
3319 assert ops.BUILD_TUPLE not in counts
3320
3321 source = """def f(a, c, d):
3322 return (u"a", 1, *a, c, 1, *d, 1, 2, 3)
3323 """
3324 counts = self.count_instructions(source)
3325 assert ops.BUILD_TUPLE not in counts
3326
3327 def test_constant_tuples_star_bug(self):
3328 source = """def f(a, c):
3329 return (*a, *c)
3330 """
3331 # very annoying bug: this was turned into
3332 # (*(), *a, *(), *c) :-(
3333 counts = self.count_instructions(source)
3334 assert ops.LOAD_CONST not in counts
3335
3336 def test_constant_list_star(self):
3337 source = """def f(a, c):
3338 return [u"a", 1, *a, 3, 5, 3, *c]
3339 """
3340 counts = self.count_instructions(source)
3341 assert ops.BUILD_TUPLE not in counts
3342
3343 source = """def f(a, c, d):
3344 return [u"a", 1, *a, c, 1, *d, 1, 2, 3]
3345 """
3346 counts = self.count_instructions(source)
3347 assert ops.BUILD_TUPLE not in counts
3348
3349 def test_call_bytecodes(self):
3350 # check that the expected bytecodes are generated
3351 source = """def f(): x(a, b, c)"""
3352 counts = self.count_instructions(source)
3353 assert counts[ops.CALL_FUNCTION] == 1
3354
3355 source = """def f(): x(a, b, c, x=1, y=2)"""
3356 counts = self.count_instructions(source)
3357 assert counts[ops.CALL_FUNCTION_KW] == 1
3358
3359 source = """def f(): x(a, b, c, *(d, 2), x=1, y=2)"""
3360 counts = self.count_instructions(source)
3361 assert counts[ops.BUILD_TUPLE] == 1
3362 assert counts[ops.LIST_TO_TUPLE] == 1
3363 assert counts[ops.CALL_FUNCTION_EX] == 1
3364
3365 source = """def f(): x(a, b, c, **kwargs)"""
3366 counts = self.count_instructions(source)
3367 assert counts[ops.BUILD_TUPLE] == 1
3368 assert counts[ops.CALL_FUNCTION_EX] == 1
3369
3370 source = """def f(): x(**kwargs)"""
3371 counts = self.count_instructions(source)
3372 assert counts[ops.CALL_FUNCTION_EX] == 1
3373 assert ops.DICT_MERGE not in counts
3374 assert ops.BUILD_MAP not in counts
3375
3376 source = """def f(): x(a, b, c, **kwargs)"""
3377 counts = self.count_instructions(source)
3378 assert counts[ops.CALL_FUNCTION_EX] == 1
3379 assert ops.DICT_MERGE not in counts
3380 assert ops.BUILD_MAP not in counts
3381
3382 source = """def f(): x.m(a, b, c)"""
3383 counts = self.count_instructions(source)
3384 assert counts[ops.CALL_METHOD] == 1
3385
3386 source = """def f(): x.m(a, b, c, y=1)"""
3387 counts = self.count_instructions(source)
3388 assert counts[ops.CALL_METHOD_KW] == 1
3389
3390 def test_dont_emit_dead_blocks(self):
3391 source = """def f():
3392 if A:
3393 if B:
3394 if C:
3395 if D:
3396 return False
3397 else:
3398 return False
3399 elif E and F:
3400 return True
3401 """
3402 counts = self.count_instructions(source)
3403 assert counts[ops.RETURN_VALUE] == 7
3404
3405 def test_assert_looks_at_constants(self):
3406 source = """def assert0():
3407 assert 0,\\
3408 "abc"
3409 """
3410 counts = self.count_instructions(source)
3411 assert counts.get(ops.POP_JUMP_IF_TRUE, 0) == 0
3412
3413 def test_match_optimized(self):
3414 source = """def f():
3415 match x:
3416 case 1 if (
3417
3418 True):
3419 pass
3420 case _:
3421 pass
3422 print()
3423 """
3424 counts = self.count_instructions(source)
3425 assert counts.get(ops.JUMP_FORWARD, 0) == 1
3426
3427 def test_jump_if_false_or_pop_to_same(self):
3428 source = """def f(a, b, c):
3429 return ((a and b)
3430 and c)
3431 """
3432 counts = self.count_instructions(source)
3433 assert self._blocks[0].instructions[1].jump.instructions[0].opcode != ops.JUMP_IF_FALSE_OR_POP
3434 assert self._blocks[0].instructions[1].jump is self._blocks[-1]
3435
3436
3437 def test_jump_if_true_or_pop_to_same(self):
3438 source = """def f(a, b, c):
3439 return ((a or b)
3440 or c)
3441 """
3442 counts = self.count_instructions(source)
3443 assert self._blocks[0].instructions[1].jump.instructions[0].opcode != ops.JUMP_IF_TRUE_OR_POP
3444 assert self._blocks[0].instructions[1].jump is self._blocks[-1]
3445
3446 def test_listcomp_assignment_hack(self):
3447 self.count_instructions("""def listcomp_assignment_hack():
3448 return [y for x in a for y in [f(x)]]
3449 """)
3450 assert self._code.consts_w[1].co_code.count(chr(ops.FOR_ITER)) == 1
3451 self.count_instructions("""def listcomp_assignment_hack2():
3452 return [y for x in [1, 2, 3] for y in []]
3453 """)
3454 # it's really pointless to optimize this
3455 assert self._code.consts_w[1].co_code.count(chr(ops.FOR_ITER)) == 2
3456
3457
3458 class TestHugeStackDepths:
3459 def run_and_check_stacksize(self, source):
3460 space = self.space
3461 code = compile_with_astcompiler("a = " + source, 'exec', space)
3462 assert code.co_stacksize < 100
3463 w_dict = space.newdict()
3464 code.exec_code(space, w_dict, w_dict)
3465 return space.getitem(w_dict, space.newtext("a"))
3466
3467 def test_tuple(self):
3468 source = "(" + ",".join([str(i) for i in range(200)]) + ")\n"
3469 w_res = self.run_and_check_stacksize(source)
3470 assert self.space.unwrap(w_res) == tuple(range(200))
3471
3472 def test_list(self):
3473 source = "[" + ",".join([str(i) for i in range(200)]) + "]\n"
3474 w_res = self.run_and_check_stacksize(source)
3475 assert self.space.unwrap(w_res) == range(200)
3476
3477 def test_list_unpacking(self):
3478 space = self.space
3479 source = "[" + ",".join(['b%d' % i for i in range(200)]) + "] = a\n"
3480 code = compile_with_astcompiler(source, 'exec', space)
3481 assert code.co_stacksize == 200 # xxx remains big
3482 w_dict = space.newdict()
3483 space.setitem(w_dict, space.newtext("a"), space.wrap(range(42, 242)))
3484 code.exec_code(space, w_dict, w_dict)
3485 assert space.unwrap(space.getitem(w_dict, space.newtext("b0"))) == 42
3486 assert space.unwrap(space.getitem(w_dict, space.newtext("b199"))) == 241
3487
3488 def test_set(self):
3489 source = "{" + ",".join([str(i) for i in range(200)]) + "}\n"
3490 w_res = self.run_and_check_stacksize(source)
3491 space = self.space
3492 assert [space.int_w(w_x)
3493 for w_x in space.unpackiterable(w_res)] == range(200)
3494
3495 def test_dict(self):
3496 source = "{" + ",".join(['%s: None' % (i, ) for i in range(200)]) + "}\n"
3497 w_res = self.run_and_check_stacksize(source)
3498 assert self.space.unwrap(w_res) == dict.fromkeys(range(200))
3499
3500 def test_dict_bug(self):
3501 source = s = "1\ndef f(): l = list(range(400)); return {%s}\na = f()" % (
3502 ", ".join(["l.pop(): l.pop()"] * 200))
3503 w_res = self.run_and_check_stacksize(source)
3504 l = list(range(400))
3505 d = {}
3506 while l:
3507 key = l.pop()
3508 value = l.pop()
3509 d[key] = value
3510 assert self.space.unwrap(w_res) == d
3511
3512 def test_callargs(self):
3513 source = "(lambda *args: args)(" + ", ".join([str(i) for i in range(200)]) + ")\n"
3514 w_res = self.run_and_check_stacksize(source)
3515 assert self.space.unwrap(w_res) == tuple(range(200))
3516
3517 source = "(lambda **args: args)(" + ", ".join(["s%s=None" % i for i in range(200)]) + ")\n"
3518 w_res = self.run_and_check_stacksize(source)
3519 assert self.space.unwrap(w_res) == dict.fromkeys(["s" + str(i) for i in range(200)])
3520
3521 def test_call_method_args(self):
3522 args = "1, " * 217
3523 source = '(type("A", (), {"f": lambda self, *args: len(args)}))().f(%s)' % args
3524 w_res = self.run_and_check_stacksize(source)
3525 assert self.space.int_w(w_res) == 217