Skip to content

Commit 5563404

Browse files
pablogsalashm-dev
andauthored
[3.15] gh-157378: Fix SyntaxError.offset for "Non-UTF-8 code" error (GH-157412) (#158123)
(cherry picked from commit e66bec0) Co-authored-by: Shamil <ashm.tech@proton.me>
1 parent 3b259b9 commit 5563404

3 files changed

Lines changed: 15 additions & 4 deletions

File tree

‎Lib/test/test_exceptions.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,16 @@ def testSyntaxErrorRange(self):
249249
self.assertEqual(cm.exception.offset, offset)
250250
self.assertEqual(cm.exception.end_offset, end_offset)
251251

252+
def testSyntaxErrorNonUTF8Offset(self):
253+
# gh-157378: the position was reported one column short for each
254+
# multi-byte character preceding the invalid byte on the same line
255+
check = self.check
256+
check(b'X\x80', 1, 2, 1, 2)
257+
check(b'\xc3\xa9X\x80', 1, 3, 1, 3)
258+
check(b'\t\xc3\xa9X\x80', 1, 4, 1, 4)
259+
check(b'a\xc3\xa9b\x80c', 1, 4, 1, 4)
260+
check(b'a\n\xc3\xa9X\x80', 2, 3, 2, 3)
261+
252262
def testSyntaxErrorOffset(self):
253263
check = self.check
254264
check('def fact(x):\n\treturn x!\n', 2, 10)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix ``SyntaxError.offset`` and ``SyntaxError.end_offset`` for the
2+
"Non-UTF-8 code starting with ..." error when a non-ASCII character precedes
3+
the invalid byte on the same line. Patch by Shamil Abdulaev.

‎Parser/tokenizer/helpers.c‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -579,17 +579,14 @@ _PyTokenizer_ensure_utf8(const char *line, struct tok_state *tok, int lineno)
579579
const char *badchar = NULL;
580580
const char *c;
581581
int length;
582-
int col_offset = 0;
583582
const char *line_start = line;
584583
for (c = line; *c; c += length) {
585584
if (!(length = valid_utf8((const unsigned char *)c))) {
586585
badchar = c;
587586
break;
588587
}
589-
col_offset++;
590588
if (*c == '\n') {
591589
lineno++;
592-
col_offset = 0;
593590
line_start = c + 1;
594591
}
595592
}
@@ -598,7 +595,8 @@ _PyTokenizer_ensure_utf8(const char *line, struct tok_state *tok, int lineno)
598595
tok->line_start = line_start;
599596
tok->cur = (char *)badchar;
600597
_PyTokenizer_syntaxerror_known_range(tok,
601-
col_offset + 1, col_offset + 1,
598+
(int)(badchar - line_start) + 1,
599+
(int)(badchar - line_start) + 1,
602600
"Non-UTF-8 code starting with '\\x%.2x'"
603601
"%s%V on line %i, "
604602
"but no encoding declared; "

0 commit comments

Comments
 (0)