Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-44368: Improve syntax errors with invalid as pattern targets #26632

Merged
merged 1 commit into from
Jun 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ pattern[pattern_ty]:
as_pattern[pattern_ty]:
| pattern=or_pattern 'as' target=pattern_capture_target {
_PyAST_MatchAs(pattern, target->v.Name.id, EXTRA) }
| invalid_as_pattern
or_pattern[pattern_ty]:
| patterns[asdl_pattern_seq*]='|'.closed_pattern+ {
asdl_seq_LEN(patterns) == 1 ? asdl_seq_GET(patterns, 0) : _PyAST_MatchOr(patterns, EXTRA) }
Expand Down Expand Up @@ -974,6 +975,9 @@ invalid_case_block:
| "case" patterns guard? !':' { RAISE_SYNTAX_ERROR("expected ':'") }
| a="case" patterns guard? ':' NEWLINE !INDENT {
RAISE_INDENTATION_ERROR("expected an indented block after 'case' statement on line %d", a->lineno) }
invalid_as_pattern:
| or_pattern 'as' a="_" { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use '_' as a target") }
| or_pattern 'as' !NAME a=expression { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "invalid pattern target") }
invalid_if_stmt:
| 'if' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
| a='if' a=named_expression ':' NEWLINE !INDENT {
Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -1226,6 +1226,20 @@
>>> import ä £
Traceback (most recent call last):
SyntaxError: invalid character '£' (U+00A3)

Invalid pattern matching constructs:

>>> match ...:
... case 42 as _:
... ...
Traceback (most recent call last):
SyntaxError: cannot use '_' as a target

>>> match ...:
... case 42 as 1+2+4:
... ...
Traceback (most recent call last):
SyntaxError: invalid pattern target
"""

import re
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve syntax errors for invalid "as" targets. Patch by Pablo Galindo
Loading