Skip to content

Commit f75abf8

Browse files
[3.12] gh-120343: Fix column offsets of multiline tokens in tokenize (GH-120391) (#120428)
(cherry picked from commit 4b5d3e0) Co-authored-by: Lysandros Nikolaou <[email protected]>
1 parent 319233f commit f75abf8

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

Lib/test/test_tokenize.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1215,6 +1215,20 @@ def test_multiline_non_ascii_fstring(self):
12151215
FSTRING_END "\'\'\'" (2, 68) (2, 71)
12161216
""")
12171217

1218+
def test_multiline_non_ascii_fstring_with_expr(self):
1219+
self.check_tokenize("""\
1220+
f'''
1221+
🔗 This is a test {test_arg1}🔗
1222+
🔗'''""", """\
1223+
FSTRING_START "f\'\'\'" (1, 0) (1, 4)
1224+
FSTRING_MIDDLE '\\n 🔗 This is a test ' (1, 4) (2, 21)
1225+
OP '{' (2, 21) (2, 22)
1226+
NAME 'test_arg1' (2, 22) (2, 31)
1227+
OP '}' (2, 31) (2, 32)
1228+
FSTRING_MIDDLE '🔗\\n🔗' (2, 32) (3, 1)
1229+
FSTRING_END "\'\'\'" (3, 1) (3, 4)
1230+
""")
1231+
12181232
class GenerateTokensTest(TokenizeTest):
12191233
def check_tokenize(self, s, expected):
12201234
# Format the tokens in s in a table format.

Python/Python-tokenize.c

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,7 @@ tokenizeriter_next(tokenizeriterobject *it)
214214

215215
const char *line_start = ISSTRINGLIT(type) ? it->tok->multi_line_start : it->tok->line_start;
216216
PyObject* line = NULL;
217+
int line_changed = 1;
217218
if (it->tok->tok_extra_tokens && is_trailing_token) {
218219
line = PyUnicode_FromString("");
219220
} else {
@@ -228,12 +229,11 @@ tokenizeriter_next(tokenizeriterobject *it)
228229
Py_XDECREF(it->last_line);
229230
line = PyUnicode_DecodeUTF8(line_start, size, "replace");
230231
it->last_line = line;
231-
if (it->tok->lineno != it->last_end_lineno) {
232-
it->byte_col_offset_diff = 0;
233-
}
232+
it->byte_col_offset_diff = 0;
234233
} else {
235234
// Line hasn't changed so we reuse the cached one.
236235
line = it->last_line;
236+
line_changed = 0;
237237
}
238238
}
239239
if (line == NULL) {
@@ -251,7 +251,13 @@ tokenizeriter_next(tokenizeriterobject *it)
251251
Py_ssize_t byte_offset = -1;
252252
if (token.start != NULL && token.start >= line_start) {
253253
byte_offset = token.start - line_start;
254-
col_offset = byte_offset - it->byte_col_offset_diff;
254+
if (line_changed) {
255+
col_offset = _PyPegen_byte_offset_to_character_offset_line(line, 0, byte_offset);
256+
it->byte_col_offset_diff = byte_offset - col_offset;
257+
}
258+
else {
259+
col_offset = byte_offset - it->byte_col_offset_diff;
260+
}
255261
}
256262
if (token.end != NULL && token.end >= it->tok->line_start) {
257263
Py_ssize_t end_byte_offset = token.end - it->tok->line_start;

0 commit comments

Comments
 (0)