blob: 94e454663573b35ac185abcde76e6cfc72522c18 [file] [log] [blame]
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +03001import copy
Fred Drake79ca79d2000-08-21 22:30:53 +00002import parser
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +03003import pickle
Fred Drake58422e52001-06-04 03:56:24 +00004import unittest
Mark Dickinson211c6252009-02-01 10:28:51 +00005import operator
Jesus Ceae9c53182012-08-03 14:28:37 +02006import struct
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Berker Peksagce643912015-05-06 06:33:17 +03008from test.support.script_helper import assert_python_failure
Fred Drake79ca79d2000-08-21 22:30:53 +00009
10#
11# First, we test that we can generate trees from valid source fragments,
12# and that these valid trees are indeed allowed by the tree-loading side
13# of the parser module.
14#
15
Fred Drake58422e52001-06-04 03:56:24 +000016class RoundtripLegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000017
Fred Drake58422e52001-06-04 03:56:24 +000018 def roundtrip(self, f, s):
19 st1 = f(s)
20 t = st1.totuple()
21 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +000022 st2 = parser.sequence2st(t)
Guido van Rossumb940e112007-01-10 16:19:56 +000023 except parser.ParserError as why:
Anthony Baxterc2a5a632004-08-02 06:10:11 +000024 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000025
Ezio Melottib3aedd42010-11-20 19:04:17 +000026 self.assertEqual(t, st2.totuple(),
27 "could not re-generate syntax tree")
Fred Drake28f739a2000-08-25 22:42:40 +000028
Fred Drake58422e52001-06-04 03:56:24 +000029 def check_expr(self, s):
30 self.roundtrip(parser.expr, s)
Fred Drake28f739a2000-08-25 22:42:40 +000031
Benjamin Petersonf216c942008-10-31 02:28:05 +000032 def test_flags_passed(self):
Mike53f7a7c2017-12-14 14:04:53 +030033 # The unicode literals flags has to be passed from the parser to AST
Benjamin Petersonf216c942008-10-31 02:28:05 +000034 # generation.
35 suite = parser.suite("from __future__ import unicode_literals; x = ''")
36 code = suite.compile()
37 scope = {}
38 exec(code, {}, scope)
Ezio Melottie9615932010-01-24 19:26:24 +000039 self.assertIsInstance(scope["x"], str)
Benjamin Petersonf216c942008-10-31 02:28:05 +000040
Fred Drake58422e52001-06-04 03:56:24 +000041 def check_suite(self, s):
42 self.roundtrip(parser.suite, s)
Fred Drake28f739a2000-08-25 22:42:40 +000043
Fred Drakecf580c72001-07-17 03:01:29 +000044 def test_yield_statement(self):
Tim Peters496563a2002-04-01 00:28:59 +000045 self.check_suite("def f(): yield 1")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000046 self.check_suite("def f(): yield")
47 self.check_suite("def f(): x += yield")
48 self.check_suite("def f(): x = yield 1")
49 self.check_suite("def f(): x = y = yield 1")
50 self.check_suite("def f(): x = yield")
51 self.check_suite("def f(): x = y = yield")
52 self.check_suite("def f(): 1 + (yield)*2")
53 self.check_suite("def f(): (yield 1)*2")
Tim Peters496563a2002-04-01 00:28:59 +000054 self.check_suite("def f(): return; yield 1")
55 self.check_suite("def f(): yield 1; return")
Nick Coghlan1f7ce622012-01-13 21:43:40 +100056 self.check_suite("def f(): yield from 1")
57 self.check_suite("def f(): x = yield from 1")
58 self.check_suite("def f(): f((yield from 1))")
59 self.check_suite("def f(): yield 1; return 1")
Tim Peters496563a2002-04-01 00:28:59 +000060 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000061 " for x in range(30):\n"
62 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000063 self.check_suite("def f():\n"
64 " if (yield):\n"
65 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000066
Yury Selivanov75445082015-05-11 22:57:16 -040067 def test_await_statement(self):
68 self.check_suite("async def f():\n await smth()")
69 self.check_suite("async def f():\n foo = await smth()")
70 self.check_suite("async def f():\n foo, bar = await smth()")
71 self.check_suite("async def f():\n (await smth())")
72 self.check_suite("async def f():\n foo((await smth()))")
73 self.check_suite("async def f():\n await foo(); return 42")
74
75 def test_async_with_statement(self):
76 self.check_suite("async def f():\n async with 1: pass")
77 self.check_suite("async def f():\n async with a as b, c as d: pass")
78
79 def test_async_for_statement(self):
80 self.check_suite("async def f():\n async for i in (): pass")
81 self.check_suite("async def f():\n async for i, b in (): pass")
82
Mark Dickinson407b3bd2012-04-29 22:18:31 +010083 def test_nonlocal_statement(self):
84 self.check_suite("def f():\n"
85 " x = 0\n"
86 " def g():\n"
87 " nonlocal x\n")
88 self.check_suite("def f():\n"
89 " x = y = 0\n"
90 " def g():\n"
91 " nonlocal x, y\n")
92
Fred Drake58422e52001-06-04 03:56:24 +000093 def test_expressions(self):
94 self.check_expr("foo(1)")
95 self.check_expr("[1, 2, 3]")
96 self.check_expr("[x**3 for x in range(20)]")
97 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
99 self.check_expr("list(x**3 for x in range(20))")
100 self.check_expr("list(x**3 for x in range(20) if x % 3)")
101 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +0000102 self.check_expr("foo(*args)")
103 self.check_expr("foo(*args, **kw)")
104 self.check_expr("foo(**kw)")
105 self.check_expr("foo(key=value)")
106 self.check_expr("foo(key=value, *args)")
107 self.check_expr("foo(key=value, *args, **kw)")
108 self.check_expr("foo(key=value, **kw)")
109 self.check_expr("foo(a, b, c, *args)")
110 self.check_expr("foo(a, b, c, *args, **kw)")
111 self.check_expr("foo(a, b, c, **kw)")
Benjamin Peterson3938a902008-08-20 02:33:00 +0000112 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +0000113 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000114 self.check_expr("foo - bar")
115 self.check_expr("foo * bar")
116 self.check_expr("foo / bar")
117 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +0000118 self.check_expr("lambda: 0")
119 self.check_expr("lambda x: 0")
120 self.check_expr("lambda *y: 0")
121 self.check_expr("lambda *y, **z: 0")
122 self.check_expr("lambda **z: 0")
123 self.check_expr("lambda x, y: 0")
124 self.check_expr("lambda foo=bar: 0")
125 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
126 self.check_expr("lambda foo=bar, **z: 0")
127 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
128 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
129 self.check_expr("lambda x, *y, **z: 0")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000130 self.check_expr("(x for x in range(10))")
131 self.check_expr("foo(x for x in range(10))")
Mark Dickinsonda029fb2012-05-07 17:24:04 +0100132 self.check_expr("...")
133 self.check_expr("a[...]")
Fred Drake79ca79d2000-08-21 22:30:53 +0000134
Fred Drake58422e52001-06-04 03:56:24 +0000135 def test_simple_expression(self):
136 # expr_stmt
137 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000138
Fred Drake58422e52001-06-04 03:56:24 +0000139 def test_simple_assignments(self):
140 self.check_suite("a = b")
141 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000142
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700143 def test_var_annot(self):
144 self.check_suite("x: int = 5")
145 self.check_suite("y: List[T] = []; z: [list] = fun()")
146 self.check_suite("x: tuple = (1, 2)")
147 self.check_suite("d[f()]: int = 42")
148 self.check_suite("f(d[x]): str = 'abc'")
149 self.check_suite("x.y.z.w: complex = 42j")
150 self.check_suite("x: int")
151 self.check_suite("def f():\n"
152 " x: str\n"
153 " y: int = 5\n")
154 self.check_suite("class C:\n"
155 " x: str\n"
156 " y: int = 5\n")
157 self.check_suite("class C:\n"
158 " def __init__(self, x: int) -> None:\n"
159 " self.x: int = x\n")
160 # double check for nonsense
161 with self.assertRaises(SyntaxError):
162 exec("2+2: int", {}, {})
163 with self.assertRaises(SyntaxError):
164 exec("[]: int = 5", {}, {})
165 with self.assertRaises(SyntaxError):
166 exec("x, *y, z: int = range(5)", {}, {})
167 with self.assertRaises(SyntaxError):
168 exec("t: tuple = 1, 2", {}, {})
169 with self.assertRaises(SyntaxError):
170 exec("u = v: int", {}, {})
171 with self.assertRaises(SyntaxError):
172 exec("False: int", {}, {})
173 with self.assertRaises(SyntaxError):
174 exec("x.False: int", {}, {})
175 with self.assertRaises(SyntaxError):
176 exec("x.y,: int", {}, {})
177 with self.assertRaises(SyntaxError):
178 exec("[0]: int", {}, {})
179 with self.assertRaises(SyntaxError):
180 exec("f(): int", {}, {})
181
Fred Drake58422e52001-06-04 03:56:24 +0000182 def test_simple_augmented_assignments(self):
183 self.check_suite("a += b")
184 self.check_suite("a -= b")
185 self.check_suite("a *= b")
186 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000187 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000188 self.check_suite("a %= b")
189 self.check_suite("a &= b")
190 self.check_suite("a |= b")
191 self.check_suite("a ^= b")
192 self.check_suite("a <<= b")
193 self.check_suite("a >>= b")
194 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000195
Fred Drake58422e52001-06-04 03:56:24 +0000196 def test_function_defs(self):
197 self.check_suite("def f(): pass")
198 self.check_suite("def f(*args): pass")
199 self.check_suite("def f(*args, **kw): pass")
200 self.check_suite("def f(**kw): pass")
201 self.check_suite("def f(foo=bar): pass")
202 self.check_suite("def f(foo=bar, *args): pass")
203 self.check_suite("def f(foo=bar, *args, **kw): pass")
204 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000205
Fred Drake58422e52001-06-04 03:56:24 +0000206 self.check_suite("def f(a, b): pass")
207 self.check_suite("def f(a, b, *args): pass")
208 self.check_suite("def f(a, b, *args, **kw): pass")
209 self.check_suite("def f(a, b, **kw): pass")
210 self.check_suite("def f(a, b, foo=bar): pass")
211 self.check_suite("def f(a, b, foo=bar, *args): pass")
212 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
213 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000214
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000215 self.check_suite("@staticmethod\n"
216 "def f(): pass")
217 self.check_suite("@staticmethod\n"
218 "@funcattrs(x, y)\n"
219 "def f(): pass")
220 self.check_suite("@funcattrs()\n"
221 "def f(): pass")
222
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100223 # keyword-only arguments
224 self.check_suite("def f(*, a): pass")
225 self.check_suite("def f(*, a = 5): pass")
226 self.check_suite("def f(*, a = 5, b): pass")
227 self.check_suite("def f(*, a, b = 5): pass")
228 self.check_suite("def f(*, a, b = 5, **kwds): pass")
229 self.check_suite("def f(*args, a): pass")
230 self.check_suite("def f(*args, a = 5): pass")
231 self.check_suite("def f(*args, a = 5, b): pass")
232 self.check_suite("def f(*args, a, b = 5): pass")
233 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
234
235 # function annotations
236 self.check_suite("def f(a: int): pass")
237 self.check_suite("def f(a: int = 5): pass")
238 self.check_suite("def f(*args: list): pass")
239 self.check_suite("def f(**kwds: dict): pass")
240 self.check_suite("def f(*, a: int): pass")
241 self.check_suite("def f(*, a: int = 5): pass")
242 self.check_suite("def f() -> int: pass")
243
Brett Cannonf4189912005-04-09 02:30:16 +0000244 def test_class_defs(self):
245 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000246 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000247 self.check_suite("@class_decorator\n"
248 "class foo():pass")
249 self.check_suite("@class_decorator(arg)\n"
250 "class foo():pass")
251 self.check_suite("@decorator1\n"
252 "@decorator2\n"
253 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000254
Fred Drake58422e52001-06-04 03:56:24 +0000255 def test_import_from_statement(self):
256 self.check_suite("from sys.path import *")
257 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000258 self.check_suite("from sys.path import (dirname)")
259 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000260 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000261 self.check_suite("from sys.path import (dirname as my_dirname)")
262 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000263 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000264 self.check_suite("from sys.path import (dirname, basename)")
265 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000266 self.check_suite(
267 "from sys.path import dirname as my_dirname, basename")
268 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000269 "from sys.path import (dirname as my_dirname, basename)")
270 self.check_suite(
271 "from sys.path import (dirname as my_dirname, basename,)")
272 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000273 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000274 self.check_suite(
275 "from sys.path import (dirname, basename as my_basename)")
276 self.check_suite(
277 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000278 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000279
Fred Drake58422e52001-06-04 03:56:24 +0000280 def test_basic_import_statement(self):
281 self.check_suite("import sys")
282 self.check_suite("import sys as system")
283 self.check_suite("import sys, math")
284 self.check_suite("import sys as system, math")
285 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000286
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000287 def test_relative_imports(self):
288 self.check_suite("from . import name")
289 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000290 # check all the way up to '....', since '...' is tokenized
291 # differently from '.' (it's an ellipsis token).
292 self.check_suite("from ... import name")
293 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000294 self.check_suite("from .pkg import name")
295 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000296 self.check_suite("from ...pkg import name")
297 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000298
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000299 def test_pep263(self):
300 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
301 "pass\n")
302
303 def test_assert(self):
304 self.check_suite("assert alo < ahi and blo < bhi\n")
305
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000306 def test_with(self):
307 self.check_suite("with open('x'): pass\n")
308 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000309 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000310
Georg Brandleee31162008-12-07 15:15:22 +0000311 def test_try_stmt(self):
312 self.check_suite("try: pass\nexcept: pass\n")
313 self.check_suite("try: pass\nfinally: pass\n")
314 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
315 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
316 "finally: pass\n")
317 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
318 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
319 "finally: pass\n")
320
Miss Islington (bot)00eb97b2019-03-21 16:56:20 -0700321 def test_if_stmt(self):
322 self.check_suite("if True:\n pass\nelse:\n pass\n")
323 self.check_suite("if True:\n pass\nelif True:\n pass\nelse:\n pass\n")
324
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325 def test_position(self):
326 # An absolutely minimal test of position information. Better
327 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000328 code = "def f(x):\n return x + 1"
Miss Islington (bot)b27c71c2018-04-18 22:10:36 -0700329 st = parser.suite(code)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000330
331 def walk(tree):
332 node_type = tree[0]
333 next = tree[1]
Miss Islington (bot)b27c71c2018-04-18 22:10:36 -0700334 if isinstance(next, (tuple, list)):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 for elt in tree[1:]:
336 for x in walk(elt):
337 yield x
338 else:
339 yield tree
340
Miss Islington (bot)b27c71c2018-04-18 22:10:36 -0700341 expected = [
Thomas Wouters89f507f2006-12-13 04:49:30 +0000342 (1, 'def', 1, 0),
343 (1, 'f', 1, 4),
344 (7, '(', 1, 5),
345 (1, 'x', 1, 6),
346 (8, ')', 1, 7),
347 (11, ':', 1, 8),
348 (4, '', 1, 9),
349 (5, '', 2, -1),
350 (1, 'return', 2, 4),
351 (1, 'x', 2, 11),
352 (14, '+', 2, 13),
353 (2, '1', 2, 15),
354 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000355 (6, '', 2, -1),
356 (4, '', 2, -1),
Miss Islington (bot)b27c71c2018-04-18 22:10:36 -0700357 (0, '', 2, -1),
358 ]
359
360 self.assertEqual(list(walk(st.totuple(line_info=True, col_info=True))),
361 expected)
362 self.assertEqual(list(walk(st.totuple())),
363 [(t, n) for t, n, l, c in expected])
364 self.assertEqual(list(walk(st.totuple(line_info=True))),
365 [(t, n, l) for t, n, l, c in expected])
366 self.assertEqual(list(walk(st.totuple(col_info=True))),
367 [(t, n, c) for t, n, l, c in expected])
368 self.assertEqual(list(walk(st.tolist(line_info=True, col_info=True))),
369 [list(x) for x in expected])
370 self.assertEqual(list(walk(parser.st2tuple(st, line_info=True,
371 col_info=True))),
372 expected)
373 self.assertEqual(list(walk(parser.st2list(st, line_info=True,
374 col_info=True))),
375 [list(x) for x in expected])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000376
Benjamin Peterson4905e802009-09-27 02:43:28 +0000377 def test_extended_unpacking(self):
378 self.check_suite("*a = y")
379 self.check_suite("x, *b, = m")
380 self.check_suite("[*a, *b] = y")
381 self.check_suite("for [*x, b] in x: pass")
382
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100383 def test_raise_statement(self):
384 self.check_suite("raise\n")
385 self.check_suite("raise e\n")
386 self.check_suite("try:\n"
387 " suite\n"
388 "except Exception as e:\n"
389 " raise ValueError from e\n")
390
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400391 def test_list_displays(self):
392 self.check_expr('[]')
393 self.check_expr('[*{2}, 3, *[4]]')
394
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100395 def test_set_displays(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400396 self.check_expr('{*{2}, 3, *[4]}')
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100397 self.check_expr('{2}')
398 self.check_expr('{2,}')
399 self.check_expr('{2, 3}')
400 self.check_expr('{2, 3,}')
401
402 def test_dict_displays(self):
403 self.check_expr('{}')
404 self.check_expr('{a:b}')
405 self.check_expr('{a:b,}')
406 self.check_expr('{a:b, c:d}')
407 self.check_expr('{a:b, c:d,}')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400408 self.check_expr('{**{}}')
409 self.check_expr('{**{}, 3:4, **{5:6, 7:8}}')
410
411 def test_argument_unpacking(self):
Yury Selivanov50a26142015-08-05 17:59:45 -0400412 self.check_expr("f(*a, **b)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400413 self.check_expr('f(a, *b, *c, *d)')
414 self.check_expr('f(**a, **b)')
415 self.check_expr('f(2, *a, *b, **b, **c, **d)')
Yury Selivanov50a26142015-08-05 17:59:45 -0400416 self.check_expr("f(*b, *() or () and (), **{} and {}, **() or {})")
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100417
418 def test_set_comprehensions(self):
419 self.check_expr('{x for x in seq}')
420 self.check_expr('{f(x) for x in seq}')
421 self.check_expr('{f(x) for x in seq if condition(x)}')
422
423 def test_dict_comprehensions(self):
424 self.check_expr('{x:x for x in seq}')
425 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
426 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
427
Thomas Wouters89f507f2006-12-13 04:49:30 +0000428
Fred Drake79ca79d2000-08-21 22:30:53 +0000429#
430# Second, we take *invalid* trees and make sure we get ParserError
431# rejections for them.
432#
433
Fred Drake58422e52001-06-04 03:56:24 +0000434class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000435
Fred Drake58422e52001-06-04 03:56:24 +0000436 def check_bad_tree(self, tree, label):
437 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000438 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000439 except parser.ParserError:
440 pass
441 else:
442 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000443
Fred Drake58422e52001-06-04 03:56:24 +0000444 def test_junk(self):
445 # not even remotely valid:
446 self.check_bad_tree((1, 2, 3), "<junk>")
447
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300448 def test_illegal_terminal(self):
449 tree = \
450 (257,
451 (269,
452 (270,
453 (271,
454 (277,
455 (1,))),
456 (4, ''))),
457 (4, ''),
458 (0, ''))
459 self.check_bad_tree(tree, "too small items in terminal node")
460 tree = \
461 (257,
462 (269,
463 (270,
464 (271,
465 (277,
466 (1, b'pass'))),
467 (4, ''))),
468 (4, ''),
469 (0, ''))
470 self.check_bad_tree(tree, "non-string second item in terminal node")
471 tree = \
472 (257,
473 (269,
474 (270,
475 (271,
476 (277,
477 (1, 'pass', '0', 0))),
478 (4, ''))),
479 (4, ''),
480 (0, ''))
481 self.check_bad_tree(tree, "non-integer third item in terminal node")
482 tree = \
483 (257,
484 (269,
485 (270,
486 (271,
487 (277,
488 (1, 'pass', 0, 0))),
489 (4, ''))),
490 (4, ''),
491 (0, ''))
492 self.check_bad_tree(tree, "too many items in terminal node")
493
Fred Drakecf580c72001-07-17 03:01:29 +0000494 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000495 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000496 tree = \
497 (257,
498 (264,
499 (285,
500 (259,
501 (1, 'def'),
502 (1, 'f'),
503 (260, (7, '('), (8, ')')),
504 (11, ':'),
505 (291,
506 (4, ''),
507 (5, ''),
508 (264,
509 (265,
510 (266,
511 (272,
512 (275,
513 (1, 'return'),
514 (313,
515 (292,
516 (293,
517 (294,
518 (295,
519 (297,
520 (298,
521 (299,
522 (300,
523 (301,
524 (302, (303, (304, (305, (2, '1')))))))))))))))))),
525 (264,
526 (265,
527 (266,
528 (272,
529 (276,
530 (1, 'yield'),
531 (313,
532 (292,
533 (293,
534 (294,
535 (295,
536 (297,
537 (298,
538 (299,
539 (300,
540 (301,
541 (302,
542 (303, (304, (305, (2, '1')))))))))))))))))),
543 (4, ''))),
544 (6, ''))))),
545 (4, ''),
546 (0, ''))))
547 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
548
549 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000550 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000551 tree = \
552 (257,
553 (264,
554 (265,
555 (266,
556 (278,
557 (1, 'from'),
558 (281, (1, '__future__')),
559 (1, 'import'),
560 (279, (1, 'generators')))),
561 (4, ''))),
562 (264,
563 (285,
564 (259,
565 (1, 'def'),
566 (1, 'f'),
567 (260, (7, '('), (8, ')')),
568 (11, ':'),
569 (291,
570 (4, ''),
571 (5, ''),
572 (264,
573 (265,
574 (266,
575 (272,
576 (275,
577 (1, 'return'),
578 (313,
579 (292,
580 (293,
581 (294,
582 (295,
583 (297,
584 (298,
585 (299,
586 (300,
587 (301,
588 (302, (303, (304, (305, (2, '1')))))))))))))))))),
589 (264,
590 (265,
591 (266,
592 (272,
593 (276,
594 (1, 'yield'),
595 (313,
596 (292,
597 (293,
598 (294,
599 (295,
600 (297,
601 (298,
602 (299,
603 (300,
604 (301,
605 (302,
606 (303, (304, (305, (2, '1')))))))))))))))))),
607 (4, ''))),
608 (6, ''))))),
609 (4, ''),
610 (0, ''))))
611 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
612
Fred Drake58422e52001-06-04 03:56:24 +0000613 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000614 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000615 tree = \
616 (258,
617 (311,
618 (290,
619 (291,
620 (292,
621 (293,
622 (295,
623 (296,
624 (297,
625 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
626 (12, ','),
627 (12, ','),
628 (290,
629 (291,
630 (292,
631 (293,
632 (295,
633 (296,
634 (297,
635 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
636 (4, ''),
637 (0, ''))
638 self.check_bad_tree(tree, "a,,c")
639
640 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000641 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000642 tree = \
643 (257,
644 (264,
645 (265,
646 (266,
647 (267,
648 (312,
649 (291,
650 (292,
651 (293,
652 (294,
653 (296,
654 (297,
655 (298,
656 (299,
657 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
658 (268, (37, '$=')),
659 (312,
660 (291,
661 (292,
662 (293,
663 (294,
664 (296,
665 (297,
666 (298,
667 (299,
668 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
669 (4, ''))),
670 (0, ''))
671 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000672
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000673 def test_malformed_global(self):
674 #doesn't have global keyword in ast
675 tree = (257,
676 (264,
677 (265,
678 (266,
679 (282, (1, 'foo'))), (4, ''))),
680 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000681 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000682 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000683
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000684 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000685 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000686 tree = \
687 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000688 (268,
689 (269,
690 (270,
691 (282,
692 (284, (1, 'from'), (1, 'import'),
693 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000694 (4, ''))),
695 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000696 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000697
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300698 def test_illegal_encoding(self):
699 # Illegal encoding declaration
700 tree = \
Jelle Zijlstraac317702017-10-05 20:24:46 -0700701 (340,
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300702 (257, (0, '')))
703 self.check_bad_tree(tree, "missed encoding")
704 tree = \
Jelle Zijlstraac317702017-10-05 20:24:46 -0700705 (340,
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300706 (257, (0, '')),
707 b'iso-8859-1')
708 self.check_bad_tree(tree, "non-string encoding")
709 tree = \
Jelle Zijlstraac317702017-10-05 20:24:46 -0700710 (340,
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300711 (257, (0, '')),
712 '\udcff')
713 with self.assertRaises(UnicodeEncodeError):
714 parser.sequence2st(tree)
715
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716
717class CompileTestCase(unittest.TestCase):
718
719 # These tests are very minimal. :-(
720
721 def test_compile_expr(self):
722 st = parser.expr('2 + 3')
723 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000724 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000725
726 def test_compile_suite(self):
727 st = parser.suite('x = 2; y = x + 3')
728 code = parser.compilest(st)
729 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000730 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000731 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732
733 def test_compile_error(self):
734 st = parser.suite('1 = 3 + 4')
735 self.assertRaises(SyntaxError, parser.compilest, st)
736
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000737 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000738 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000739 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000740 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000741 self.assertRaises(SyntaxError, parser.compilest, st)
742
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000743 def test_issue_9011(self):
744 # Issue 9011: compilation of an unary minus expression changed
745 # the meaning of the ST, so that a second compilation produced
746 # incorrect results.
747 st = parser.expr('-3')
748 code1 = parser.compilest(st)
749 self.assertEqual(eval(code1), -3)
750 code2 = parser.compilest(st)
751 self.assertEqual(eval(code2), -3)
752
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300753 def test_compile_filename(self):
754 st = parser.expr('a + 5')
755 code = parser.compilest(st)
756 self.assertEqual(code.co_filename, '<syntax-tree>')
757 code = st.compile()
758 self.assertEqual(code.co_filename, '<syntax-tree>')
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300759 for filename in 'file.py', b'file.py':
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300760 code = parser.compilest(st, filename)
761 self.assertEqual(code.co_filename, 'file.py')
762 code = st.compile(filename)
763 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300764 for filename in bytearray(b'file.py'), memoryview(b'file.py'):
765 with self.assertWarns(DeprecationWarning):
766 code = parser.compilest(st, filename)
767 self.assertEqual(code.co_filename, 'file.py')
768 with self.assertWarns(DeprecationWarning):
769 code = st.compile(filename)
770 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300771 self.assertRaises(TypeError, parser.compilest, st, list(b'file.py'))
772 self.assertRaises(TypeError, st.compile, list(b'file.py'))
773
774
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000775class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000776 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000777 see http://bugs.python.org/issue1881 for a discussion
778 """
779 def _nested_expression(self, level):
780 return "["*level+"]"*level
781
782 def test_deeply_nested_list(self):
783 # XXX used to be 99 levels in 2.x
784 e = self._nested_expression(93)
785 st = parser.expr(e)
786 st.compile()
787
788 def test_trigger_memory_error(self):
789 e = self._nested_expression(100)
Ezio Melotti39191842013-03-09 22:17:33 +0200790 rc, out, err = assert_python_failure('-c', e)
791 # parsing the expression will result in an error message
792 # followed by a MemoryError (see #11963)
Ezio Melottie7c32992013-03-10 03:25:45 +0200793 self.assertIn(b's_push: parser stack overflow', err)
794 self.assertIn(b'MemoryError', err)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000795
Mark Dickinson211c6252009-02-01 10:28:51 +0000796class STObjectTestCase(unittest.TestCase):
797 """Test operations on ST objects themselves"""
798
799 def test_comparisons(self):
800 # ST objects should support order and equality comparisons
801 st1 = parser.expr('2 + 3')
802 st2 = parser.suite('x = 2; y = x + 3')
803 st3 = parser.expr('list(x**3 for x in range(20))')
804 st1_copy = parser.expr('2 + 3')
805 st2_copy = parser.suite('x = 2; y = x + 3')
806 st3_copy = parser.expr('list(x**3 for x in range(20))')
807
808 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000809 self.assertEqual(st1 == st1, True)
810 self.assertEqual(st2 == st2, True)
811 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000812 # slow path equality
813 self.assertEqual(st1, st1_copy)
814 self.assertEqual(st2, st2_copy)
815 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000816 self.assertEqual(st1 == st2, False)
817 self.assertEqual(st1 == st3, False)
818 self.assertEqual(st2 == st3, False)
819 self.assertEqual(st1 != st1, False)
820 self.assertEqual(st2 != st2, False)
821 self.assertEqual(st3 != st3, False)
822 self.assertEqual(st1 != st1_copy, False)
823 self.assertEqual(st2 != st2_copy, False)
824 self.assertEqual(st3 != st3_copy, False)
825 self.assertEqual(st2 != st1, True)
826 self.assertEqual(st1 != st3, True)
827 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000828 # we don't particularly care what the ordering is; just that
829 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000830 self.assertEqual(st1 < st2, not (st2 <= st1))
831 self.assertEqual(st1 < st3, not (st3 <= st1))
832 self.assertEqual(st2 < st3, not (st3 <= st2))
833 self.assertEqual(st1 < st2, st2 > st1)
834 self.assertEqual(st1 < st3, st3 > st1)
835 self.assertEqual(st2 < st3, st3 > st2)
836 self.assertEqual(st1 <= st2, st2 >= st1)
837 self.assertEqual(st3 <= st1, st1 >= st3)
838 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000839 # transitivity
840 bottom = min(st1, st2, st3)
841 top = max(st1, st2, st3)
842 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000843 self.assertTrue(bottom < mid)
844 self.assertTrue(bottom < top)
845 self.assertTrue(mid < top)
846 self.assertTrue(bottom <= mid)
847 self.assertTrue(bottom <= top)
848 self.assertTrue(mid <= top)
849 self.assertTrue(bottom <= bottom)
850 self.assertTrue(mid <= mid)
851 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000852 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000853 self.assertEqual(st1 == 1588.602459, False)
854 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000855 self.assertRaises(TypeError, operator.ge, st3, None)
856 self.assertRaises(TypeError, operator.le, False, st1)
857 self.assertRaises(TypeError, operator.lt, st1, 1815)
858 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
859
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300860 def test_copy_pickle(self):
861 sts = [
862 parser.expr('2 + 3'),
863 parser.suite('x = 2; y = x + 3'),
864 parser.expr('list(x**3 for x in range(20))')
865 ]
866 for st in sts:
867 st_copy = copy.copy(st)
868 self.assertEqual(st_copy.totuple(), st.totuple())
869 st_copy = copy.deepcopy(st)
870 self.assertEqual(st_copy.totuple(), st.totuple())
871 for proto in range(pickle.HIGHEST_PROTOCOL+1):
872 st_copy = pickle.loads(pickle.dumps(st, proto))
873 self.assertEqual(st_copy.totuple(), st.totuple())
874
Jesus Ceae9c53182012-08-03 14:28:37 +0200875 check_sizeof = support.check_sizeof
876
877 @support.cpython_only
878 def test_sizeof(self):
879 def XXXROUNDUP(n):
880 if n <= 1:
881 return n
882 if n <= 128:
883 return (n + 3) & ~3
884 return 1 << (n - 1).bit_length()
885
886 basesize = support.calcobjsize('Pii')
887 nodesize = struct.calcsize('hP3iP0h')
888 def sizeofchildren(node):
889 if node is None:
890 return 0
891 res = 0
892 hasstr = len(node) > 1 and isinstance(node[-1], str)
893 if hasstr:
894 res += len(node[-1]) + 1
895 children = node[1:-1] if hasstr else node[1:]
896 if children:
897 res += XXXROUNDUP(len(children)) * nodesize
Jesus Ceae9c53182012-08-03 14:28:37 +0200898 for child in children:
899 res += sizeofchildren(child)
900 return res
901
902 def check_st_sizeof(st):
903 self.check_sizeof(st, basesize + nodesize +
904 sizeofchildren(st.totuple()))
905
906 check_st_sizeof(parser.expr('2 + 3'))
907 check_st_sizeof(parser.expr('2 + 3 + 4'))
908 check_st_sizeof(parser.suite('x = 2 + 3'))
909 check_st_sizeof(parser.suite(''))
910 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
911 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
912
Mark Dickinson211c6252009-02-01 10:28:51 +0000913
914 # XXX tests for pickling and unpickling of ST objects should go here
915
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500916class OtherParserCase(unittest.TestCase):
917
918 def test_two_args_to_expr(self):
919 # See bug #12264
920 with self.assertRaises(TypeError):
921 parser.expr("a", "b")
922
Fred Drake2e2be372001-09-20 21:33:42 +0000923if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500924 unittest.main()