blob: e7968cc3b30b5e1b8ebc87bd19cf9eb84873d37a [file] [log] [blame]
Fred Drake79ca79d2000-08-21 22:30:53 +00001import parser
Fred Drake58422e52001-06-04 03:56:24 +00002import unittest
Christian Heimesb186d002008-03-18 15:15:01 +00003import sys
Mark Dickinson211c6252009-02-01 10:28:51 +00004import operator
Jesus Ceae9c53182012-08-03 14:28:37 +02005import struct
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Ezio Melotti39191842013-03-09 22:17:33 +02007from test.script_helper import assert_python_failure
Fred Drake79ca79d2000-08-21 22:30:53 +00008
9#
10# First, we test that we can generate trees from valid source fragments,
11# and that these valid trees are indeed allowed by the tree-loading side
12# of the parser module.
13#
14
Fred Drake58422e52001-06-04 03:56:24 +000015class RoundtripLegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000016
Fred Drake58422e52001-06-04 03:56:24 +000017 def roundtrip(self, f, s):
18 st1 = f(s)
19 t = st1.totuple()
20 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +000021 st2 = parser.sequence2st(t)
Guido van Rossumb940e112007-01-10 16:19:56 +000022 except parser.ParserError as why:
Anthony Baxterc2a5a632004-08-02 06:10:11 +000023 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000024
Ezio Melottib3aedd42010-11-20 19:04:17 +000025 self.assertEqual(t, st2.totuple(),
26 "could not re-generate syntax tree")
Fred Drake28f739a2000-08-25 22:42:40 +000027
Fred Drake58422e52001-06-04 03:56:24 +000028 def check_expr(self, s):
29 self.roundtrip(parser.expr, s)
Fred Drake28f739a2000-08-25 22:42:40 +000030
Benjamin Petersonf216c942008-10-31 02:28:05 +000031 def test_flags_passed(self):
32 # The unicode literals flags has to be passed from the paser to AST
33 # generation.
34 suite = parser.suite("from __future__ import unicode_literals; x = ''")
35 code = suite.compile()
36 scope = {}
37 exec(code, {}, scope)
Ezio Melottie9615932010-01-24 19:26:24 +000038 self.assertIsInstance(scope["x"], str)
Benjamin Petersonf216c942008-10-31 02:28:05 +000039
Fred Drake58422e52001-06-04 03:56:24 +000040 def check_suite(self, s):
41 self.roundtrip(parser.suite, s)
Fred Drake28f739a2000-08-25 22:42:40 +000042
Fred Drakecf580c72001-07-17 03:01:29 +000043 def test_yield_statement(self):
Tim Peters496563a2002-04-01 00:28:59 +000044 self.check_suite("def f(): yield 1")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000045 self.check_suite("def f(): yield")
46 self.check_suite("def f(): x += yield")
47 self.check_suite("def f(): x = yield 1")
48 self.check_suite("def f(): x = y = yield 1")
49 self.check_suite("def f(): x = yield")
50 self.check_suite("def f(): x = y = yield")
51 self.check_suite("def f(): 1 + (yield)*2")
52 self.check_suite("def f(): (yield 1)*2")
Tim Peters496563a2002-04-01 00:28:59 +000053 self.check_suite("def f(): return; yield 1")
54 self.check_suite("def f(): yield 1; return")
Nick Coghlan1f7ce622012-01-13 21:43:40 +100055 self.check_suite("def f(): yield from 1")
56 self.check_suite("def f(): x = yield from 1")
57 self.check_suite("def f(): f((yield from 1))")
58 self.check_suite("def f(): yield 1; return 1")
Tim Peters496563a2002-04-01 00:28:59 +000059 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000060 " for x in range(30):\n"
61 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000062 self.check_suite("def f():\n"
63 " if (yield):\n"
64 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000065
Mark Dickinson407b3bd2012-04-29 22:18:31 +010066 def test_nonlocal_statement(self):
67 self.check_suite("def f():\n"
68 " x = 0\n"
69 " def g():\n"
70 " nonlocal x\n")
71 self.check_suite("def f():\n"
72 " x = y = 0\n"
73 " def g():\n"
74 " nonlocal x, y\n")
75
Fred Drake58422e52001-06-04 03:56:24 +000076 def test_expressions(self):
77 self.check_expr("foo(1)")
78 self.check_expr("[1, 2, 3]")
79 self.check_expr("[x**3 for x in range(20)]")
80 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000081 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
82 self.check_expr("list(x**3 for x in range(20))")
83 self.check_expr("list(x**3 for x in range(20) if x % 3)")
84 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +000085 self.check_expr("foo(*args)")
86 self.check_expr("foo(*args, **kw)")
87 self.check_expr("foo(**kw)")
88 self.check_expr("foo(key=value)")
89 self.check_expr("foo(key=value, *args)")
90 self.check_expr("foo(key=value, *args, **kw)")
91 self.check_expr("foo(key=value, **kw)")
92 self.check_expr("foo(a, b, c, *args)")
93 self.check_expr("foo(a, b, c, *args, **kw)")
94 self.check_expr("foo(a, b, c, **kw)")
Benjamin Peterson3938a902008-08-20 02:33:00 +000095 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +000096 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +000097 self.check_expr("foo - bar")
98 self.check_expr("foo * bar")
99 self.check_expr("foo / bar")
100 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +0000101 self.check_expr("lambda: 0")
102 self.check_expr("lambda x: 0")
103 self.check_expr("lambda *y: 0")
104 self.check_expr("lambda *y, **z: 0")
105 self.check_expr("lambda **z: 0")
106 self.check_expr("lambda x, y: 0")
107 self.check_expr("lambda foo=bar: 0")
108 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
109 self.check_expr("lambda foo=bar, **z: 0")
110 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
111 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
112 self.check_expr("lambda x, *y, **z: 0")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000113 self.check_expr("(x for x in range(10))")
114 self.check_expr("foo(x for x in range(10))")
Mark Dickinsonda029fb2012-05-07 17:24:04 +0100115 self.check_expr("...")
116 self.check_expr("a[...]")
Fred Drake79ca79d2000-08-21 22:30:53 +0000117
Fred Drake58422e52001-06-04 03:56:24 +0000118 def test_simple_expression(self):
119 # expr_stmt
120 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000121
Fred Drake58422e52001-06-04 03:56:24 +0000122 def test_simple_assignments(self):
123 self.check_suite("a = b")
124 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000125
Fred Drake58422e52001-06-04 03:56:24 +0000126 def test_simple_augmented_assignments(self):
127 self.check_suite("a += b")
128 self.check_suite("a -= b")
129 self.check_suite("a *= b")
130 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000131 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000132 self.check_suite("a %= b")
133 self.check_suite("a &= b")
134 self.check_suite("a |= b")
135 self.check_suite("a ^= b")
136 self.check_suite("a <<= b")
137 self.check_suite("a >>= b")
138 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000139
Fred Drake58422e52001-06-04 03:56:24 +0000140 def test_function_defs(self):
141 self.check_suite("def f(): pass")
142 self.check_suite("def f(*args): pass")
143 self.check_suite("def f(*args, **kw): pass")
144 self.check_suite("def f(**kw): pass")
145 self.check_suite("def f(foo=bar): pass")
146 self.check_suite("def f(foo=bar, *args): pass")
147 self.check_suite("def f(foo=bar, *args, **kw): pass")
148 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000149
Fred Drake58422e52001-06-04 03:56:24 +0000150 self.check_suite("def f(a, b): pass")
151 self.check_suite("def f(a, b, *args): pass")
152 self.check_suite("def f(a, b, *args, **kw): pass")
153 self.check_suite("def f(a, b, **kw): pass")
154 self.check_suite("def f(a, b, foo=bar): pass")
155 self.check_suite("def f(a, b, foo=bar, *args): pass")
156 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
157 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000158
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000159 self.check_suite("@staticmethod\n"
160 "def f(): pass")
161 self.check_suite("@staticmethod\n"
162 "@funcattrs(x, y)\n"
163 "def f(): pass")
164 self.check_suite("@funcattrs()\n"
165 "def f(): pass")
166
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100167 # keyword-only arguments
168 self.check_suite("def f(*, a): pass")
169 self.check_suite("def f(*, a = 5): pass")
170 self.check_suite("def f(*, a = 5, b): pass")
171 self.check_suite("def f(*, a, b = 5): pass")
172 self.check_suite("def f(*, a, b = 5, **kwds): pass")
173 self.check_suite("def f(*args, a): pass")
174 self.check_suite("def f(*args, a = 5): pass")
175 self.check_suite("def f(*args, a = 5, b): pass")
176 self.check_suite("def f(*args, a, b = 5): pass")
177 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
178
179 # function annotations
180 self.check_suite("def f(a: int): pass")
181 self.check_suite("def f(a: int = 5): pass")
182 self.check_suite("def f(*args: list): pass")
183 self.check_suite("def f(**kwds: dict): pass")
184 self.check_suite("def f(*, a: int): pass")
185 self.check_suite("def f(*, a: int = 5): pass")
186 self.check_suite("def f() -> int: pass")
187
Brett Cannonf4189912005-04-09 02:30:16 +0000188 def test_class_defs(self):
189 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000190 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000191 self.check_suite("@class_decorator\n"
192 "class foo():pass")
193 self.check_suite("@class_decorator(arg)\n"
194 "class foo():pass")
195 self.check_suite("@decorator1\n"
196 "@decorator2\n"
197 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000198
Fred Drake58422e52001-06-04 03:56:24 +0000199 def test_import_from_statement(self):
200 self.check_suite("from sys.path import *")
201 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000202 self.check_suite("from sys.path import (dirname)")
203 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000204 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000205 self.check_suite("from sys.path import (dirname as my_dirname)")
206 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000207 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000208 self.check_suite("from sys.path import (dirname, basename)")
209 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000210 self.check_suite(
211 "from sys.path import dirname as my_dirname, basename")
212 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000213 "from sys.path import (dirname as my_dirname, basename)")
214 self.check_suite(
215 "from sys.path import (dirname as my_dirname, basename,)")
216 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000217 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000218 self.check_suite(
219 "from sys.path import (dirname, basename as my_basename)")
220 self.check_suite(
221 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000222 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000223
Fred Drake58422e52001-06-04 03:56:24 +0000224 def test_basic_import_statement(self):
225 self.check_suite("import sys")
226 self.check_suite("import sys as system")
227 self.check_suite("import sys, math")
228 self.check_suite("import sys as system, math")
229 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000230
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000231 def test_relative_imports(self):
232 self.check_suite("from . import name")
233 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000234 # check all the way up to '....', since '...' is tokenized
235 # differently from '.' (it's an ellipsis token).
236 self.check_suite("from ... import name")
237 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000238 self.check_suite("from .pkg import name")
239 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000240 self.check_suite("from ...pkg import name")
241 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000242
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000243 def test_pep263(self):
244 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
245 "pass\n")
246
247 def test_assert(self):
248 self.check_suite("assert alo < ahi and blo < bhi\n")
249
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000250 def test_with(self):
251 self.check_suite("with open('x'): pass\n")
252 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000253 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000254
Georg Brandleee31162008-12-07 15:15:22 +0000255 def test_try_stmt(self):
256 self.check_suite("try: pass\nexcept: pass\n")
257 self.check_suite("try: pass\nfinally: pass\n")
258 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
259 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
260 "finally: pass\n")
261 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
262 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
263 "finally: pass\n")
264
Thomas Wouters89f507f2006-12-13 04:49:30 +0000265 def test_position(self):
266 # An absolutely minimal test of position information. Better
267 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000268 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000269 st1 = parser.suite(code)
270 st2 = st1.totuple(line_info=1, col_info=1)
271
272 def walk(tree):
273 node_type = tree[0]
274 next = tree[1]
275 if isinstance(next, tuple):
276 for elt in tree[1:]:
277 for x in walk(elt):
278 yield x
279 else:
280 yield tree
281
282 terminals = list(walk(st2))
283 self.assertEqual([
284 (1, 'def', 1, 0),
285 (1, 'f', 1, 4),
286 (7, '(', 1, 5),
287 (1, 'x', 1, 6),
288 (8, ')', 1, 7),
289 (11, ':', 1, 8),
290 (4, '', 1, 9),
291 (5, '', 2, -1),
292 (1, 'return', 2, 4),
293 (1, 'x', 2, 11),
294 (14, '+', 2, 13),
295 (2, '1', 2, 15),
296 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000297 (6, '', 2, -1),
298 (4, '', 2, -1),
299 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000300 terminals)
301
Benjamin Peterson4905e802009-09-27 02:43:28 +0000302 def test_extended_unpacking(self):
303 self.check_suite("*a = y")
304 self.check_suite("x, *b, = m")
305 self.check_suite("[*a, *b] = y")
306 self.check_suite("for [*x, b] in x: pass")
307
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100308 def test_raise_statement(self):
309 self.check_suite("raise\n")
310 self.check_suite("raise e\n")
311 self.check_suite("try:\n"
312 " suite\n"
313 "except Exception as e:\n"
314 " raise ValueError from e\n")
315
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100316 def test_set_displays(self):
317 self.check_expr('{2}')
318 self.check_expr('{2,}')
319 self.check_expr('{2, 3}')
320 self.check_expr('{2, 3,}')
321
322 def test_dict_displays(self):
323 self.check_expr('{}')
324 self.check_expr('{a:b}')
325 self.check_expr('{a:b,}')
326 self.check_expr('{a:b, c:d}')
327 self.check_expr('{a:b, c:d,}')
328
329 def test_set_comprehensions(self):
330 self.check_expr('{x for x in seq}')
331 self.check_expr('{f(x) for x in seq}')
332 self.check_expr('{f(x) for x in seq if condition(x)}')
333
334 def test_dict_comprehensions(self):
335 self.check_expr('{x:x for x in seq}')
336 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
337 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
338
Thomas Wouters89f507f2006-12-13 04:49:30 +0000339
Fred Drake79ca79d2000-08-21 22:30:53 +0000340#
341# Second, we take *invalid* trees and make sure we get ParserError
342# rejections for them.
343#
344
Fred Drake58422e52001-06-04 03:56:24 +0000345class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000346
Fred Drake58422e52001-06-04 03:56:24 +0000347 def check_bad_tree(self, tree, label):
348 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000349 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000350 except parser.ParserError:
351 pass
352 else:
353 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000354
Fred Drake58422e52001-06-04 03:56:24 +0000355 def test_junk(self):
356 # not even remotely valid:
357 self.check_bad_tree((1, 2, 3), "<junk>")
358
Fred Drakecf580c72001-07-17 03:01:29 +0000359 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000360 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000361 tree = \
362 (257,
363 (264,
364 (285,
365 (259,
366 (1, 'def'),
367 (1, 'f'),
368 (260, (7, '('), (8, ')')),
369 (11, ':'),
370 (291,
371 (4, ''),
372 (5, ''),
373 (264,
374 (265,
375 (266,
376 (272,
377 (275,
378 (1, 'return'),
379 (313,
380 (292,
381 (293,
382 (294,
383 (295,
384 (297,
385 (298,
386 (299,
387 (300,
388 (301,
389 (302, (303, (304, (305, (2, '1')))))))))))))))))),
390 (264,
391 (265,
392 (266,
393 (272,
394 (276,
395 (1, 'yield'),
396 (313,
397 (292,
398 (293,
399 (294,
400 (295,
401 (297,
402 (298,
403 (299,
404 (300,
405 (301,
406 (302,
407 (303, (304, (305, (2, '1')))))))))))))))))),
408 (4, ''))),
409 (6, ''))))),
410 (4, ''),
411 (0, ''))))
412 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
413
414 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000415 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000416 tree = \
417 (257,
418 (264,
419 (265,
420 (266,
421 (278,
422 (1, 'from'),
423 (281, (1, '__future__')),
424 (1, 'import'),
425 (279, (1, 'generators')))),
426 (4, ''))),
427 (264,
428 (285,
429 (259,
430 (1, 'def'),
431 (1, 'f'),
432 (260, (7, '('), (8, ')')),
433 (11, ':'),
434 (291,
435 (4, ''),
436 (5, ''),
437 (264,
438 (265,
439 (266,
440 (272,
441 (275,
442 (1, 'return'),
443 (313,
444 (292,
445 (293,
446 (294,
447 (295,
448 (297,
449 (298,
450 (299,
451 (300,
452 (301,
453 (302, (303, (304, (305, (2, '1')))))))))))))))))),
454 (264,
455 (265,
456 (266,
457 (272,
458 (276,
459 (1, 'yield'),
460 (313,
461 (292,
462 (293,
463 (294,
464 (295,
465 (297,
466 (298,
467 (299,
468 (300,
469 (301,
470 (302,
471 (303, (304, (305, (2, '1')))))))))))))))))),
472 (4, ''))),
473 (6, ''))))),
474 (4, ''),
475 (0, ''))))
476 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
477
Fred Drake58422e52001-06-04 03:56:24 +0000478 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000479 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000480 tree = \
481 (258,
482 (311,
483 (290,
484 (291,
485 (292,
486 (293,
487 (295,
488 (296,
489 (297,
490 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
491 (12, ','),
492 (12, ','),
493 (290,
494 (291,
495 (292,
496 (293,
497 (295,
498 (296,
499 (297,
500 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
501 (4, ''),
502 (0, ''))
503 self.check_bad_tree(tree, "a,,c")
504
505 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000506 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000507 tree = \
508 (257,
509 (264,
510 (265,
511 (266,
512 (267,
513 (312,
514 (291,
515 (292,
516 (293,
517 (294,
518 (296,
519 (297,
520 (298,
521 (299,
522 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
523 (268, (37, '$=')),
524 (312,
525 (291,
526 (292,
527 (293,
528 (294,
529 (296,
530 (297,
531 (298,
532 (299,
533 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
534 (4, ''))),
535 (0, ''))
536 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000537
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000538 def test_malformed_global(self):
539 #doesn't have global keyword in ast
540 tree = (257,
541 (264,
542 (265,
543 (266,
544 (282, (1, 'foo'))), (4, ''))),
545 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000546 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000547 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000548
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000549 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000550 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000551 tree = \
552 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000553 (268,
554 (269,
555 (270,
556 (282,
557 (284, (1, 'from'), (1, 'import'),
558 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000559 (4, ''))),
560 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000561 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000562
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000563
564class CompileTestCase(unittest.TestCase):
565
566 # These tests are very minimal. :-(
567
568 def test_compile_expr(self):
569 st = parser.expr('2 + 3')
570 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000571 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572
573 def test_compile_suite(self):
574 st = parser.suite('x = 2; y = x + 3')
575 code = parser.compilest(st)
576 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000577 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000578 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579
580 def test_compile_error(self):
581 st = parser.suite('1 = 3 + 4')
582 self.assertRaises(SyntaxError, parser.compilest, st)
583
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000584 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000585 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000586 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000587 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000588 self.assertRaises(SyntaxError, parser.compilest, st)
589
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000590 def test_issue_9011(self):
591 # Issue 9011: compilation of an unary minus expression changed
592 # the meaning of the ST, so that a second compilation produced
593 # incorrect results.
594 st = parser.expr('-3')
595 code1 = parser.compilest(st)
596 self.assertEqual(eval(code1), -3)
597 code2 = parser.compilest(st)
598 self.assertEqual(eval(code2), -3)
599
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000600class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000601 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000602 see http://bugs.python.org/issue1881 for a discussion
603 """
604 def _nested_expression(self, level):
605 return "["*level+"]"*level
606
607 def test_deeply_nested_list(self):
608 # XXX used to be 99 levels in 2.x
609 e = self._nested_expression(93)
610 st = parser.expr(e)
611 st.compile()
612
613 def test_trigger_memory_error(self):
614 e = self._nested_expression(100)
Ezio Melotti39191842013-03-09 22:17:33 +0200615 rc, out, err = assert_python_failure('-c', e)
616 # parsing the expression will result in an error message
617 # followed by a MemoryError (see #11963)
Ezio Melottie7c32992013-03-10 03:25:45 +0200618 self.assertIn(b's_push: parser stack overflow', err)
619 self.assertIn(b'MemoryError', err)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000620
Mark Dickinson211c6252009-02-01 10:28:51 +0000621class STObjectTestCase(unittest.TestCase):
622 """Test operations on ST objects themselves"""
623
624 def test_comparisons(self):
625 # ST objects should support order and equality comparisons
626 st1 = parser.expr('2 + 3')
627 st2 = parser.suite('x = 2; y = x + 3')
628 st3 = parser.expr('list(x**3 for x in range(20))')
629 st1_copy = parser.expr('2 + 3')
630 st2_copy = parser.suite('x = 2; y = x + 3')
631 st3_copy = parser.expr('list(x**3 for x in range(20))')
632
633 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000634 self.assertEqual(st1 == st1, True)
635 self.assertEqual(st2 == st2, True)
636 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000637 # slow path equality
638 self.assertEqual(st1, st1_copy)
639 self.assertEqual(st2, st2_copy)
640 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000641 self.assertEqual(st1 == st2, False)
642 self.assertEqual(st1 == st3, False)
643 self.assertEqual(st2 == st3, False)
644 self.assertEqual(st1 != st1, False)
645 self.assertEqual(st2 != st2, False)
646 self.assertEqual(st3 != st3, False)
647 self.assertEqual(st1 != st1_copy, False)
648 self.assertEqual(st2 != st2_copy, False)
649 self.assertEqual(st3 != st3_copy, False)
650 self.assertEqual(st2 != st1, True)
651 self.assertEqual(st1 != st3, True)
652 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000653 # we don't particularly care what the ordering is; just that
654 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000655 self.assertEqual(st1 < st2, not (st2 <= st1))
656 self.assertEqual(st1 < st3, not (st3 <= st1))
657 self.assertEqual(st2 < st3, not (st3 <= st2))
658 self.assertEqual(st1 < st2, st2 > st1)
659 self.assertEqual(st1 < st3, st3 > st1)
660 self.assertEqual(st2 < st3, st3 > st2)
661 self.assertEqual(st1 <= st2, st2 >= st1)
662 self.assertEqual(st3 <= st1, st1 >= st3)
663 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000664 # transitivity
665 bottom = min(st1, st2, st3)
666 top = max(st1, st2, st3)
667 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000668 self.assertTrue(bottom < mid)
669 self.assertTrue(bottom < top)
670 self.assertTrue(mid < top)
671 self.assertTrue(bottom <= mid)
672 self.assertTrue(bottom <= top)
673 self.assertTrue(mid <= top)
674 self.assertTrue(bottom <= bottom)
675 self.assertTrue(mid <= mid)
676 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000677 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000678 self.assertEqual(st1 == 1588.602459, False)
679 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000680 self.assertRaises(TypeError, operator.ge, st3, None)
681 self.assertRaises(TypeError, operator.le, False, st1)
682 self.assertRaises(TypeError, operator.lt, st1, 1815)
683 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
684
Jesus Ceae9c53182012-08-03 14:28:37 +0200685 check_sizeof = support.check_sizeof
686
687 @support.cpython_only
688 def test_sizeof(self):
689 def XXXROUNDUP(n):
690 if n <= 1:
691 return n
692 if n <= 128:
693 return (n + 3) & ~3
694 return 1 << (n - 1).bit_length()
695
696 basesize = support.calcobjsize('Pii')
697 nodesize = struct.calcsize('hP3iP0h')
698 def sizeofchildren(node):
699 if node is None:
700 return 0
701 res = 0
702 hasstr = len(node) > 1 and isinstance(node[-1], str)
703 if hasstr:
704 res += len(node[-1]) + 1
705 children = node[1:-1] if hasstr else node[1:]
706 if children:
707 res += XXXROUNDUP(len(children)) * nodesize
Jesus Ceae9c53182012-08-03 14:28:37 +0200708 for child in children:
709 res += sizeofchildren(child)
710 return res
711
712 def check_st_sizeof(st):
713 self.check_sizeof(st, basesize + nodesize +
714 sizeofchildren(st.totuple()))
715
716 check_st_sizeof(parser.expr('2 + 3'))
717 check_st_sizeof(parser.expr('2 + 3 + 4'))
718 check_st_sizeof(parser.suite('x = 2 + 3'))
719 check_st_sizeof(parser.suite(''))
720 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
721 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
722
Mark Dickinson211c6252009-02-01 10:28:51 +0000723
724 # XXX tests for pickling and unpickling of ST objects should go here
725
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500726class OtherParserCase(unittest.TestCase):
727
728 def test_two_args_to_expr(self):
729 # See bug #12264
730 with self.assertRaises(TypeError):
731 parser.expr("a", "b")
732
Fred Drake2e2be372001-09-20 21:33:42 +0000733def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000734 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000735 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736 IllegalSyntaxTestCase,
737 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000738 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000739 STObjectTestCase,
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500740 OtherParserCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000741 )
Fred Drake2e2be372001-09-20 21:33:42 +0000742
743
744if __name__ == "__main__":
745 test_main()