blob: 34b9cbb8c1636822536273d28c5016122f0c976f [file] [log] [blame]
Serhiy Storchaka2a1bf062017-04-20 00:48:57 +03001import copy
Fred Drake79ca79d2000-08-21 22:30:53 +00002import parser
Serhiy Storchaka2a1bf062017-04-20 00:48:57 +03003import pickle
Fred Drake58422e52001-06-04 03:56:24 +00004import unittest
Martin v. Löwis66e26632008-03-18 13:16:05 +00005import sys
Jesus Cea3e3192d2012-08-03 14:25:53 +02006import struct
7from test import test_support as support
Ezio Melottida9eeae2013-03-09 22:17:33 +02008from test.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)
Anthony Baxterc2a5a632004-08-02 06:10:11 +000023 except parser.ParserError, why:
24 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000025
Ezio Melotti2623a372010-11-21 13:34:58 +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 Petersondcee09d2008-10-31 02:16:05 +000032 def test_flags_passed(self):
33 # The unicode literals flags has to be passed from the paser to AST
34 # generation.
35 suite = parser.suite("from __future__ import unicode_literals; x = ''")
36 code = suite.compile()
37 scope = {}
38 exec code in scope
Ezio Melottib0f5adc2010-01-24 16:58:36 +000039 self.assertIsInstance(scope["x"], unicode)
Benjamin Petersondcee09d2008-10-31 02:16: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")
56 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000057 " for x in range(30):\n"
58 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000059 self.check_suite("def f():\n"
60 " if (yield):\n"
61 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000062
Fred Drake58422e52001-06-04 03:56:24 +000063 def test_expressions(self):
64 self.check_expr("foo(1)")
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000065 self.check_expr("{1:1}")
66 self.check_expr("{1:1, 2:2, 3:3}")
67 self.check_expr("{1:1, 2:2, 3:3,}")
68 self.check_expr("{1}")
69 self.check_expr("{1, 2, 3}")
70 self.check_expr("{1, 2, 3,}")
71 self.check_expr("[]")
72 self.check_expr("[1]")
Fred Drake58422e52001-06-04 03:56:24 +000073 self.check_expr("[1, 2, 3]")
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000074 self.check_expr("[1, 2, 3,]")
75 self.check_expr("()")
76 self.check_expr("(1,)")
77 self.check_expr("(1, 2, 3)")
78 self.check_expr("(1, 2, 3,)")
Fred Drake58422e52001-06-04 03:56:24 +000079 self.check_expr("[x**3 for x in range(20)]")
80 self.check_expr("[x**3 for x in range(20) if x % 3]")
Neal Norwitzd3a91622006-04-12 05:27:46 +000081 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
Alexandre Vassalottib6465472010-01-11 22:36:12 +000082 self.check_expr("[x+y for x in range(30) for y in range(20) if x % 2 if y % 3]")
83 #self.check_expr("[x for x in lambda: True, lambda: False if x()]")
Neal Norwitzd3a91622006-04-12 05:27:46 +000084 self.check_expr("list(x**3 for x in range(20))")
85 self.check_expr("list(x**3 for x in range(20) if x % 3)")
86 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Alexandre Vassalottib6465472010-01-11 22:36:12 +000087 self.check_expr("list(x+y for x in range(30) for y in range(20) if x % 2 if y % 3)")
88 self.check_expr("{x**3 for x in range(30)}")
89 self.check_expr("{x**3 for x in range(30) if x % 3}")
90 self.check_expr("{x**3 for x in range(30) if x % 2 if x % 3}")
91 self.check_expr("{x+y for x in range(30) for y in range(20) if x % 2 if y % 3}")
92 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30))}")
93 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3}")
94 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3 if y % 3}")
95 self.check_expr("{x:y for x in range(30) for y in range(20) if x % 2 if y % 3}")
Fred Drake58422e52001-06-04 03:56:24 +000096 self.check_expr("foo(*args)")
97 self.check_expr("foo(*args, **kw)")
98 self.check_expr("foo(**kw)")
99 self.check_expr("foo(key=value)")
100 self.check_expr("foo(key=value, *args)")
101 self.check_expr("foo(key=value, *args, **kw)")
102 self.check_expr("foo(key=value, **kw)")
103 self.check_expr("foo(a, b, c, *args)")
104 self.check_expr("foo(a, b, c, *args, **kw)")
105 self.check_expr("foo(a, b, c, **kw)")
Benjamin Petersonbd6a05f2008-08-19 22:06:11 +0000106 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +0000107 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000108 self.check_expr("foo - bar")
109 self.check_expr("foo * bar")
110 self.check_expr("foo / bar")
111 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +0000112 self.check_expr("lambda: 0")
113 self.check_expr("lambda x: 0")
114 self.check_expr("lambda *y: 0")
115 self.check_expr("lambda *y, **z: 0")
116 self.check_expr("lambda **z: 0")
117 self.check_expr("lambda x, y: 0")
118 self.check_expr("lambda foo=bar: 0")
119 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
120 self.check_expr("lambda foo=bar, **z: 0")
121 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
122 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
123 self.check_expr("lambda x, *y, **z: 0")
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000124 self.check_expr("lambda x: 5 if x else 2")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000125 self.check_expr("(x for x in range(10))")
126 self.check_expr("foo(x for x in range(10))")
Fred Drake79ca79d2000-08-21 22:30:53 +0000127
Fred Drake58422e52001-06-04 03:56:24 +0000128 def test_print(self):
129 self.check_suite("print")
130 self.check_suite("print 1")
131 self.check_suite("print 1,")
132 self.check_suite("print >>fp")
133 self.check_suite("print >>fp, 1")
134 self.check_suite("print >>fp, 1,")
Fred Drake79ca79d2000-08-21 22:30:53 +0000135
Fred Drake58422e52001-06-04 03:56:24 +0000136 def test_simple_expression(self):
137 # expr_stmt
138 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000139
Fred Drake58422e52001-06-04 03:56:24 +0000140 def test_simple_assignments(self):
141 self.check_suite("a = b")
142 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000143
Fred Drake58422e52001-06-04 03:56:24 +0000144 def test_simple_augmented_assignments(self):
145 self.check_suite("a += b")
146 self.check_suite("a -= b")
147 self.check_suite("a *= b")
148 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000149 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000150 self.check_suite("a %= b")
151 self.check_suite("a &= b")
152 self.check_suite("a |= b")
153 self.check_suite("a ^= b")
154 self.check_suite("a <<= b")
155 self.check_suite("a >>= b")
156 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000157
Fred Drake58422e52001-06-04 03:56:24 +0000158 def test_function_defs(self):
159 self.check_suite("def f(): pass")
160 self.check_suite("def f(*args): pass")
161 self.check_suite("def f(*args, **kw): pass")
162 self.check_suite("def f(**kw): pass")
163 self.check_suite("def f(foo=bar): pass")
164 self.check_suite("def f(foo=bar, *args): pass")
165 self.check_suite("def f(foo=bar, *args, **kw): pass")
166 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000167
Fred Drake58422e52001-06-04 03:56:24 +0000168 self.check_suite("def f(a, b): pass")
169 self.check_suite("def f(a, b, *args): pass")
170 self.check_suite("def f(a, b, *args, **kw): pass")
171 self.check_suite("def f(a, b, **kw): pass")
172 self.check_suite("def f(a, b, foo=bar): pass")
173 self.check_suite("def f(a, b, foo=bar, *args): pass")
174 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
175 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000176
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000177 self.check_suite("@staticmethod\n"
178 "def f(): pass")
179 self.check_suite("@staticmethod\n"
180 "@funcattrs(x, y)\n"
181 "def f(): pass")
182 self.check_suite("@funcattrs()\n"
183 "def f(): pass")
184
Brett Cannonf4189912005-04-09 02:30:16 +0000185 def test_class_defs(self):
186 self.check_suite("class foo():pass")
Mark Dickinsona7ee59b2010-07-04 16:23:54 +0000187 self.check_suite("@class_decorator\n"
188 "class foo():pass")
189 self.check_suite("@class_decorator(arg)\n"
190 "class foo():pass")
191 self.check_suite("@decorator1\n"
192 "@decorator2\n"
193 "class foo():pass")
194
Tim Peterse8906822005-04-20 17:45:13 +0000195
Fred Drake58422e52001-06-04 03:56:24 +0000196 def test_import_from_statement(self):
197 self.check_suite("from sys.path import *")
198 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000199 self.check_suite("from sys.path import (dirname)")
200 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000201 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000202 self.check_suite("from sys.path import (dirname as my_dirname)")
203 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000204 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000205 self.check_suite("from sys.path import (dirname, basename)")
206 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000207 self.check_suite(
208 "from sys.path import dirname as my_dirname, basename")
209 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000210 "from sys.path import (dirname as my_dirname, basename)")
211 self.check_suite(
212 "from sys.path import (dirname as my_dirname, basename,)")
213 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000214 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000215 self.check_suite(
216 "from sys.path import (dirname, basename as my_basename)")
217 self.check_suite(
218 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Peterson6624a9f2008-11-03 15:14:51 +0000219 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000220
Fred Drake58422e52001-06-04 03:56:24 +0000221 def test_basic_import_statement(self):
222 self.check_suite("import sys")
223 self.check_suite("import sys as system")
224 self.check_suite("import sys, math")
225 self.check_suite("import sys as system, math")
226 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000227
Mark Dickinson75b44b32010-07-04 16:47:56 +0000228 def test_relative_imports(self):
229 self.check_suite("from . import name")
230 self.check_suite("from .. import name")
231 self.check_suite("from .pkg import name")
232 self.check_suite("from ..pkg import name")
233
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000234 def test_pep263(self):
235 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
236 "pass\n")
237
238 def test_assert(self):
239 self.check_suite("assert alo < ahi and blo < bhi\n")
240
Benjamin Peterson9dfe6a82008-11-24 04:09:03 +0000241 def test_with(self):
242 self.check_suite("with open('x'): pass\n")
243 self.check_suite("with open('x') as f: pass\n")
Georg Brandl944f6842009-05-25 21:02:56 +0000244 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson9dfe6a82008-11-24 04:09:03 +0000245
Georg Brandlfe879e82008-12-05 12:09:41 +0000246 def test_try_stmt(self):
247 self.check_suite("try: pass\nexcept: pass\n")
248 self.check_suite("try: pass\nfinally: pass\n")
249 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
250 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
251 "finally: pass\n")
252 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
253 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
254 "finally: pass\n")
255
Mark Dickinson070f0ab2010-06-30 16:27:57 +0000256 def test_except_clause(self):
257 self.check_suite("try: pass\nexcept: pass\n")
258 self.check_suite("try: pass\nexcept A: pass\n")
259 self.check_suite("try: pass\nexcept A, e: pass\n")
260 self.check_suite("try: pass\nexcept A as e: pass\n")
261
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000262 def test_position(self):
263 # An absolutely minimal test of position information. Better
264 # tests would be a big project.
Benjamin Petersona4a04d12009-12-06 21:24:30 +0000265 code = "def f(x):\n return x + 1"
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000266 st1 = parser.suite(code)
267 st2 = st1.totuple(line_info=1, col_info=1)
268
269 def walk(tree):
270 node_type = tree[0]
271 next = tree[1]
272 if isinstance(next, tuple):
273 for elt in tree[1:]:
274 for x in walk(elt):
275 yield x
276 else:
277 yield tree
Tim Peters147f9ae2006-08-25 22:05:39 +0000278
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000279 terminals = list(walk(st2))
280 self.assertEqual([
281 (1, 'def', 1, 0),
282 (1, 'f', 1, 4),
283 (7, '(', 1, 5),
284 (1, 'x', 1, 6),
285 (8, ')', 1, 7),
286 (11, ':', 1, 8),
287 (4, '', 1, 9),
288 (5, '', 2, -1),
289 (1, 'return', 2, 4),
290 (1, 'x', 2, 11),
291 (14, '+', 2, 13),
292 (2, '1', 2, 15),
293 (4, '', 2, 16),
Benjamin Petersona4a04d12009-12-06 21:24:30 +0000294 (6, '', 2, -1),
295 (4, '', 2, -1),
296 (0, '', 2, -1)],
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000297 terminals)
298
299
Fred Drake79ca79d2000-08-21 22:30:53 +0000300#
301# Second, we take *invalid* trees and make sure we get ParserError
302# rejections for them.
303#
304
Fred Drake58422e52001-06-04 03:56:24 +0000305class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000306
Fred Drake58422e52001-06-04 03:56:24 +0000307 def check_bad_tree(self, tree, label):
308 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000309 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000310 except parser.ParserError:
311 pass
312 else:
313 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000314
Fred Drake58422e52001-06-04 03:56:24 +0000315 def test_junk(self):
316 # not even remotely valid:
317 self.check_bad_tree((1, 2, 3), "<junk>")
318
Serhiy Storchaka2a1bf062017-04-20 00:48:57 +0300319 def test_illegal_terminal(self):
320 tree = \
321 (257,
322 (267,
323 (268,
324 (269,
325 (274,
326 (1,))),
327 (4, ''))),
328 (4, ''),
329 (0, ''))
330 self.check_bad_tree(tree, "too small items in terminal node")
331 tree = \
332 (257,
333 (267,
334 (268,
335 (269,
336 (274,
337 (1, u'pass'))),
338 (4, ''))),
339 (4, ''),
340 (0, ''))
341 self.check_bad_tree(tree, "non-string second item in terminal node")
342 tree = \
343 (257,
344 (267,
345 (268,
346 (269,
347 (274,
348 (1, 'pass', '0', 0))),
349 (4, ''))),
350 (4, ''),
351 (0, ''))
352 self.check_bad_tree(tree, "non-integer third item in terminal node")
353 tree = \
354 (257,
355 (267,
356 (268,
357 (269,
358 (274,
359 (1, 'pass', 0, 0))),
360 (4, ''))),
361 (4, ''),
362 (0, ''))
363 self.check_bad_tree(tree, "too many items in terminal node")
364
Fred Drakecf580c72001-07-17 03:01:29 +0000365 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000366 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000367 tree = \
368 (257,
369 (264,
370 (285,
371 (259,
372 (1, 'def'),
373 (1, 'f'),
374 (260, (7, '('), (8, ')')),
375 (11, ':'),
376 (291,
377 (4, ''),
378 (5, ''),
379 (264,
380 (265,
381 (266,
382 (272,
383 (275,
384 (1, 'return'),
385 (313,
386 (292,
387 (293,
388 (294,
389 (295,
390 (297,
391 (298,
392 (299,
393 (300,
394 (301,
395 (302, (303, (304, (305, (2, '1')))))))))))))))))),
396 (264,
397 (265,
398 (266,
399 (272,
400 (276,
401 (1, 'yield'),
402 (313,
403 (292,
404 (293,
405 (294,
406 (295,
407 (297,
408 (298,
409 (299,
410 (300,
411 (301,
412 (302,
413 (303, (304, (305, (2, '1')))))))))))))))))),
414 (4, ''))),
415 (6, ''))))),
416 (4, ''),
417 (0, ''))))
418 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
419
420 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000421 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000422 tree = \
423 (257,
424 (264,
425 (265,
426 (266,
427 (278,
428 (1, 'from'),
429 (281, (1, '__future__')),
430 (1, 'import'),
431 (279, (1, 'generators')))),
432 (4, ''))),
433 (264,
434 (285,
435 (259,
436 (1, 'def'),
437 (1, 'f'),
438 (260, (7, '('), (8, ')')),
439 (11, ':'),
440 (291,
441 (4, ''),
442 (5, ''),
443 (264,
444 (265,
445 (266,
446 (272,
447 (275,
448 (1, 'return'),
449 (313,
450 (292,
451 (293,
452 (294,
453 (295,
454 (297,
455 (298,
456 (299,
457 (300,
458 (301,
459 (302, (303, (304, (305, (2, '1')))))))))))))))))),
460 (264,
461 (265,
462 (266,
463 (272,
464 (276,
465 (1, 'yield'),
466 (313,
467 (292,
468 (293,
469 (294,
470 (295,
471 (297,
472 (298,
473 (299,
474 (300,
475 (301,
476 (302,
477 (303, (304, (305, (2, '1')))))))))))))))))),
478 (4, ''))),
479 (6, ''))))),
480 (4, ''),
481 (0, ''))))
482 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
483
Fred Drake58422e52001-06-04 03:56:24 +0000484 def test_print_chevron_comma(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000485 # Illegal input: print >>fp,
Fred Drake58422e52001-06-04 03:56:24 +0000486 tree = \
487 (257,
488 (264,
489 (265,
490 (266,
491 (268,
492 (1, 'print'),
493 (35, '>>'),
494 (290,
495 (291,
496 (292,
497 (293,
498 (295,
499 (296,
500 (297,
501 (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))),
502 (12, ','))),
503 (4, ''))),
504 (0, ''))
505 self.check_bad_tree(tree, "print >>fp,")
506
507 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000508 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000509 tree = \
510 (258,
511 (311,
512 (290,
513 (291,
514 (292,
515 (293,
516 (295,
517 (296,
518 (297,
519 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
520 (12, ','),
521 (12, ','),
522 (290,
523 (291,
524 (292,
525 (293,
526 (295,
527 (296,
528 (297,
529 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
530 (4, ''),
531 (0, ''))
532 self.check_bad_tree(tree, "a,,c")
533
534 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000535 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000536 tree = \
537 (257,
538 (264,
539 (265,
540 (266,
541 (267,
542 (312,
543 (291,
544 (292,
545 (293,
546 (294,
547 (296,
548 (297,
549 (298,
550 (299,
551 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
552 (268, (37, '$=')),
553 (312,
554 (291,
555 (292,
556 (293,
557 (294,
558 (296,
559 (297,
560 (298,
561 (299,
562 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
563 (4, ''))),
564 (0, ''))
565 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000566
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000567 def test_malformed_global(self):
568 #doesn't have global keyword in ast
569 tree = (257,
570 (264,
571 (265,
572 (266,
573 (282, (1, 'foo'))), (4, ''))),
574 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000575 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000576 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000577
Mark Dickinson75b44b32010-07-04 16:47:56 +0000578 def test_missing_import_source(self):
579 # from import a
580 tree = \
581 (257,
582 (267,
583 (268,
584 (269,
585 (281,
586 (283, (1, 'from'), (1, 'import'),
587 (286, (284, (1, 'fred')))))),
588 (4, ''))),
589 (4, ''), (0, ''))
590 self.check_bad_tree(tree, "from import a")
591
Serhiy Storchaka2a1bf062017-04-20 00:48:57 +0300592 def test_illegal_encoding(self):
593 # Illegal encoding declaration
594 tree = \
595 (339,
596 (257, (0, '')))
597 self.check_bad_tree(tree, "missed encoding")
598 tree = \
599 (339,
600 (257, (0, '')),
601 u'iso-8859-1')
602 self.check_bad_tree(tree, "non-string encoding")
603
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000604
605class CompileTestCase(unittest.TestCase):
606
607 # These tests are very minimal. :-(
608
609 def test_compile_expr(self):
610 st = parser.expr('2 + 3')
611 code = parser.compilest(st)
Ezio Melotti2623a372010-11-21 13:34:58 +0000612 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
614 def test_compile_suite(self):
615 st = parser.suite('x = 2; y = x + 3')
616 code = parser.compilest(st)
617 globs = {}
618 exec code in globs
Ezio Melotti2623a372010-11-21 13:34:58 +0000619 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000620
621 def test_compile_error(self):
622 st = parser.suite('1 = 3 + 4')
623 self.assertRaises(SyntaxError, parser.compilest, st)
624
Guido van Rossumb6ac23c2007-07-18 17:19:14 +0000625 def test_compile_badunicode(self):
626 st = parser.suite('a = u"\U12345678"')
627 self.assertRaises(SyntaxError, parser.compilest, st)
628 st = parser.suite('a = u"\u1"')
629 self.assertRaises(SyntaxError, parser.compilest, st)
630
Mark Dickinsonb1cc6aa2012-11-25 17:11:33 +0000631 def test_issue_9011(self):
632 # Issue 9011: compilation of an unary minus expression changed
633 # the meaning of the ST, so that a second compilation produced
634 # incorrect results.
635 st = parser.expr('-3')
636 code1 = parser.compilest(st)
637 self.assertEqual(eval(code1), -3)
638 code2 = parser.compilest(st)
639 self.assertEqual(eval(code2), -3)
640
641
Facundo Batistafc2d0102008-02-23 12:01:13 +0000642class ParserStackLimitTestCase(unittest.TestCase):
Ezio Melottida9eeae2013-03-09 22:17:33 +0200643 """try to push the parser to/over its limits.
Facundo Batistafc2d0102008-02-23 12:01:13 +0000644 see http://bugs.python.org/issue1881 for a discussion
645 """
646 def _nested_expression(self, level):
647 return "["*level+"]"*level
648
649 def test_deeply_nested_list(self):
650 e = self._nested_expression(99)
651 st = parser.expr(e)
652 st.compile()
653
654 def test_trigger_memory_error(self):
655 e = self._nested_expression(100)
Ezio Melottida9eeae2013-03-09 22:17:33 +0200656 rc, out, err = assert_python_failure('-c', e)
657 # parsing the expression will result in an error message
658 # followed by a MemoryError (see #11963)
Ezio Melottic5267042013-03-10 03:25:45 +0200659 self.assertIn(b's_push: parser stack overflow', err)
660 self.assertIn(b'MemoryError', err)
Facundo Batistafc2d0102008-02-23 12:01:13 +0000661
Jesus Cea3e3192d2012-08-03 14:25:53 +0200662class STObjectTestCase(unittest.TestCase):
663 """Test operations on ST objects themselves"""
664
Serhiy Storchaka2a1bf062017-04-20 00:48:57 +0300665 def test_copy_pickle(self):
666 sts = [
667 parser.expr('2 + 3'),
668 parser.suite('x = 2; y = x + 3'),
669 parser.expr('list(x**3 for x in range(20))')
670 ]
671 for st in sts:
672 st_copy = copy.copy(st)
673 self.assertEqual(st_copy.totuple(), st.totuple())
674 st_copy = copy.deepcopy(st)
675 self.assertEqual(st_copy.totuple(), st.totuple())
676 for proto in range(pickle.HIGHEST_PROTOCOL+1):
677 st_copy = pickle.loads(pickle.dumps(st, proto))
678 self.assertEqual(st_copy.totuple(), st.totuple())
679
Jesus Cea3e3192d2012-08-03 14:25:53 +0200680 check_sizeof = support.check_sizeof
681
682 @support.cpython_only
683 def test_sizeof(self):
684 def XXXROUNDUP(n):
685 if n <= 1:
686 return n
687 if n <= 128:
688 return (n + 3) & ~3
689 return 1 << (n - 1).bit_length()
690
691 basesize = support.calcobjsize('Pii')
692 nodesize = struct.calcsize('hP3iP0h')
693 def sizeofchildren(node):
694 if node is None:
695 return 0
696 res = 0
697 hasstr = len(node) > 1 and isinstance(node[-1], str)
698 if hasstr:
699 res += len(node[-1]) + 1
700 children = node[1:-1] if hasstr else node[1:]
701 if children:
702 res += XXXROUNDUP(len(children)) * nodesize
Jesus Cea3e3192d2012-08-03 14:25:53 +0200703 for child in children:
704 res += sizeofchildren(child)
705 return res
706
707 def check_st_sizeof(st):
708 self.check_sizeof(st, basesize + nodesize +
709 sizeofchildren(st.totuple()))
710
711 check_st_sizeof(parser.expr('2 + 3'))
712 check_st_sizeof(parser.expr('2 + 3 + 4'))
713 check_st_sizeof(parser.suite('x = 2 + 3'))
714 check_st_sizeof(parser.suite(''))
715 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
716 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
717
718
719 # XXX tests for pickling and unpickling of ST objects should go here
720
Fred Drake2e2be372001-09-20 21:33:42 +0000721def test_main():
Jesus Cea3e3192d2012-08-03 14:25:53 +0200722 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000723 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724 IllegalSyntaxTestCase,
725 CompileTestCase,
Facundo Batistafc2d0102008-02-23 12:01:13 +0000726 ParserStackLimitTestCase,
Jesus Cea3e3192d2012-08-03 14:25:53 +0200727 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000728 )
Fred Drake2e2be372001-09-20 21:33:42 +0000729
730
731if __name__ == "__main__":
732 test_main()