Skip to content

Commit 19a8550

Browse files
bpo-46237: Fix the line number of tokenizer errors inside f-strings (GH-30463)
(cherry picked from commit 6fa8b2c) Co-authored-by: Pablo Galindo Salgado <[email protected]>
1 parent 4cfb109 commit 19a8550

File tree

4 files changed

+22
-5
lines changed

4 files changed

+22
-5
lines changed

Lib/test/test_exceptions.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,18 @@ def baz():
266266
check("(1+)", 1, 4)
267267
check("[interesting\nfoo()\n", 1, 1)
268268
check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
269+
check("""f'''
270+
{
271+
(123_a)
272+
}'''""", 3, 17)
273+
check("""f'''
274+
{
275+
f\"\"\"
276+
{
277+
(123_a)
278+
}
279+
\"\"\"
280+
}'''""", 5, 17)
269281

270282
# Errors thrown by symtable.c
271283
check('x = [(yield i) for i in range(3)]', 1, 7)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix the line number of tokenizer errors inside f-strings. Patch by Pablo
2+
Galindo.

Parser/pegen.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -701,10 +701,10 @@ initialize_token(Parser *p, Token *token, const char *start, const char *end, in
701701
int col_offset = (start != NULL && start >= line_start) ? (int)(start - line_start) : -1;
702702
int end_col_offset = (end != NULL && end >= p->tok->line_start) ? (int)(end - p->tok->line_start) : -1;
703703

704-
token->lineno = p->starting_lineno + lineno;
705-
token->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
706-
token->end_lineno = p->starting_lineno + end_lineno;
707-
token->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
704+
token->lineno = lineno;
705+
token->col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + col_offset : col_offset;
706+
token->end_lineno = end_lineno;
707+
token->end_col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + end_col_offset : end_col_offset;
708708

709709
p->fill += 1;
710710

Parser/string_parser.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,11 +392,14 @@ fstring_compile_expr(Parser *p, const char *expr_start, const char *expr_end,
392392
return NULL;
393393
}
394394
Py_INCREF(p->tok->filename);
395+
395396
tok->filename = p->tok->filename;
397+
tok->lineno = t->lineno + lines - 1;
396398

397399
Parser *p2 = _PyPegen_Parser_New(tok, Py_fstring_input, p->flags, p->feature_version,
398400
NULL, p->arena);
399-
p2->starting_lineno = t->lineno + lines - 1;
401+
402+
p2->starting_lineno = t->lineno + lines;
400403
p2->starting_col_offset = t->col_offset + cols;
401404

402405
expr = _PyPegen_run_parser(p2);

0 commit comments

Comments
 (0)