@@ -36,6 +36,28 @@ namespace {
3636const destructor original_gen_dealloc = PyGen_Type.tp_dealloc;
3737const destructor original_coro_dealloc = PyCoro_Type.tp_dealloc;
3838
39+ // Track a GC object whose type is known to have GC support.
40+ template <class T >
41+ void track (T arg) {
42+ BorrowedRef<> obj{_PyObject_CAST (arg)};
43+ #if defined(META_PYTHON)
44+ _PyObject_GC_TRACK (obj);
45+ #else
46+ PyObject_GC_Track (obj);
47+ #endif
48+ }
49+
50+ // Untrack a GC object whose type is known to have GC support.
51+ template <class T >
52+ void untrack (T arg) {
53+ BorrowedRef<> obj{_PyObject_CAST (arg)};
54+ #if defined(META_PYTHON)
55+ _PyObject_GC_UNTRACK (obj);
56+ #else
57+ PyObject_GC_UnTrack (obj);
58+ #endif
59+ }
60+
3961// Reimplementation of CPython's gen_dealloc that uses our custom free-list
4062// (Ci_free_jit_list_gen) instead of PyObject_GC_Del for memory recycling.
4163void gen_dealloc_with_custom_free (PyObject* self) {
@@ -45,18 +67,18 @@ void gen_dealloc_with_custom_free(PyObject* self) {
4567
4668 auto * gen = reinterpret_cast <PyGenObject*>(self);
4769
48- _PyObject_GC_UNTRACK (gen);
70+ untrack (gen);
4971
5072 if (gen->gi_weakreflist != nullptr ) {
5173 PyObject_ClearWeakRefs (self);
5274 }
5375
5476 // Re-track so the finalizer can run; it may resurrect the object.
55- _PyObject_GC_TRACK (self);
77+ track (self);
5678 if (PyObject_CallFinalizerFromDealloc (self)) {
5779 return ;
5880 }
59- _PyObject_GC_UNTRACK (self);
81+ untrack (self);
6082
6183 JIT_DCHECK (
6284 !PyAsyncGen_CheckExact (gen),
@@ -445,7 +467,7 @@ struct JitCoroWrapper {
445467};
446468
447469void jitcoro_wrapper_dealloc (JitCoroWrapper* cw) {
448- PyObject_GC_UnTrack (reinterpret_cast <PyObject*>(cw));
470+ untrack (reinterpret_cast <PyObject*>(cw));
449471 Py_CLEAR (cw->cw_coroutine );
450472 PyObject_GC_Del (cw);
451473}
@@ -570,13 +592,14 @@ PyTypeObject _JitCoroWrapper_Type = {
570592};
571593
572594namespace {
595+
573596PyObject* jitcoro_await (PyCoroObject* coro) {
574597 JitCoroWrapper* cw = PyObject_GC_New (JitCoroWrapper, &_JitCoroWrapper_Type);
575598 if (cw == nullptr ) {
576599 return nullptr ;
577600 }
578601 cw->cw_coroutine = Py_NewRef (coro);
579- PyObject_GC_Track (cw);
602+ track (cw);
580603 return reinterpret_cast <PyObject*>(cw);
581604}
582605
0 commit comments