Skip to content

Commit cb157a1

Browse files
authored
GH-103727: Avoid advancing tokenizer too far in f-string mode (GH-103775)
1 parent ab25c7e commit cb157a1

File tree

2 files changed

+14
-14
lines changed

2 files changed

+14
-14
lines changed

Lib/test/test_fstring.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -940,15 +940,13 @@ def test_lambda(self):
940940
"f'{lambda :x}'",
941941
"f'{lambda *arg, :x}'",
942942
"f'{1, lambda:x}'",
943+
"f'{lambda x:}'",
944+
"f'{lambda :}'",
943945
])
944946

945947
# but don't emit the paren warning in general cases
946-
self.assertAllRaise(SyntaxError,
947-
"f-string: expecting a valid expression after '{'",
948-
["f'{lambda x:}'",
949-
"f'{lambda :}'",
950-
"f'{+ lambda:None}'",
951-
])
948+
with self.assertRaisesRegex(SyntaxError, "f-string: expecting a valid expression after '{'"):
949+
eval("f'{+ lambda:None}'")
952950

953951
def test_valid_prefixes(self):
954952
self.assertEqual(F'{1}', "1")

Parser/tokenizer.c

+10-8
Original file line numberDiff line numberDiff line change
@@ -2481,19 +2481,21 @@ tok_get_fstring_mode(struct tok_state *tok, tokenizer_mode* current_tok, struct
24812481
// If we start with a bracket, we defer to the normal mode as there is nothing for us to tokenize
24822482
// before it.
24832483
int start_char = tok_nextc(tok);
2484-
int peek1 = tok_nextc(tok);
2485-
tok_backup(tok, peek1);
2486-
tok_backup(tok, start_char);
2487-
2488-
if ((start_char == '{' && peek1 != '{') || (start_char == '}' && peek1 != '}')) {
2489-
if (start_char == '{') {
2484+
if (start_char == '{') {
2485+
int peek1 = tok_nextc(tok);
2486+
tok_backup(tok, peek1);
2487+
tok_backup(tok, start_char);
2488+
if (peek1 != '{') {
24902489
current_tok->curly_bracket_expr_start_depth++;
24912490
if (current_tok->curly_bracket_expr_start_depth >= MAX_EXPR_NESTING) {
24922491
return MAKE_TOKEN(syntaxerror(tok, "f-string: expressions nested too deeply"));
24932492
}
2493+
TOK_GET_MODE(tok)->kind = TOK_REGULAR_MODE;
2494+
return tok_get_normal_mode(tok, current_tok, token);
24942495
}
2495-
TOK_GET_MODE(tok)->kind = TOK_REGULAR_MODE;
2496-
return tok_get_normal_mode(tok, current_tok, token);
2496+
}
2497+
else {
2498+
tok_backup(tok, start_char);
24972499
}
24982500

24992501
// Check if we are at the end of the string

0 commit comments

Comments
 (0)