Skip to content

Commit 2f7889d

Browse files
refactor(query): replace usage of private function
1 parent 876fd40 commit 2f7889d

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

tests/test_query.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from re import error as RegexError
12
from unittest import TestCase
23

34
import tree_sitter_python
@@ -257,6 +258,19 @@ def test_text_predicates_errors(self):
257258
"""
258259
)
259260

261+
with self.assertRaises(QueryError) as ctx:
262+
self.javascript.query(
263+
"""
264+
((function_declaration
265+
name: (identifier) @function-name)
266+
(#match? @function-name "?"))
267+
"""
268+
)
269+
self.assertEqual(
270+
str(ctx.exception), "Invalid predicate in pattern at row 1: regular expression error"
271+
)
272+
self.assertIsInstance(ctx.exception.__cause__, RegexError)
273+
260274
def test_point_range_captures(self):
261275
parser = Parser(self.python)
262276
source = b"def foo():\n bar()\ndef baz():\n quux()\n"

tree_sitter/binding/query.c

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -274,9 +274,33 @@ PyObject *query_new(PyTypeObject *cls, PyObject *args, PyObject *Py_UNUSED(kwarg
274274
PyObject *pattern =
275275
PyObject_CallFunction(state->re_compile, "s#", second_arg, length);
276276
if (pattern == NULL) {
277-
_PyErr_FormatFromCause(
278-
state->query_error,
279-
"Invalid predicate in pattern at row %u: regular expression error", row);
277+
const char *msg =
278+
"Invalid predicate in pattern at row %u: regular expression error";
279+
#if PY_MINOR_VERSION < 12
280+
PyObject *etype, *cause, *exc, *trace;
281+
PyErr_Fetch(&etype, &cause, &trace);
282+
PyErr_NormalizeException(&etype, &cause, &trace);
283+
if (trace != NULL) {
284+
PyException_SetTraceback(cause, trace);
285+
Py_DECREF(trace);
286+
}
287+
Py_DECREF(etype);
288+
PyErr_Format(state->query_error, msg, row);
289+
PyErr_Fetch(&etype, &exc, &trace);
290+
PyErr_NormalizeException(&etype, &exc, &trace);
291+
Py_INCREF(cause);
292+
PyException_SetCause(exc, cause);
293+
PyException_SetContext(exc, cause);
294+
PyErr_Restore(etype, exc, trace);
295+
#else
296+
PyObject *cause = PyErr_GetRaisedException();
297+
PyErr_Format(state->query_error, msg, row);
298+
PyObject *exc = PyErr_GetRaisedException();
299+
PyException_SetCause(exc, Py_NewRef(cause));
300+
PyException_SetContext(exc, Py_NewRef(cause));
301+
Py_DECREF(cause);
302+
PyErr_SetRaisedException(exc);
303+
#endif
280304
goto error;
281305
}
282306

0 commit comments

Comments
 (0)