Skip to content
Open
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: 10 additions & 0 deletions Lib/test/test_fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,16 @@ def test_unclosed_multiline_replacement_field(self):
f"{prefix[-1]}-string: expecting '}}' to close '{{' "
f"on line {lineno}")

def test_unclosed_replacement_field_after_nested_fstring(self):
# gh-162140: an inner f-string that ends with an unclosed '{' must
# not change which opening brace the diagnostic identifies.
import io, tokenize
source = 'f"{\n(\nf"{:\\\n""'
with self.assertRaises(tokenize.TokenError) as cm:
list(tokenize.generate_tokens(io.StringIO(source).readline))
self.assertEqual(cm.exception.args[0],
"f-string: expecting '}' to close '{' on line 1")

@unittest.skipIf(support.is_wasi, "exhausts limited stack on WASI")
def test_mismatched_parens(self):
self.assertAllRaise(SyntaxError, r"closing parenthesis '\}' "
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix an assertion failure in the lexer, and a wrong line number in the
error message, for an unclosed f-string replacement field that contains a
nested f-string which itself ends with an unclosed replacement field.
3 changes: 2 additions & 1 deletion Parser/lexer/lexer.c
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,7 @@ tok_get_normal_mode(struct tok_state *tok, tokenizer_mode* current_tok, struct t
the_current_tok->string_kind = string_kind;
the_current_tok->curly_bracket_depth = 0;
the_current_tok->curly_bracket_expr_start_depth = -1;
the_current_tok->paren_level = tok->level;
return string_kind == TSTRING ? MAKE_TOKEN(TSTRING_START) : MAKE_TOKEN(FSTRING_START);
}

Expand Down Expand Up @@ -1144,7 +1145,7 @@ tok_get_normal_mode(struct tok_state *tok, tokenizer_mode* current_tok, struct t
tokenizer_mode *the_current_tok = TOK_GET_MODE(tok);
if (the_current_tok->quote == quote &&
the_current_tok->quote_size == quote_size) {
int level = tok->level - the_current_tok->curly_bracket_depth
int level = the_current_tok->paren_level
+ the_current_tok->curly_bracket_expr_start_depth;
assert(level >= 0 && level < tok->level);
assert(tok->parenstack[level] == '{');
Expand Down
2 changes: 2 additions & 0 deletions Parser/lexer/state.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ typedef struct _tokenizer_mode {

int curly_bracket_depth;
int curly_bracket_expr_start_depth;
/* Value of tok->level when the f-string started. */
int paren_level;

char quote;
int quote_size;
Expand Down
Loading