Debian Codegraph @

pypy/interpreter/pyparser/test/test_pyparse.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 import pytest
3 from pypy.interpreter.pyparser import pyparse, pytokenizer
4 from pypy.interpreter.pyparser.error import SyntaxError, IndentationError, TabError
5 from pypy.interpreter.astcompiler import consts
6
7
8 class BaseTestPythonParser:
9 spaceconfig = {}
10
11 def setup_class(self):
12 self.parser = pyparse.PegParser(self.space)
13
14 def parse(self, source, mode="exec", info=None, flags=0):
15 if info is None:
16 info = pyparse.CompileInfo("<test>", mode, flags=flags)
17 return self.parser.parse_source(source, info)
18
19 class TestPythonParser(BaseTestPythonParser):
20 def test_encoding(self):
21 info = pyparse.CompileInfo("<test>", "exec")
22 self.parse("""# coding: latin-1
23 stuff = "nothing"
24 """, info=info)
25 assert info.encoding == "iso-8859-1"
26 sentence = u"u'Die Männer ärgern sich!'"
27 input = (u"# coding: utf-7\nstuff = %s" % (sentence,)).encode("utf-7")
28 self.parse(input, info=info)
29 assert info.encoding == "utf-7"
30 input = "# coding: iso-8859-15\nx"
31 self.parse(input, info=info)
32 assert info.encoding == "iso-8859-15"
33 input = "\xEF\xBB\xBF# coding: utf-8\nx"
34 self.parse(input, info=info)
35 assert info.encoding == "utf-8"
36 input = "\xEF\xBB\xBF# coding: latin-1\nx"
37 exc = pytest.raises(SyntaxError, self.parse, input).value
38 assert exc.msg == "UTF-8 BOM with latin-1 coding cookie"
39 input = "\xEF\xBB\xBF# coding: UtF-8-yadda-YADDA\nx"
40 self.parse(input) # this does not raise
41 input = "# coding: not-here"
42 exc = pytest.raises(SyntaxError, self.parse, input).value
43 assert exc.msg == "Unknown encoding: not-here"
44 input = u"# coding: ascii\n\xe2".encode('utf-8')
45 exc = pytest.raises(SyntaxError, self.parse, input).value
46 assert exc.msg == ("'ascii' codec can't decode byte 0xc3 "
47 "in position 16: ordinal not in range(128)")
48
49 def test_with_and_as(self):
50 pytest.raises(SyntaxError, self.parse, "with = 23")
51 pytest.raises(SyntaxError, self.parse, "as = 2")
52
53 def test_dont_imply_dedent(self):
54 info = pyparse.CompileInfo("<test>", "single",
55 consts.PyCF_DONT_IMPLY_DEDENT)
56 self.parse('if 1:\n x\n', info=info)
57 self.parse('x = 5 ', info=info)
58 pytest.raises(SyntaxError, self.parse, "if 1:\n x", info=info)
59 excinfo = pytest.raises(SyntaxError, self.parse, "if 1:\n x x\n", info=info)
60
61 def test_encoding_pep3120(self):
62 info = pyparse.CompileInfo("<test>", "exec")
63 tree = self.parse("""foo = '日本'""", info=info)
64 assert info.encoding == 'utf-8'
65
66 def test_unicode_identifier(self):
67 tree = self.parse("a日本 = 32")
68 tree = self.parse("日本 = 32")
69
70 def test_syntax_error(self):
71 parse = self.parse
72 exc = pytest.raises(SyntaxError, parse, "name another for").value
73 assert exc.msg.startswith("invalid syntax")
74 assert exc.lineno == 1
75 assert exc.offset in (1, 6)
76 assert exc.text.startswith("name another for")
77 exc = pytest.raises(SyntaxError, parse, "x = \"blah\n\n\n").value
78 assert exc.msg == "unterminated string literal (detected at line 1)"
79 assert exc.lineno == exc.end_lineno == 1
80 assert exc.offset == 5
81 assert exc.end_offset == 10
82 exc = pytest.raises(SyntaxError, parse, "x = '''\n\n\n").value
83 assert exc.msg.startswith(pytokenizer.TRIPLE_QUOTE_UNTERMINATED_ERROR)
84 assert exc.lineno == 1
85 assert exc.offset == 5
86 assert exc.end_lineno == 3
87 for input in ("())", "(()", "((", "))"):
88 pytest.raises(SyntaxError, parse, input)
89 exc = pytest.raises(SyntaxError, parse, "x = (\n\n(),\n(),").value
90 assert exc.msg == "'(' was never closed"
91 assert exc.lineno == 1
92 assert exc.offset == 5
93 assert exc.end_lineno == 5
94 exc = pytest.raises(SyntaxError, parse, "abc)").value
95 assert exc.msg == "unmatched ')'"
96 assert exc.lineno == 1
97 assert exc.offset == 4
98 exc = pytest.raises(SyntaxError, parse, "\\").value
99 assert exc.msg == "unexpected end of file (EOF) in multi-line statement"
100 assert exc.lineno == 1
101
102 def test_is(self):
103 self.parse("x is y")
104 self.parse("x is not y")
105
106 def test_indentation_error(self):
107 parse = self.parse
108 input = """
109 def f():
110 pass"""
111 exc = pytest.raises(IndentationError, parse, input).value
112 assert exc.msg == "expected an indented block after function definition on line 2"
113 assert exc.lineno == 3
114 assert exc.text.startswith("pass")
115 assert exc.offset == 1
116 input = "hi\n indented"
117 exc = pytest.raises(IndentationError, parse, input).value
118 assert exc.msg == "unexpected indent"
119 input = "def f():\n pass\n next_stmt"
120 exc = pytest.raises(IndentationError, parse, input).value
121 assert exc.msg == "unindent does not match any outer indentation level"
122 assert exc.lineno == 3
123 assert exc.offset == 3
124
125 input = """
126 if 1\
127 > 3:
128 pass"""
129 exc = pytest.raises(IndentationError, parse, input).value
130 assert exc.msg == "expected an indented block after 'if' statement on line 2"
131 assert exc.lineno == 3
132 assert exc.text.startswith("pass")
133 assert exc.offset == 1
134
135 input = """
136 if x > 1:
137 pass
138 elif x < 1:
139 pass"""
140 exc = pytest.raises(IndentationError, parse, input).value
141 assert exc.msg == "expected an indented block after 'elif' statement on line 4"
142 assert exc.lineno == 5
143 assert exc.text.startswith("pass")
144 assert exc.offset == 1
145
146
147 def test_taberror(self):
148 src = """
149 if 1:
150 pass
151 \tpass
152 """
153 exc = pytest.raises(TabError, "self.parse(src)").value
154 assert exc.msg == "inconsistent use of tabs and spaces in indentation"
155 assert exc.lineno == 4
156 assert exc.offset == 5
157 assert exc.text == " \tpass\n"
158
159 def test_mac_newline(self):
160 self.parse("this_is\ra_mac\rfile")
161
162 def test_multiline_string(self):
163 self.parse("''' \n '''")
164 self.parse("r''' \n '''")
165
166 def test_bytes_literal(self):
167 self.parse('b" "')
168 self.parse('br" "')
169 self.parse('b""" """')
170 self.parse("b''' '''")
171 self.parse("br'\\\n'")
172
173 pytest.raises(SyntaxError, self.parse, "b'a\\n")
174
175 def test_new_octal_literal(self):
176 self.parse('0o777')
177 pytest.raises(SyntaxError, self.parse, '0o777L')
178 pytest.raises(SyntaxError, self.parse, "0o778")
179
180 def test_new_binary_literal(self):
181 self.parse('0b1101')
182 pytest.raises(SyntaxError, self.parse, '0b0l')
183 pytest.raises(SyntaxError, self.parse, "0b112")
184
185 def test_print_function(self):
186 self.parse("from __future__ import print_function\nx = print\n")
187
188 def test_revdb_dollar_num(self):
189 assert not self.space.config.translation.reverse_debugger
190 pytest.raises(SyntaxError, self.parse, '$0')
191 pytest.raises(SyntaxError, self.parse, '$0 + 5')
192 pytest.raises(SyntaxError, self.parse,
193 "from __future__ import print_function\nx = ($0, print)")
194
195 def test_py3k_reject_old_binary_literal(self):
196 pytest.raises(SyntaxError, self.parse, '0777')
197
198 def test_py3k_extended_unpacking(self):
199 self.parse('a, *rest, b = 1, 2, 3, 4, 5')
200 self.parse('(a, *rest, b) = 1, 2, 3, 4, 5')
201
202 def test_u_triple_quote(self):
203 self.parse('u""""""')
204 self.parse('U""""""')
205 self.parse("u''''''")
206 self.parse("U''''''")
207
208 def test_bad_single_statement(self):
209 pytest.raises(SyntaxError, self.parse, '1\n2', "single")
210 pytest.raises(SyntaxError, self.parse, 'a = 13\nb = 187', "single")
211 pytest.raises(SyntaxError, self.parse, 'del x\ndel y', "single")
212 pytest.raises(SyntaxError, self.parse, 'f()\ng()', "single")
213 pytest.raises(SyntaxError, self.parse, 'f()\n# blah\nblah()', "single")
214 pytest.raises(SyntaxError, self.parse, 'f()\nxy # blah\nblah()', "single")
215 pytest.raises(SyntaxError, self.parse, 'x = 5 # comment\nx = 6\n', "single")
216
217 def test_null_bytes_rejected(self):
218 # bpo-24022, bpo-25388: null bytes must always raise SyntaxError with
219 # the right message, even when PyCF_ACCEPT_NULL_BYTES is set.
220 for src in [b'0000\x00\n', b'#\x00\n']:
221 for flags in [0, consts.PyCF_ACCEPT_NULL_BYTES]:
222 exc = pytest.raises(SyntaxError, self.parse, src, flags=flags)
223 assert "null bytes" in exc.value.msg
224
225 def test_unpack(self):
226 self.parse('[*{2}, 3, *[4]]')
227 self.parse('{*{2}, 3, *[4]}')
228 self.parse('{**{}, 3:4, **{5:6, 7:8}}')
229 self.parse('f(2, *a, *b, **b, **c, **d)')
230
231 def test_async_await(self):
232 self.parse("async def coro(): await func")
233 self.parse("await x")
234 #Test as var and func name
235 with pytest.raises(SyntaxError):
236 self.parse("async = 1")
237 with pytest.raises(SyntaxError):
238 self.parse("await = 1")
239 with pytest.raises(SyntaxError):
240 self.parse("def async(): pass")
241 #async for
242 self.parse("""async def foo():
243 async for a in b:
244 pass""")
245 self.parse("""def foo():
246 async for a in b:
247 pass""")
248 #async with
249 self.parse("""async def foo():
250 async with a:
251 pass""")
252 self.parse('''def foo():
253 async with a:
254 pass''')
255
256 def test_async_await_hacks(self):
257 def parse(source):
258 return self.parse(source, flags=consts.PyCF_ASYNC_HACKS)
259
260 # legal syntax
261 parse("async def coro(): await func")
262
263 # legal syntax for 3.6<=
264 parse("async = 1")
265 parse("await = 1")
266 parse("def async(): pass")
267 parse("def await(): pass")
268 parse("""async def foo():
269 async for a in b:
270 pass""")
271
272 # illegal syntax for 3.6<=
273 with pytest.raises(SyntaxError):
274 parse("await x")
275 with pytest.raises(SyntaxError):
276 parse("async for a in b: pass")
277 with pytest.raises(SyntaxError):
278 parse("def foo(): async for a in b: pass")
279 with pytest.raises(SyntaxError):
280 parse("def foo(): async for a in b: pass")
281
282 def test_number_underscores(self):
283 VALID_UNDERSCORE_LITERALS = [
284 '0_0_0',
285 '4_2',
286 '1_0000_0000',
287 '0b1001_0100',
288 '0xffff_ffff',
289 '0o5_7_7',
290 '1_00_00.5',
291 '1_00_00.5e5',
292 '1_00_00e5_1',
293 '1e1_0',
294 '.1_4',
295 '.1_4e1',
296 '0b_0',
297 '0x_f',
298 '0o_5',
299 '1_00_00j',
300 '1_00_00.5j',
301 '1_00_00e5_1j',
302 '.1_4j',
303 '(1_2.5+3_3j)',
304 '(.5_6j)',
305 '.2_3',
306 '.2_3e4',
307 '1.2_3',
308 '1.2_3_4',
309 '12.000_400',
310 '1_2.3_4',
311 '1_2.3_4e5_6',
312 ]
313 INVALID_UNDERSCORE_LITERALS = [
314 # Trailing underscores:
315 '0_',
316 '42_',
317 '1.4j_',
318 '0x_',
319 '0b1_',
320 '0xf_',
321 '0o5_',
322 '0 if 1_Else 1',
323 # Underscores in the base selector:
324 '0_b0',
325 '0_xf',
326 '0_o5',
327 # Old-style octal, still disallowed:
328 '0_7',
329 '09_99',
330 # Multiple consecutive underscores:
331 '4_______2',
332 '0.1__4',
333 '0.1__4j',
334 '0b1001__0100',
335 '0xffff__ffff',
336 '0x___',
337 '0o5__77',
338 '1e1__0',
339 '1e1__0j',
340 # Underscore right before a dot:
341 '1_.4',
342 '1_.4j',
343 # Underscore right after a dot:
344 '1._4',
345 '1._4j',
346 '._5',
347 '._5j',
348 # Underscore right after a sign:
349 '1.0e+_1',
350 '1.0e+_1j',
351 # Underscore right before j:
352 '1.4_j',
353 '1.4e5_j',
354 # Underscore right before e:
355 '1_e1',
356 '1.4_e1',
357 '1.4_e1j',
358 # Underscore right after e:
359 '1e_1',
360 '1.4e_1',
361 '1.4e_1j',
362 # Complex cases with parens:
363 '(1+1.5_j_)',
364 '(1+1.5_j)',
365 # Extra underscores around decimal part
366 '._3',
367 '._3e4',
368 '1.2_',
369 '1._3_4',
370 '12._',
371 '1_2._3',
372 ]
373 for x in VALID_UNDERSCORE_LITERALS:
374 tree = self.parse(x)
375 for x in INVALID_UNDERSCORE_LITERALS:
376 print x
377 pytest.raises(SyntaxError, self.parse, "x = %s" % x)
378
379 def test_relaxed_decorators(self):
380 self.parse("@(1 + 2)\ndef f(x): pass") # does not crash
381
382 def test_universal_newlines(self):
383 fmt = 'stuff = """hello%sworld"""'
384 for linefeed in ["\r\n","\r"]:
385 self.parse(fmt % linefeed)
386
387
388 def test_error_forgotten_chars(self):
389 info = pytest.raises(SyntaxError, self.parse, "if 1\n print 4")
390 assert "expected ':'" in info.value.msg
391 assert info.value.lineno == 1
392 info = pytest.raises(SyntaxError, self.parse, "for i in range(10)\n print i")
393 assert "expected ':'" in info.value.msg
394 assert info.value.lineno == 1
395 info = pytest.raises(SyntaxError, self.parse, "class A\n print i")
396 assert "expected ':'" in info.value.msg
397 assert info.value.lineno == 1
398 info = pytest.raises(SyntaxError, self.parse, "with a as b\n print i")
399 assert "expected ':'" in info.value.msg
400 assert info.value.lineno == 1
401 info = pytest.raises(SyntaxError, self.parse, "try:\n 1\nexcept\n pass")
402 assert "expected ':'" in info.value.msg
403 assert info.value.lineno == 3
404 info = pytest.raises(SyntaxError, self.parse, "try:\n 1\nexcept IndexError as e\n pass")
405 assert "expected ':'" in info.value.msg
406 assert info.value.lineno == 3
407 info = pytest.raises(SyntaxError, self.parse, "match x\n case _:\n pass")
408 assert "expected ':'" in info.value.msg
409 assert info.value.lineno == 1
410
411 # the following should *not* contain expected ':'
412 info = pytest.raises(SyntaxError, self.parse, "class A&B\n print i")
413 assert "expected ':'" not in info.value.msg # this must point to the 'range 10'
414 info = pytest.raises(SyntaxError, self.parse, "for i in range 10\n print i")
415 assert "expected ':'" not in info.value.msg # this must point to the 'range 10'
416
417 def test_positional_only_args(self):
418 self.parse("def f(a, /): pass")
419
420 def test_forgot_comma_wrong(self):
421 info = pytest.raises(SyntaxError, self.parse, "with block ad something\n print i")
422 assert "invalid syntax" == info.value.msg
423
424 def test_error_print_without_parens(self):
425 info = pytest.raises(SyntaxError, self.parse, "print 1")
426 assert "Missing parentheses in call to 'print'" in info.value.msg
427 info = pytest.raises(SyntaxError, self.parse, "print 1)")
428 assert "unmatched" in info.value.msg
429
430 def test_end_location_unparenthized_genexp(self):
431 info = pytest.raises(SyntaxError, self.parse, "f(x for x in range(10), 1)")
432 assert "Generator expression must be parenthesized" in info.value.msg
433 assert info.value.end_offset == 23
434 info = pytest.raises(SyntaxError, self.parse, "f(x for x in range(10) if x != 2, 1)")
435 assert "Generator expression must be parenthesized" in info.value.msg
436 assert info.value.end_offset == 33
437 info = pytest.raises(SyntaxError, self.parse, "f(1, x for x in range(10) if x != 2, 1)")
438 assert "Generator expression must be parenthesized" in info.value.msg
439 assert info.value.end_offset == 36
440
441 def test_invalid_default(self):
442 info = pytest.raises(SyntaxError, self.parse, "def f(x=): return 1")
443 assert "expected default value expression" in info.value.msg
444 assert info.value.offset == 8
445 assert info.value.end_offset == 9
446
447 def test_invalid_star(self):
448 info = pytest.raises(SyntaxError, self.parse, "f(**kw, *)")
449 assert "Invalid star expression" in info.value.msg
450 assert info.value.offset == 10
451
452 def test_null_bytes_in_source(self):
453 info = pytest.raises(SyntaxError, self.parse, "x = 0\x00\n")
454 assert "source code cannot contain null bytes" in info.value.msg
455
456 def test_null_bytes_in_comment(self):
457 info = pytest.raises(SyntaxError, self.parse, "#\x00\n")
458 assert "source code cannot contain null bytes" in info.value.msg
459
460 def test_null_bytes_lineno_and_text(self):
461 # Error should report the line containing the null byte, truncated at it
462 info = pytest.raises(SyntaxError, self.parse, "x = '\x00' rest\n")
463 assert info.value.lineno == 1
464 assert info.value.text == "x = '\n"
465
466 def test_null_bytes_multiline_lineno_and_text(self):
467 info = pytest.raises(SyntaxError, self.parse, "\n'''\nmultilinestring\x00\n'''")
468 assert info.value.lineno == 3
469 assert info.value.text == "multilinestring\n"
470
471
472 class TestPythonParserRevDB(TestPythonParser):
473 spaceconfig = {"translation.reverse_debugger": True}
474
475 def setup_class(self):
476 self.parser = pyparse.PegParser(self.space)
477
478 def test_revdb_dollar_num(self):
479 self.parse('$0')
480 self.parse('$5')
481 self.parse('$42')
482 self.parse('2+$42.attrname')
483 self.parse("from __future__ import print_function\nx = ($0, print)")
484 pytest.raises(SyntaxError, self.parse, '$')
485 pytest.raises(SyntaxError, self.parse, '$a')
486 pytest.raises(SyntaxError, self.parse, '$.5')
487
488
489 class TestPythonPegParser(BaseTestPythonParser):
490 spaceconfig = {}
491
492 def setup_class(self):
493 self.parser = pyparse.PegParser(self.space)
494
495 def test_crash_with(self):
496 # used to crash
497 pytest.raises(SyntaxError, self.parse,
498 "async with a:\n pass", "single",
499 flags=consts.PyCF_DONT_IMPLY_DEDENT | consts.PyCF_ALLOW_TOP_LEVEL_AWAIT)
500
501 def test_crash_eval_empty(self):
502 # used to crash
503 pytest.raises(SyntaxError, self.parse,
504 '', 'eval', flags=consts.PyCF_DONT_IMPLY_DEDENT)
505
506
507 def test_dont_imply_dedent_ignored_on_exec(self):
508 self.parse(
509 "if 1: \n pass", "exec",
510 flags=consts.PyCF_DONT_IMPLY_DEDENT)
511
512 def test_pattern_matching_experiment(self):
513 self.parse("""match x:
514 case 1:
515 print('hello')""")
516
517 def test_nonparen_genexp_in_call(self):
518 with pytest.raises(SyntaxError) as info:
519 self.parse("""\
520 f(x for x in l)
521 if 1:
522 pass
523 """)
524 assert info.value.msg == "expected an indented block after 'if' statement on line 2"
525 with pytest.raises(SyntaxError) as info:
526 self.parse("""f(1, x for x in y for z in a if
527
528 b)""")
529 assert info.value.msg == 'Generator expression must be parenthesized'
530 assert info.value.lineno == 1
531 assert info.value.offset == 6
532 assert info.value.end_lineno == 3
533 assert info.value.end_offset == 5
534
535
536 def test_end_positions(self):
537 # this is really an AST test
538 ast = self.parse("45 * a", "eval")
539 assert ast.body.end_col_offset == 6
540
541 def test_match_deeply_nested(self):
542 self.parse("""
543 match x:
544 case [[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]:
545 pass
546 """)
547
548 def test_except_star(self):
549 self.parse("""
550 try:
551 f(x)
552 except* ValueError:
553 pass""")
554
555 def test_dict_with_equals_suggests_colon(self):
556 # ages = {'Alice'=22} should suggest ':' instead of generic "invalid syntax"
557 exc = pytest.raises(SyntaxError, self.parse, "ages = {'Alice'=22, 'Bob'=23}").value
558 assert exc.msg == "':' expected after dictionary key"
559 assert exc.offset == 16 # points at '='
560
561 def test_except_star_no_type_offset(self):
562 # 'except*:' should report offset pointing at ':' (offset 8), not past it
563 src = "try:\n pass\nexcept*:\n pass"
564 exc = pytest.raises(SyntaxError, self.parse, src).value
565 assert exc.msg == "expected one or more exception types"
566 assert exc.offset == 8 # points at ':'
567
568 class TestIncompleteInput(object):
569 def setup_class(self):
570 self.parser = pyparse.PegParser(self.space)
571
572 def parse(self, source):
573 info = pyparse.CompileInfo("<test>", "single", flags=consts.PyCF_ALLOW_INCOMPLETE_INPUT)
574 return self.parser.parse_source(source, info)
575
576 def check_incomplete(self, inputstring):
577 self.check_error(inputstring, "incomplete input")
578
579 def check_error(self, inputstring, msgfragment='', lineno=-1, offset=-1):
580 with pytest.raises(SyntaxError) as info:
581 self.parse(inputstring)
582 assert msgfragment in info.value.msg
583 return info.value.msg
584
585 def test_simple(self):
586 self.parse("a")
587
588 def test_expression(self):
589 self.check_incomplete("a +")
590
591 def test_if(self):
592 self.check_incomplete("if 1:")
593
594 def test_nested(self):
595 self.check_incomplete("def f(x):\n if 1:")
596
597 def test_real_error(self):
598 msg = self.check_error("a b c de")
599 assert "incomplete source" not in msg
600
601 def test_triplequote(self):
602 msg = self.check_incomplete("a = '''")
603
604 def test_triplequote(self):
605 msg = self.check_incomplete("a = '''\nabc\def")
606
607 def test_augmented_assignment(self):
608 msg = self.check_error("(y for y in (1,2)) += 10")
609 assert "'generator expression'" in msg
610
611 def test_parenthesized(self):
612 self.check_incomplete("(a **")
613
614 def test_ifelse(self):
615 self.check_incomplete("if 9==3:\n pass\nelse:")
616
617 def test_line_continuation(self):
618 self.check_incomplete("a = \\")
619 self.check_incomplete("a = '\\")
620
621 def test_unterminated_single_quote_with_newline_is_invalid(self):
622 self.check_incomplete("a = 'a\\\n")
623 self.check_incomplete("a = 'a\\\r")
624 self.check_incomplete("a = 'a\\\r\n")
625 for eol in ("\n", "\r", "\r\n"):
626 msg = self.check_error("a = 'sta" + eol)
627 assert "unterminated string literal" in msg
628 msg = self.check_error("a = 'a\\ " + eol)
629 assert "unterminated string literal" in msg
630
631 def test_unterminated_single_quote_no_newline_is_invalid(self):
632 msg = self.check_error("a = 'a\\ ")
633 assert "unterminated string literal" in msg
634 msg = self.check_error("a = 'sta")
635 assert "unterminated string literal" in msg
636
637 def test_invalid_with_explicit_newline(self):
638 # An expression that is genuinely invalid (not just incomplete) should
639 # raise "invalid syntax" when it ends with an explicit newline.
640 # CPython behaviour: compile("a @\n", ..., PyCF_ALLOW_INCOMPLETE_INPUT)
641 # raises SyntaxError("invalid syntax"), not "incomplete input".
642 msg = self.check_error("a @\n")
643 assert "invalid syntax" in msg, msg
644
645 def test_if_with_explicit_newline(self):
646 # An 'if' header ending with an explicit newline is still incomplete
647 # (it needs an indented body), so "incomplete input" must be raised.
648 self.check_incomplete("if True:\n")
649 self.check_incomplete("while True:\n")
650 self.check_incomplete("for x in y:\n")
651 self.check_incomplete("def f():\n")
652
653 def test_def_blank_line_unindented_body_is_invalid(self):
654 # "def x():\n\npass\n": a blank line then 'pass' at col 0 means the
655 # function body is empty. This is definitively invalid (not incomplete).
656 msg = self.check_error("def x():\n\npass\n")
657 assert "incomplete input" not in msg, msg
658
659 def test_eval_mode_empty_is_incomplete(self):
660 # compile("\n", "<input>", "eval", PyCF_ALLOW_INCOMPLETE_INPUT|...)
661 # should report incomplete input, not plain "invalid syntax".
662 # codeop._maybe_compile relies on this to return None for empty eval.
663 info = pyparse.CompileInfo("<test>", "eval", flags=consts.PyCF_ALLOW_INCOMPLETE_INPUT)
664 with pytest.raises(SyntaxError) as excinfo:
665 self.parser.parse_source("\n", info)
666 assert "incomplete input" in excinfo.value.msg, excinfo.value.msg
667
668 def test_eval_mode_trailing_operator_is_invalid(self):
669 # "9+\n" (trailing newline, top-level) is invalid, not incomplete.
670 # codeop appends "\n" and retries; PyPy must not say "incomplete input"
671 # or codeop returns None instead of raising SyntaxError.
672 info = pyparse.CompileInfo("<test>", "eval", flags=consts.PyCF_ALLOW_INCOMPLETE_INPUT)
673 with pytest.raises(SyntaxError) as excinfo:
674 self.parser.parse_source("9+\n", info)
675 assert "incomplete input" not in excinfo.value.msg, excinfo.value.msg
676
677 def test_eval_mode_open_paren_with_newline_is_incomplete(self):
678 # "(9+\n" has an unclosed paren so more input can fix it.
679 info = pyparse.CompileInfo("<test>", "eval", flags=consts.PyCF_ALLOW_INCOMPLETE_INPUT)
680 with pytest.raises(SyntaxError) as excinfo:
681 self.parser.parse_source("(9+\n", info)
682 assert "incomplete input" in excinfo.value.msg, excinfo.value.msg
683
684 def test_decorator_without_body_is_incomplete(self):
685 # "@foo" and "@foo\n" are both incomplete: a decorator requires a
686 # function or class definition to follow. codeop._maybe_compile passes
687 # both PyCF_ALLOW_INCOMPLETE_INPUT and PyCF_DONT_IMPLY_DEDENT; both
688 # forms must report "incomplete input" so codeop returns None.
689 both = consts.PyCF_ALLOW_INCOMPLETE_INPUT | consts.PyCF_DONT_IMPLY_DEDENT
690 for src in ("@int", "@int\n"):
691 info = pyparse.CompileInfo("<test>", "single", flags=both)
692 with pytest.raises(SyntaxError) as excinfo:
693 self.parser.parse_source(src, info)
694 assert excinfo.value.msg == "incomplete input", (
695 "src=%r got %r" % (src, excinfo.value.msg))
696