Skip to content

Commit 390459d

Browse files
authored
Allow the parser to avoid nested processing of invalid rules (GH-31252)
1 parent 2cea8c2 commit 390459d

File tree

6 files changed

+1085
-1084
lines changed

6 files changed

+1085
-1084
lines changed

Grammar/python.gram

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,6 +1078,7 @@ invalid_kwarg:
10781078
RAISE_SYNTAX_ERROR_KNOWN_RANGE(
10791079
a, b, "expression cannot contain assignment, perhaps you meant \"==\"?") }
10801080

1081+
# IMPORTANT: Note that the "_without_invalid" suffix causes the rule to not call invalid rules under it
10811082
expression_without_invalid[expr_ty]:
10821083
| a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) }
10831084
| disjunction
@@ -1095,16 +1096,14 @@ invalid_expression:
10951096
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") }
10961097
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
10971098

1098-
invalid_left_assignment_prefixes(memo): list|tuple|genexp|'True'|'None'|'False'
1099-
1100-
invalid_named_expression:
1099+
invalid_named_expression(memo):
11011100
| a=expression ':=' expression {
11021101
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
11031102
a, "cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) }
11041103
| a=NAME '=' b=bitwise_or !('='|':=') {
1105-
p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?") }
1106-
| !invalid_left_assignment_prefixes a=bitwise_or b='=' bitwise_or !('='|':=') {
1107-
p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot assign to %s here. Maybe you meant '==' instead of '='?",
1104+
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?") }
1105+
| !(list|tuple|genexp|'True'|'None'|'False') a=bitwise_or b='=' bitwise_or !('='|':=') {
1106+
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot assign to %s here. Maybe you meant '==' instead of '='?",
11081107
_PyPegen_get_expr_name(a)) }
11091108

11101109
invalid_assignment:

Lib/test/test_exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ def testSyntaxErrorOffset(self):
231231
check('a = « hello » « world »', 1, 5)
232232
check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
233233
check('[file for\n str(file) in []]', 2, 2)
234-
check("ages = {'Alice'=22, 'Bob'=23}", 1, 16)
234+
check("ages = {'Alice'=22, 'Bob'=23}", 1, 9)
235235
check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19)
236236
check("[a b c d e f]", 1, 2)
237237
check("for x yfff:", 1, 7)

0 commit comments

Comments
 (0)