Skip to content

Commit

Permalink
bpo-44368: Improve syntax errors with invalid as pattern targets (GH-…
Browse files Browse the repository at this point in the history
  • Loading branch information
pablogsal committed Jun 10, 2021
1 parent e7b4644 commit 0507303
Show file tree
Hide file tree
Showing 4 changed files with 332 additions and 213 deletions.
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

0 comments on commit 0507303

Please sign in to comment.