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

GH-103727: Avoid advancing tokenizer too far in f-string mode #103775

Merged
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
10 changes: 4 additions & 6 deletions Lib/test/test_fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -940,15 +940,13 @@ def test_lambda(self):
"f'{lambda :x}'",
"f'{lambda *arg, :x}'",
"f'{1, lambda:x}'",
"f'{lambda x:}'",
"f'{lambda :}'",
])

# but don't emit the paren warning in general cases
self.assertAllRaise(SyntaxError,
"f-string: expecting a valid expression after '{'",
["f'{lambda x:}'",
"f'{lambda :}'",
"f'{+ lambda:None}'",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we removing the other cases?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just moved them up to the check for the specialized error message, since these now raise the "parenthesize your lambdas" error.

])
with self.assertRaisesRegex(SyntaxError, "f-string: expecting a valid expression after '{'"):
eval("f'{+ lambda:None}'")

def test_valid_prefixes(self):
self.assertEqual(F'{1}', "1")
Expand Down
18 changes: 10 additions & 8 deletions Parser/tokenizer.c
Original file line number Diff line number Diff line change
Expand Up @@ -2481,19 +2481,21 @@ tok_get_fstring_mode(struct tok_state *tok, tokenizer_mode* current_tok, struct
// If we start with a bracket, we defer to the normal mode as there is nothing for us to tokenize
// before it.
int start_char = tok_nextc(tok);
int peek1 = tok_nextc(tok);
tok_backup(tok, peek1);
tok_backup(tok, start_char);

if ((start_char == '{' && peek1 != '{') || (start_char == '}' && peek1 != '}')) {
if (start_char == '{') {
if (start_char == '{') {
int peek1 = tok_nextc(tok);
tok_backup(tok, peek1);
tok_backup(tok, start_char);
if (peek1 != '{') {
current_tok->curly_bracket_expr_start_depth++;
if (current_tok->curly_bracket_expr_start_depth >= MAX_EXPR_NESTING) {
return MAKE_TOKEN(syntaxerror(tok, "f-string: expressions nested too deeply"));
}
TOK_GET_MODE(tok)->kind = TOK_REGULAR_MODE;
return tok_get_normal_mode(tok, current_tok, token);
}
TOK_GET_MODE(tok)->kind = TOK_REGULAR_MODE;
return tok_get_normal_mode(tok, current_tok, token);
}
else {
tok_backup(tok, start_char);
}

// Check if we are at the end of the string
Expand Down