Skip to content

Commit 097b8b6

Browse files
bpo-40985: Show correct SyntaxError text when last line has a LINECONT (GH-20888)
When a file ends with a line that contains a line continuation character the text of the emitted SyntaxError is empty, contrary to the old parser, where the error text contained the text of the last line. (cherry picked from commit 113e2b0) Co-authored-by: Lysandros Nikolaou <[email protected]>
1 parent bc996c6 commit 097b8b6

File tree

3 files changed

+13
-4
lines changed

3 files changed

+13
-4
lines changed

Lib/test/test_eof.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,14 @@ def test_line_continuation_EOF_from_file_bpo2180(self):
5252
file_name = script_helper.make_script(temp_dir, 'foo', '\\')
5353
rc, out, err = script_helper.assert_python_failure(file_name)
5454
self.assertIn(b'unexpected EOF while parsing', err)
55+
self.assertIn(b'line 2', err)
56+
self.assertIn(b'\\', err)
5557

5658
file_name = script_helper.make_script(temp_dir, 'foo', 'y = 6\\')
5759
rc, out, err = script_helper.assert_python_failure(file_name)
5860
self.assertIn(b'unexpected EOF while parsing', err)
61+
self.assertIn(b'line 2', err)
62+
self.assertIn(b'y = 6\\', err)
5963

6064
if __name__ == "__main__":
6165
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a bug that caused the :exc:`SyntaxError` text to be empty when a file ends with a line ending in a line continuation character (i.e. backslash). The error text should contain the text of the last line.

Python/errors.c

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1648,23 +1648,27 @@ err_programtext(PyThreadState *tstate, FILE *fp, int lineno)
16481648
{
16491649
int i;
16501650
char linebuf[1000];
1651-
1652-
if (fp == NULL)
1651+
if (fp == NULL) {
16531652
return NULL;
1653+
}
1654+
16541655
for (i = 0; i < lineno; i++) {
16551656
char *pLastChar = &linebuf[sizeof(linebuf) - 2];
16561657
do {
16571658
*pLastChar = '\0';
16581659
if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1659-
fp, NULL) == NULL)
1660-
break;
1660+
fp, NULL) == NULL) {
1661+
goto after_loop;
1662+
}
16611663
/* fgets read *something*; if it didn't get as
16621664
far as pLastChar, it must have found a newline
16631665
or hit the end of the file; if pLastChar is \n,
16641666
it obviously found a newline; else we haven't
16651667
yet seen a newline, so must continue */
16661668
} while (*pLastChar != '\0' && *pLastChar != '\n');
16671669
}
1670+
1671+
after_loop:
16681672
fclose(fp);
16691673
if (i == lineno) {
16701674
PyObject *res;

0 commit comments

Comments
 (0)