Skip to content

Commit 1723eb9

Browse files
committed
compat patches
1 parent 1d1b3b9 commit 1723eb9

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

mlir/lib/Bindings/Python/Traceback.cpp

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,29 @@ limitations under the License.
4343

4444
// Introduced in python 3.10
4545
#if PY_VERSION_HEX < 0x030a00f0
46-
PyObject * Py_NewRef(PyObject *o) {
46+
PyObject *Py_NewRef(PyObject *o) {
4747
Py_INCREF(o);
4848
return o;
4949
}
5050
#endif
5151

52+
// bpo-40421 added PyFrame_GetLasti() to Python 3.11.0b1
53+
#if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION)
54+
static inline int PyFrame_GetLasti(PyFrameObject *frame) {
55+
#if PY_VERSION_HEX >= 0x030A00A7
56+
// bpo-27129: Since Python 3.10.0a7, f_lasti is an instruction offset,
57+
// not a bytes offset anymore. Python uses 16-bit "wordcode" (2 bytes)
58+
// instructions.
59+
if (frame->f_lasti < 0) {
60+
return -1;
61+
}
62+
return frame->f_lasti * 2;
63+
#else
64+
return frame->f_lasti;
65+
#endif
66+
}
67+
#endif
68+
5269
namespace mlir::python {
5370
struct TracebackEntry;
5471
struct TracebackObject;
@@ -143,9 +160,15 @@ static void traceback_tp_dealloc(PyObject *self) {
143160
}
144161

145162
Traceback::Frame DecodeFrame(const TracebackEntry &frame) {
163+
// python 3.11
164+
#if PY_VERSION_HEX < 0x030b00f0
165+
PyObject *name = frame.code->co_name;
166+
#else
167+
PyObject *name = frame.code->co_qualname;
168+
#endif
146169
return Traceback::Frame{
147170
.file_name = nb::borrow<nb::str>(frame.code->co_filename),
148-
.function_name = nb::borrow<nb::str>(frame.code->co_qualname),
171+
.function_name = nb::borrow<nb::str>(name),
149172
.function_start_line = frame.code->co_firstlineno,
150173
.line_num = PyCode_Addr2Line(frame.code, frame.lasti),
151174
};
@@ -423,11 +446,13 @@ void BuildTracebackSubmodule(nb::module_ &m) {
423446
throw std::runtime_error("code argument must be a code object");
424447
}
425448
int start_line, start_column, end_line, end_column;
426-
if (!PyCode_Addr2Location(reinterpret_cast<PyCodeObject *>(code.ptr()),
427-
lasti, &start_line, &start_column, &end_line,
428-
&end_column)) {
429-
throw nb::python_error();
430-
}
449+
// if (!PyCode_Addr2Location(reinterpret_cast<PyCodeObject
450+
// *>(code.ptr()),
451+
// lasti, &start_line, &start_column,
452+
// &end_line, &end_column)) {
453+
// throw nb::python_error();
454+
// }
455+
throw nb::python_error();
431456
return nb::make_tuple(start_line, start_column, end_line, end_column);
432457
},
433458
"Python wrapper around the Python C API function PyCode_Addr2Location");

0 commit comments

Comments
 (0)