Skip to content

Commit 6efa468

Browse files
committed
bpo-30858: Improve error location for expressions with assignments
1 parent 550e467 commit 6efa468

4 files changed

Lines changed: 14 additions & 5 deletions

File tree

Grammar/python.gram

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -646,9 +646,9 @@ invalid_arguments:
646646
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "Generator expression must be parenthesized") }
647647
| a=args ',' args { _PyPegen_arguments_parsing_error(p, a) }
648648
invalid_kwarg:
649-
| a=expression '=' {
649+
| a=expression b='=' {
650650
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
651-
a, "expression cannot contain assignment, perhaps you meant \"==\"?") }
651+
b, "expression cannot contain assignment, perhaps you meant \"==\"?") }
652652
invalid_named_expression:
653653
| a=expression ':=' expression {
654654
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(

Lib/test/test_syntax.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -802,6 +802,13 @@ def _check_error(self, code, errtext,
802802
else:
803803
self.fail("compile() did not raise SyntaxError")
804804

805+
def test_expression_with_assignment(self):
806+
self._check_error(
807+
"print(end1 + end2 = ' ')",
808+
'expression cannot contain assignment, perhaps you meant "=="?',
809+
offset=19
810+
)
811+
805812
def test_curly_brace_after_primary_raises_immediately(self):
806813
self._check_error("f{", "invalid syntax", mode="single")
807814

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve error location in expressions that contain assignments. Patch by
2+
Pablo Galindo and Lysandros Nikolaou.

Parser/parser.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14562,16 +14562,16 @@ invalid_kwarg_rule(Parser *p)
1456214562
return NULL;
1456314563
}
1456414564
D(fprintf(stderr, "%*c> invalid_kwarg[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression '='"));
14565-
Token * _literal;
1456614565
expr_ty a;
14566+
Token * b;
1456714567
if (
1456814568
(a = expression_rule(p)) // expression
1456914569
&&
14570-
(_literal = _PyPegen_expect_token(p, 22)) // token='='
14570+
(b = _PyPegen_expect_token(p, 22)) // token='='
1457114571
)
1457214572
{
1457314573
D(fprintf(stderr, "%*c+ invalid_kwarg[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression '='"));
14574-
_res = RAISE_SYNTAX_ERROR_KNOWN_LOCATION ( a , "expression cannot contain assignment, perhaps you meant \"==\"?" );
14574+
_res = RAISE_SYNTAX_ERROR_KNOWN_LOCATION ( b , "expression cannot contain assignment, perhaps you meant \"==\"?" );
1457514575
if (_res == NULL && PyErr_Occurred()) {
1457614576
p->error_indicator = 1;
1457714577
D(p->level--);

0 commit comments

Comments
 (0)