blob: 2f1b21978099fbff4674daa7c69377078c3e0d4d [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
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321 def test_position(self):
322 # An absolutely minimal test of position information. Better
323 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000324 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325 st1 = parser.suite(code)
326 st2 = st1.totuple(line_info=1, col_info=1)
327
328 def walk(tree):
329 node_type = tree[0]
330 next = tree[1]
331 if isinstance(next, tuple):
332 for elt in tree[1:]:
333 for x in walk(elt):
334 yield x
335 else:
336 yield tree
337
338 terminals = list(walk(st2))
339 self.assertEqual([
340 (1, 'def', 1, 0),
341 (1, 'f', 1, 4),
342 (7, '(', 1, 5),
343 (1, 'x', 1, 6),
344 (8, ')', 1, 7),
345 (11, ':', 1, 8),
346 (4, '', 1, 9),
347 (5, '', 2, -1),
348 (1, 'return', 2, 4),
349 (1, 'x', 2, 11),
350 (14, '+', 2, 13),
351 (2, '1', 2, 15),
352 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000353 (6, '', 2, -1),
354 (4, '', 2, -1),
355 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356 terminals)
357
Benjamin Peterson4905e802009-09-27 02:43:28 +0000358 def test_extended_unpacking(self):
359 self.check_suite("*a = y")
360 self.check_suite("x, *b, = m")
361 self.check_suite("[*a, *b] = y")
362 self.check_suite("for [*x, b] in x: pass")
363
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100364 def test_raise_statement(self):
365 self.check_suite("raise\n")
366 self.check_suite("raise e\n")
367 self.check_suite("try:\n"
368 " suite\n"
369 "except Exception as e:\n"
370 " raise ValueError from e\n")
371
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400372 def test_list_displays(self):
373 self.check_expr('[]')
374 self.check_expr('[*{2}, 3, *[4]]')
375
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100376 def test_set_displays(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400377 self.check_expr('{*{2}, 3, *[4]}')
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100378 self.check_expr('{2}')
379 self.check_expr('{2,}')
380 self.check_expr('{2, 3}')
381 self.check_expr('{2, 3,}')
382
383 def test_dict_displays(self):
384 self.check_expr('{}')
385 self.check_expr('{a:b}')
386 self.check_expr('{a:b,}')
387 self.check_expr('{a:b, c:d}')
388 self.check_expr('{a:b, c:d,}')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400389 self.check_expr('{**{}}')
390 self.check_expr('{**{}, 3:4, **{5:6, 7:8}}')
391
392 def test_argument_unpacking(self):
Yury Selivanov50a26142015-08-05 17:59:45 -0400393 self.check_expr("f(*a, **b)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400394 self.check_expr('f(a, *b, *c, *d)')
395 self.check_expr('f(**a, **b)')
396 self.check_expr('f(2, *a, *b, **b, **c, **d)')
Yury Selivanov50a26142015-08-05 17:59:45 -0400397 self.check_expr("f(*b, *() or () and (), **{} and {}, **() or {})")
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100398
399 def test_set_comprehensions(self):
400 self.check_expr('{x for x in seq}')
401 self.check_expr('{f(x) for x in seq}')
402 self.check_expr('{f(x) for x in seq if condition(x)}')
403
404 def test_dict_comprehensions(self):
405 self.check_expr('{x:x for x in seq}')
406 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
407 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
408
Thomas Wouters89f507f2006-12-13 04:49:30 +0000409
Fred Drake79ca79d2000-08-21 22:30:53 +0000410#
411# Second, we take *invalid* trees and make sure we get ParserError
412# rejections for them.
413#
414
Fred Drake58422e52001-06-04 03:56:24 +0000415class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000416
Fred Drake58422e52001-06-04 03:56:24 +0000417 def check_bad_tree(self, tree, label):
418 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000419 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000420 except parser.ParserError:
421 pass
422 else:
423 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000424
Fred Drake58422e52001-06-04 03:56:24 +0000425 def test_junk(self):
426 # not even remotely valid:
427 self.check_bad_tree((1, 2, 3), "<junk>")
428
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300429 def test_illegal_terminal(self):
430 tree = \
431 (257,
432 (269,
433 (270,
434 (271,
435 (277,
436 (1,))),
437 (4, ''))),
438 (4, ''),
439 (0, ''))
440 self.check_bad_tree(tree, "too small items in terminal node")
441 tree = \
442 (257,
443 (269,
444 (270,
445 (271,
446 (277,
447 (1, b'pass'))),
448 (4, ''))),
449 (4, ''),
450 (0, ''))
451 self.check_bad_tree(tree, "non-string second item in terminal node")
452 tree = \
453 (257,
454 (269,
455 (270,
456 (271,
457 (277,
458 (1, 'pass', '0', 0))),
459 (4, ''))),
460 (4, ''),
461 (0, ''))
462 self.check_bad_tree(tree, "non-integer third item in terminal node")
463 tree = \
464 (257,
465 (269,
466 (270,
467 (271,
468 (277,
469 (1, 'pass', 0, 0))),
470 (4, ''))),
471 (4, ''),
472 (0, ''))
473 self.check_bad_tree(tree, "too many items in terminal node")
474
Fred Drakecf580c72001-07-17 03:01:29 +0000475 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000476 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000477 tree = \
478 (257,
479 (264,
480 (285,
481 (259,
482 (1, 'def'),
483 (1, 'f'),
484 (260, (7, '('), (8, ')')),
485 (11, ':'),
486 (291,
487 (4, ''),
488 (5, ''),
489 (264,
490 (265,
491 (266,
492 (272,
493 (275,
494 (1, 'return'),
495 (313,
496 (292,
497 (293,
498 (294,
499 (295,
500 (297,
501 (298,
502 (299,
503 (300,
504 (301,
505 (302, (303, (304, (305, (2, '1')))))))))))))))))),
506 (264,
507 (265,
508 (266,
509 (272,
510 (276,
511 (1, 'yield'),
512 (313,
513 (292,
514 (293,
515 (294,
516 (295,
517 (297,
518 (298,
519 (299,
520 (300,
521 (301,
522 (302,
523 (303, (304, (305, (2, '1')))))))))))))))))),
524 (4, ''))),
525 (6, ''))))),
526 (4, ''),
527 (0, ''))))
528 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
529
530 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000531 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000532 tree = \
533 (257,
534 (264,
535 (265,
536 (266,
537 (278,
538 (1, 'from'),
539 (281, (1, '__future__')),
540 (1, 'import'),
541 (279, (1, 'generators')))),
542 (4, ''))),
543 (264,
544 (285,
545 (259,
546 (1, 'def'),
547 (1, 'f'),
548 (260, (7, '('), (8, ')')),
549 (11, ':'),
550 (291,
551 (4, ''),
552 (5, ''),
553 (264,
554 (265,
555 (266,
556 (272,
557 (275,
558 (1, 'return'),
559 (313,
560 (292,
561 (293,
562 (294,
563 (295,
564 (297,
565 (298,
566 (299,
567 (300,
568 (301,
569 (302, (303, (304, (305, (2, '1')))))))))))))))))),
570 (264,
571 (265,
572 (266,
573 (272,
574 (276,
575 (1, 'yield'),
576 (313,
577 (292,
578 (293,
579 (294,
580 (295,
581 (297,
582 (298,
583 (299,
584 (300,
585 (301,
586 (302,
587 (303, (304, (305, (2, '1')))))))))))))))))),
588 (4, ''))),
589 (6, ''))))),
590 (4, ''),
591 (0, ''))))
592 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
593
Fred Drake58422e52001-06-04 03:56:24 +0000594 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000595 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000596 tree = \
597 (258,
598 (311,
599 (290,
600 (291,
601 (292,
602 (293,
603 (295,
604 (296,
605 (297,
606 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
607 (12, ','),
608 (12, ','),
609 (290,
610 (291,
611 (292,
612 (293,
613 (295,
614 (296,
615 (297,
616 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
617 (4, ''),
618 (0, ''))
619 self.check_bad_tree(tree, "a,,c")
620
621 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000622 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000623 tree = \
624 (257,
625 (264,
626 (265,
627 (266,
628 (267,
629 (312,
630 (291,
631 (292,
632 (293,
633 (294,
634 (296,
635 (297,
636 (298,
637 (299,
638 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
639 (268, (37, '$=')),
640 (312,
641 (291,
642 (292,
643 (293,
644 (294,
645 (296,
646 (297,
647 (298,
648 (299,
649 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
650 (4, ''))),
651 (0, ''))
652 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000653
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000654 def test_malformed_global(self):
655 #doesn't have global keyword in ast
656 tree = (257,
657 (264,
658 (265,
659 (266,
660 (282, (1, 'foo'))), (4, ''))),
661 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000662 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000663 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000664
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000665 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000666 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000667 tree = \
668 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000669 (268,
670 (269,
671 (270,
672 (282,
673 (284, (1, 'from'), (1, 'import'),
674 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000675 (4, ''))),
676 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000677 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000678
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300679 def test_illegal_encoding(self):
680 # Illegal encoding declaration
681 tree = \
Jelle Zijlstraac317702017-10-05 20:24:46 -0700682 (340,
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300683 (257, (0, '')))
684 self.check_bad_tree(tree, "missed encoding")
685 tree = \
Jelle Zijlstraac317702017-10-05 20:24:46 -0700686 (340,
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300687 (257, (0, '')),
688 b'iso-8859-1')
689 self.check_bad_tree(tree, "non-string encoding")
690 tree = \
Jelle Zijlstraac317702017-10-05 20:24:46 -0700691 (340,
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300692 (257, (0, '')),
693 '\udcff')
694 with self.assertRaises(UnicodeEncodeError):
695 parser.sequence2st(tree)
696
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000697
698class CompileTestCase(unittest.TestCase):
699
700 # These tests are very minimal. :-(
701
702 def test_compile_expr(self):
703 st = parser.expr('2 + 3')
704 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000705 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000706
707 def test_compile_suite(self):
708 st = parser.suite('x = 2; y = x + 3')
709 code = parser.compilest(st)
710 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000711 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000712 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000713
714 def test_compile_error(self):
715 st = parser.suite('1 = 3 + 4')
716 self.assertRaises(SyntaxError, parser.compilest, st)
717
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000718 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000719 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000720 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000721 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000722 self.assertRaises(SyntaxError, parser.compilest, st)
723
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000724 def test_issue_9011(self):
725 # Issue 9011: compilation of an unary minus expression changed
726 # the meaning of the ST, so that a second compilation produced
727 # incorrect results.
728 st = parser.expr('-3')
729 code1 = parser.compilest(st)
730 self.assertEqual(eval(code1), -3)
731 code2 = parser.compilest(st)
732 self.assertEqual(eval(code2), -3)
733
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300734 def test_compile_filename(self):
735 st = parser.expr('a + 5')
736 code = parser.compilest(st)
737 self.assertEqual(code.co_filename, '<syntax-tree>')
738 code = st.compile()
739 self.assertEqual(code.co_filename, '<syntax-tree>')
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300740 for filename in 'file.py', b'file.py':
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300741 code = parser.compilest(st, filename)
742 self.assertEqual(code.co_filename, 'file.py')
743 code = st.compile(filename)
744 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300745 for filename in bytearray(b'file.py'), memoryview(b'file.py'):
746 with self.assertWarns(DeprecationWarning):
747 code = parser.compilest(st, filename)
748 self.assertEqual(code.co_filename, 'file.py')
749 with self.assertWarns(DeprecationWarning):
750 code = st.compile(filename)
751 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300752 self.assertRaises(TypeError, parser.compilest, st, list(b'file.py'))
753 self.assertRaises(TypeError, st.compile, list(b'file.py'))
754
755
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000756class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000757 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000758 see http://bugs.python.org/issue1881 for a discussion
759 """
760 def _nested_expression(self, level):
761 return "["*level+"]"*level
762
763 def test_deeply_nested_list(self):
764 # XXX used to be 99 levels in 2.x
765 e = self._nested_expression(93)
766 st = parser.expr(e)
767 st.compile()
768
769 def test_trigger_memory_error(self):
770 e = self._nested_expression(100)
Ezio Melotti39191842013-03-09 22:17:33 +0200771 rc, out, err = assert_python_failure('-c', e)
772 # parsing the expression will result in an error message
773 # followed by a MemoryError (see #11963)
Ezio Melottie7c32992013-03-10 03:25:45 +0200774 self.assertIn(b's_push: parser stack overflow', err)
775 self.assertIn(b'MemoryError', err)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000776
Mark Dickinson211c6252009-02-01 10:28:51 +0000777class STObjectTestCase(unittest.TestCase):
778 """Test operations on ST objects themselves"""
779
780 def test_comparisons(self):
781 # ST objects should support order and equality comparisons
782 st1 = parser.expr('2 + 3')
783 st2 = parser.suite('x = 2; y = x + 3')
784 st3 = parser.expr('list(x**3 for x in range(20))')
785 st1_copy = parser.expr('2 + 3')
786 st2_copy = parser.suite('x = 2; y = x + 3')
787 st3_copy = parser.expr('list(x**3 for x in range(20))')
788
789 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000790 self.assertEqual(st1 == st1, True)
791 self.assertEqual(st2 == st2, True)
792 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000793 # slow path equality
794 self.assertEqual(st1, st1_copy)
795 self.assertEqual(st2, st2_copy)
796 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000797 self.assertEqual(st1 == st2, False)
798 self.assertEqual(st1 == st3, False)
799 self.assertEqual(st2 == st3, False)
800 self.assertEqual(st1 != st1, False)
801 self.assertEqual(st2 != st2, False)
802 self.assertEqual(st3 != st3, False)
803 self.assertEqual(st1 != st1_copy, False)
804 self.assertEqual(st2 != st2_copy, False)
805 self.assertEqual(st3 != st3_copy, False)
806 self.assertEqual(st2 != st1, True)
807 self.assertEqual(st1 != st3, True)
808 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000809 # we don't particularly care what the ordering is; just that
810 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000811 self.assertEqual(st1 < st2, not (st2 <= st1))
812 self.assertEqual(st1 < st3, not (st3 <= st1))
813 self.assertEqual(st2 < st3, not (st3 <= st2))
814 self.assertEqual(st1 < st2, st2 > st1)
815 self.assertEqual(st1 < st3, st3 > st1)
816 self.assertEqual(st2 < st3, st3 > st2)
817 self.assertEqual(st1 <= st2, st2 >= st1)
818 self.assertEqual(st3 <= st1, st1 >= st3)
819 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000820 # transitivity
821 bottom = min(st1, st2, st3)
822 top = max(st1, st2, st3)
823 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000824 self.assertTrue(bottom < mid)
825 self.assertTrue(bottom < top)
826 self.assertTrue(mid < top)
827 self.assertTrue(bottom <= mid)
828 self.assertTrue(bottom <= top)
829 self.assertTrue(mid <= top)
830 self.assertTrue(bottom <= bottom)
831 self.assertTrue(mid <= mid)
832 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000833 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000834 self.assertEqual(st1 == 1588.602459, False)
835 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000836 self.assertRaises(TypeError, operator.ge, st3, None)
837 self.assertRaises(TypeError, operator.le, False, st1)
838 self.assertRaises(TypeError, operator.lt, st1, 1815)
839 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
840
Serhiy Storchakaa79f4c22017-04-19 21:09:21 +0300841 def test_copy_pickle(self):
842 sts = [
843 parser.expr('2 + 3'),
844 parser.suite('x = 2; y = x + 3'),
845 parser.expr('list(x**3 for x in range(20))')
846 ]
847 for st in sts:
848 st_copy = copy.copy(st)
849 self.assertEqual(st_copy.totuple(), st.totuple())
850 st_copy = copy.deepcopy(st)
851 self.assertEqual(st_copy.totuple(), st.totuple())
852 for proto in range(pickle.HIGHEST_PROTOCOL+1):
853 st_copy = pickle.loads(pickle.dumps(st, proto))
854 self.assertEqual(st_copy.totuple(), st.totuple())
855
Jesus Ceae9c53182012-08-03 14:28:37 +0200856 check_sizeof = support.check_sizeof
857
858 @support.cpython_only
859 def test_sizeof(self):
860 def XXXROUNDUP(n):
861 if n <= 1:
862 return n
863 if n <= 128:
864 return (n + 3) & ~3
865 return 1 << (n - 1).bit_length()
866
867 basesize = support.calcobjsize('Pii')
868 nodesize = struct.calcsize('hP3iP0h')
869 def sizeofchildren(node):
870 if node is None:
871 return 0
872 res = 0
873 hasstr = len(node) > 1 and isinstance(node[-1], str)
874 if hasstr:
875 res += len(node[-1]) + 1
876 children = node[1:-1] if hasstr else node[1:]
877 if children:
878 res += XXXROUNDUP(len(children)) * nodesize
Jesus Ceae9c53182012-08-03 14:28:37 +0200879 for child in children:
880 res += sizeofchildren(child)
881 return res
882
883 def check_st_sizeof(st):
884 self.check_sizeof(st, basesize + nodesize +
885 sizeofchildren(st.totuple()))
886
887 check_st_sizeof(parser.expr('2 + 3'))
888 check_st_sizeof(parser.expr('2 + 3 + 4'))
889 check_st_sizeof(parser.suite('x = 2 + 3'))
890 check_st_sizeof(parser.suite(''))
891 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
892 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
893
Mark Dickinson211c6252009-02-01 10:28:51 +0000894
895 # XXX tests for pickling and unpickling of ST objects should go here
896
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500897class OtherParserCase(unittest.TestCase):
898
899 def test_two_args_to_expr(self):
900 # See bug #12264
901 with self.assertRaises(TypeError):
902 parser.expr("a", "b")
903
Fred Drake2e2be372001-09-20 21:33:42 +0000904if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500905 unittest.main()