gh-109114: Relax the check for invalid lambdas inside f-strings to avoid false positives (#109121)

This commit is contained in:
Pablo Galindo Salgado 2023-09-08 18:00:23 +01:00 committed by GitHub
parent 87a7faf6b6
commit 5bda2f637e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 1697 additions and 1749 deletions

View File

@ -1170,7 +1170,7 @@ invalid_expression:
_PyPegen_check_legacy_stmt(p, a) ? NULL : p->tokens[p->mark-1]->level == 0 ? NULL :
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") }
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
| a='lambda' [lambda_params] b=':' &(FSTRING_MIDDLE | fstring_replacement_field) {
| a='lambda' [lambda_params] b=':' &FSTRING_MIDDLE {
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "f-string: lambda expressions are not allowed without parentheses") }
invalid_named_expression(memo):

View File

@ -1027,6 +1027,10 @@ x = (
"f'{lambda x:}'",
"f'{lambda :}'",
])
# Ensure the detection of invalid lambdas doesn't trigger detection
# for valid lambdas in the second error pass
with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
compile("lambda name_3=f'{name_4}': {name_3}\n1 $ 1", "<string>", "exec")
# but don't emit the paren warning in general cases
with self.assertRaisesRegex(SyntaxError, "f-string: expecting a valid expression after '{'"):

View File

@ -0,0 +1,3 @@
Relax the detection of the error message for invalid lambdas inside
f-strings to not search for arbitrary replacement fields to avoid false
positives. Patch by Pablo Galindo

3437
Parser/parser.c generated

File diff suppressed because it is too large Load Diff