Skip to content
Closed
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
17 changes: 17 additions & 0 deletions Lib/test/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2710,6 +2710,23 @@ def try_compile(source):
self.assertEqual(exc.offset, 1)
self.assertEqual(exc.end_offset, 12)

def test_parser_error_uses_supplied_source(self):
self.addCleanup(unlink, TESTFN)
with open(TESTFN, 'wb') as f:
f.write(b'pass\npass\n')

line = 'café = 1 + * 2\n'
source = '# coding: latin-1\n' + line
for src in (source, source.encode('latin-1')):
with self.subTest(src=src):
with self.assertRaises(SyntaxError) as cm:
compile(src, TESTFN, 'exec')
exc = cm.exception
self.assertEqual(exc.filename, TESTFN)
self.assertEqual(exc.lineno, 2)
self.assertEqual(exc.text, line)
self.assertEqual((exc.offset, exc.end_offset), (12, 13))

def test_file_source(self):
self.addCleanup(unlink, TESTFN)
err = run_script('return "ä"')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
When parsing source passed to :func:`compile` or :func:`ast.parse`, use the
supplied source for the text and column offsets of parser-generated
:exc:`SyntaxError` exceptions even when the filename names an existing file.
12 changes: 4 additions & 8 deletions Parser/pegen_errors.c
Original file line number Diff line number Diff line change
Expand Up @@ -321,19 +321,15 @@ _PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
if (info.is_interactive && _PyTokenizer_RetainedSource(p->tok) != NULL) {
error_line = get_error_line_from_source(p, lineno);
}
else if (p->start_rule == Py_file_input) {
else if (p->start_rule == Py_file_input &&
_PyTokenizer_RetainedSource(p->tok) == NULL) {
error_line = _PyErr_ProgramDecodedTextObject(info.filename,
(int) lineno, info.encoding);
}

if (!error_line) {
/* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
then we need to find the error line from some other source, because
p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
failed or we're parsing from a string or the REPL. There's a third edge case where
we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
`PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
does not physically exist */
/* Use the tokenizer's input. For a file, an EOF error can point
one line past the last line on disk. */
assert(!info.is_file || info.status == E_EOF);

if (location.lineno <= lineno &&
Expand Down
Loading