Skip to content

Commit 06361ad

Browse files
committed
gh-138857: Improve error message for case outside of match
1 parent 805e336 commit 06361ad

4 files changed

Lines changed: 60 additions & 0 deletions

File tree

Grammar/python.gram

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1476,6 +1476,10 @@ invalid_match_stmt:
14761476
| "match" subject_expr NEWLINE { CHECK_VERSION(void*, 10, "Pattern matching is", RAISE_SYNTAX_ERROR("expected ':'") ) }
14771477
| a="match" subject=subject_expr ':' NEWLINE !INDENT {
14781478
RAISE_INDENTATION_ERROR("expected an indented block after 'match' statement on line %d", a->lineno) }
1479+
| a="case" patterns guard? b=':' block {
1480+
RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1481+
a, b,
1482+
"case statement must be inside match statement") }
14791483
invalid_case_block:
14801484
| "case" patterns guard? NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
14811485
| a="case" patterns guard? ':' NEWLINE !INDENT {

Lib/test/test_syntax.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,22 @@
382382
Traceback (most recent call last):
383383
SyntaxError: invalid syntax
384384
385+
>>> case 1: ...
386+
Traceback (most recent call last):
387+
SyntaxError: case statement must be inside match statement
388+
389+
>>> case 1 | 2: ...
390+
Traceback (most recent call last):
391+
SyntaxError: case statement must be inside match statement
392+
393+
>>> case klass(attr=1) | {}: ...
394+
Traceback (most recent call last):
395+
SyntaxError: case statement must be inside match statement
396+
397+
>>> case [] if x > 1: ...
398+
Traceback (most recent call last):
399+
SyntaxError: case statement must be inside match statement
400+
385401
# But prefixes of soft keywords should
386402
# still raise specialized errors
387403
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve :exc:`SyntaxError` message for :keyword:`case` placed outside
2+
:keyword:`match` body.

Parser/parser.c

Lines changed: 38 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)