Skip to content

Commit

Permalink
[3.12] gh-111609: end_offset is ignored in subclasses of SyntaxError (
Browse files Browse the repository at this point in the history
#127554)

* `end_offset` is ignored in subclasses of SyntaxError

* 📜🤖 Added by blurb_it.

* Add test

---------

Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
  • Loading branch information
nineteendo and blurb-it[bot] authored Dec 11, 2024
1 parent 20c0c8c commit 487a51a
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 34 deletions.
16 changes: 16 additions & 0 deletions Lib/test/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2195,6 +2195,22 @@ def test_range_of_offsets(self):
self.assertIn(expected, err.getvalue())
the_exception = exc

def test_subclass(self):
class MySyntaxError(SyntaxError):
pass

try:
raise MySyntaxError("bad bad", ("bad.py", 1, 2, "abcdefg", 1, 7))
except SyntaxError as exc:
with support.captured_stderr() as err:
sys.__excepthook__(*sys.exc_info())
self.assertIn("""
File "bad.py", line 1
abcdefg
^^^^^
""", err.getvalue())


def test_encodings(self):
self.addCleanup(unlink, TESTFN)
source = (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Respect *end_offset* in :exc:`SyntaxError` subclasses.
62 changes: 28 additions & 34 deletions Python/pythonrun.c
Original file line number Diff line number Diff line change
Expand Up @@ -538,43 +538,37 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
*offset = hold;
}

if (Py_TYPE(err) == (PyTypeObject*)PyExc_SyntaxError) {
v = PyObject_GetAttr(err, &_Py_ID(end_lineno));
if (!v) {
PyErr_Clear();
*end_lineno = *lineno;
}
else if (v == Py_None) {
*end_lineno = *lineno;
Py_DECREF(v);
} else {
hold = PyLong_AsSsize_t(v);
Py_DECREF(v);
if (hold < 0 && PyErr_Occurred())
goto finally;
*end_lineno = hold;
}

v = PyObject_GetAttr(err, &_Py_ID(end_offset));
if (!v) {
PyErr_Clear();
*end_offset = -1;
}
else if (v == Py_None) {
*end_offset = -1;
Py_DECREF(v);
} else {
hold = PyLong_AsSsize_t(v);
Py_DECREF(v);
if (hold < 0 && PyErr_Occurred())
goto finally;
*end_offset = hold;
}
} else {
// SyntaxError subclasses
v = PyObject_GetAttr(err, &_Py_ID(end_lineno));
if (!v) {
PyErr_Clear();
*end_lineno = *lineno;
}
else if (v == Py_None) {
*end_lineno = *lineno;
Py_DECREF(v);
} else {
hold = PyLong_AsSsize_t(v);
Py_DECREF(v);
if (hold < 0 && PyErr_Occurred())
goto finally;
*end_lineno = hold;
}

v = PyObject_GetAttr(err, &_Py_ID(end_offset));
if (!v) {
PyErr_Clear();
*end_offset = -1;
}
else if (v == Py_None) {
*end_offset = -1;
Py_DECREF(v);
} else {
hold = PyLong_AsSsize_t(v);
Py_DECREF(v);
if (hold < 0 && PyErr_Occurred())
goto finally;
*end_offset = hold;
}

v = PyObject_GetAttr(err, &_Py_ID(text));
if (!v)
Expand Down

0 comments on commit 487a51a

Please sign in to comment.