Skip to content

Commit 7873c8c

Browse files
committed
Improve syntax error for non-case statement inside match statement
1 parent 578d726 commit 7873c8c

4 files changed

Lines changed: 61 additions & 1 deletion

File tree

Grammar/python.gram

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1503,6 +1503,7 @@ invalid_case_block:
15031503
| "case" patterns guard? NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
15041504
| a="case" patterns guard? ':' NEWLINE !INDENT {
15051505
RAISE_INDENTATION_ERROR("expected an indented block after 'case' statement on line %d", a->lineno) }
1506+
| !"case" { RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("expected 'case' statement inside 'match' statement") }
15061507
invalid_as_pattern:
15071508
| or_pattern 'as' a="_" { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use '_' as a target") }
15081509
| or_pattern 'as' a=expression {

Lib/test/test_syntax.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@
356356
>>> match x:
357357
... y = 3
358358
Traceback (most recent call last):
359-
SyntaxError: invalid syntax
359+
SyntaxError: expected 'case' statement inside 'match' statement
360360
361361
>>> match x:
362362
... case y:
@@ -3466,6 +3466,38 @@ def test_match_stmt_invalid_as_expr(self):
34663466
end_offset=15 + len("obj.attr"),
34673467
)
34683468

3469+
def test_match_stmt_contains_invalid_stmt(self):
3470+
for stmt in [
3471+
"a",
3472+
"a = 1",
3473+
"if a:",
3474+
"else:",
3475+
"match 1:"
3476+
"pass",
3477+
"return",
3478+
"return 2",
3479+
"raise Exception('a')",
3480+
"del a",
3481+
"yield 2",
3482+
"assert False",
3483+
"break",
3484+
"continue",
3485+
"import",
3486+
"import ast",
3487+
"from",
3488+
"from ast import *"
3489+
]:
3490+
self._check_error(
3491+
textwrap.dedent(
3492+
f"""
3493+
match 1:
3494+
{stmt}
3495+
"""
3496+
),
3497+
errtext="expected 'case' statement inside 'match' statement",
3498+
lineno=3,
3499+
)
3500+
34693501
def test_ifexp_else_stmt(self):
34703502
msg = "expected expression after 'else', but statement is given"
34713503

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Improve :exc:`SyntaxError` message when a statement other than a
2+
:keyword:`case` statement appears inside a :keyword:`match` statement.
3+
Patch by Brian Schubert.

Parser/parser.c

Lines changed: 24 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)