blob: 33fc4a592492a8eb992ce714f9631a90707345ab [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02004#include "pycore_ceval.h" // _PyEval_EvalFrame()
Victor Stinnerbcda8f12018-11-21 22:27:47 +01005#include "pycore_object.h"
Chris Jerdonekda742ba2020-05-17 22:47:31 -07006#include "pycore_pyerrors.h" // _PyErr_ClearExcState()
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include "pycore_pystate.h" // _PyThreadState_GET()
Martin v. Löwise440e472004-06-01 15:22:42 +00008#include "frameobject.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02009#include "structmember.h" // PyMemberDef
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +000011
Yury Selivanoveb636452016-09-08 22:01:51 -070012static PyObject *gen_close(PyGenObject *, PyObject *);
13static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
14static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
15
Andy Lester7386a702020-02-13 22:42:56 -060016static const char *NON_INIT_CORO_MSG = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -070017 "just-started coroutine";
18
Andy Lester7386a702020-02-13 22:42:56 -060019static const char *ASYNC_GEN_IGNORED_EXIT_MSG =
Yury Selivanoveb636452016-09-08 22:01:51 -070020 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100021
Mark Shannonae3087c2017-10-22 22:41:51 +010022static inline int
23exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
24{
25 Py_VISIT(exc_state->exc_type);
26 Py_VISIT(exc_state->exc_value);
27 Py_VISIT(exc_state->exc_traceback);
28 return 0;
29}
30
Martin v. Löwise440e472004-06-01 15:22:42 +000031static int
32gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
33{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_VISIT((PyObject *)gen->gi_frame);
35 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020036 Py_VISIT(gen->gi_name);
37 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080038 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
39 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010040 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000041}
42
Antoine Pitrou58720d62013-08-05 23:26:40 +020043void
44_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020045{
46 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070047 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020048 PyObject *error_type, *error_value, *error_traceback;
49
Mark Shannoncb9879b2020-07-17 11:44:23 +010050 if (gen->gi_frame == NULL || _PyFrameHasCompleted(gen->gi_frame)) {
Antoine Pitrou796564c2013-07-30 19:59:21 +020051 /* Generator isn't paused, so no need to close */
52 return;
Yury Selivanov2a2270d2018-01-29 14:31:47 -050053 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020054
Yury Selivanoveb636452016-09-08 22:01:51 -070055 if (PyAsyncGen_CheckExact(self)) {
56 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
57 PyObject *finalizer = agen->ag_finalizer;
58 if (finalizer && !agen->ag_closed) {
59 /* Save the current exception, if any. */
60 PyErr_Fetch(&error_type, &error_value, &error_traceback);
61
Petr Viktorinffd97532020-02-11 17:46:57 +010062 res = PyObject_CallOneArg(finalizer, self);
Yury Selivanoveb636452016-09-08 22:01:51 -070063
64 if (res == NULL) {
65 PyErr_WriteUnraisable(self);
66 } else {
67 Py_DECREF(res);
68 }
69 /* Restore the saved exception. */
70 PyErr_Restore(error_type, error_value, error_traceback);
71 return;
72 }
73 }
74
Antoine Pitrou796564c2013-07-30 19:59:21 +020075 /* Save the current exception, if any. */
76 PyErr_Fetch(&error_type, &error_value, &error_traceback);
77
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070078 /* If `gen` is a coroutine, and if it was never awaited on,
79 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070080 if (gen->gi_code != NULL &&
81 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
Yury Selivanov2a2270d2018-01-29 14:31:47 -050082 gen->gi_frame->f_lasti == -1)
83 {
84 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070085 }
86 else {
87 res = gen_close(gen, NULL);
88 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020089
Benjamin Petersonb88db872016-09-07 08:46:59 -070090 if (res == NULL) {
Yury Selivanov2a2270d2018-01-29 14:31:47 -050091 if (PyErr_Occurred()) {
Benjamin Petersonb88db872016-09-07 08:46:59 -070092 PyErr_WriteUnraisable(self);
Yury Selivanov2a2270d2018-01-29 14:31:47 -050093 }
Benjamin Petersonb88db872016-09-07 08:46:59 -070094 }
95 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020096 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070097 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020098
99 /* Restore the saved exception. */
100 PyErr_Restore(error_type, error_value, error_traceback);
101}
102
103static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000104gen_dealloc(PyGenObject *gen)
105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (gen->gi_weakreflist != NULL)
111 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000112
Antoine Pitrou93963562013-05-14 20:37:52 +0200113 _PyObject_GC_TRACK(self);
114
Antoine Pitrou796564c2013-07-30 19:59:21 +0200115 if (PyObject_CallFinalizerFromDealloc(self))
116 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200117
118 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700119 if (PyAsyncGen_CheckExact(gen)) {
120 /* We have to handle this case for asynchronous generators
121 right here, because this code has to be between UNTRACK
122 and GC_Del. */
123 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
124 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700125 if (gen->gi_frame != NULL) {
126 gen->gi_frame->f_gen = NULL;
127 Py_CLEAR(gen->gi_frame);
128 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800129 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
130 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200133 Py_CLEAR(gen->gi_name);
134 Py_CLEAR(gen->gi_qualname);
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700135 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000137}
138
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300139static PySendResult
140gen_send_ex2(PyGenObject *gen, PyObject *arg, PyObject **presult,
141 int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000142{
Victor Stinner50b48572018-11-01 01:51:40 +0100143 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200145 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000146
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300147 *presult = NULL;
Mark Shannon99c72322021-12-08 14:46:32 +0000148 if (f != NULL && f->f_lasti < 0 && arg && arg != Py_None) {
149 const char *msg = "can't send non-None value to a "
150 "just-started generator";
151 if (PyCoro_CheckExact(gen)) {
152 msg = NON_INIT_CORO_MSG;
153 }
154 else if (PyAsyncGen_CheckExact(gen)) {
155 msg = "can't send non-None value to a "
156 "just-started async generator";
157 }
158 PyErr_SetString(PyExc_TypeError, msg);
159 return PYGEN_ERROR;
160 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100161 if (f != NULL && _PyFrame_IsExecuting(f)) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200162 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700163 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400164 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700165 }
166 else if (PyAsyncGen_CheckExact(gen)) {
167 msg = "async generator already executing";
168 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400169 PyErr_SetString(PyExc_ValueError, msg);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300170 return PYGEN_ERROR;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500171 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100172 if (f == NULL || _PyFrameHasCompleted(f)) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500173 if (PyCoro_CheckExact(gen) && !closing) {
174 /* `gen` is an exhausted coroutine: raise an error,
175 except when called from gen_close(), which should
176 always be a silent method. */
177 PyErr_SetString(
178 PyExc_RuntimeError,
179 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700180 }
181 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500182 /* `gen` is an exhausted generator:
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300183 only return value if called from send(). */
184 *presult = Py_None;
185 Py_INCREF(*presult);
186 return PYGEN_RETURN;
Yury Selivanov77c96812016-02-13 17:59:05 -0500187 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300188 return PYGEN_ERROR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000190
Mark Shannoncb9879b2020-07-17 11:44:23 +0100191 assert(_PyFrame_IsRunnable(f));
Mark Shannonb37181e2021-04-06 11:48:59 +0100192 assert(f->f_lasti >= 0 || ((unsigned char *)PyBytes_AS_STRING(f->f_code->co_code))[0] == GEN_START);
193 /* Push arg onto the frame's value stack */
194 result = arg ? arg : Py_None;
195 Py_INCREF(result);
196 gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth] = result;
197 gen->gi_frame->f_stackdepth++;
Antoine Pitrou93963562013-05-14 20:37:52 +0200198
199 /* Generators always return to their most recent caller, not
200 * necessarily their creator. */
201 Py_XINCREF(tstate->frame);
202 assert(f->f_back == NULL);
203 f->f_back = tstate->frame;
204
Mark Shannonae3087c2017-10-22 22:41:51 +0100205 gen->gi_exc_state.previous_item = tstate->exc_info;
206 tstate->exc_info = &gen->gi_exc_state;
Chris Jerdonek7c30d122020-05-22 13:33:27 -0700207
208 if (exc) {
209 assert(_PyErr_Occurred(tstate));
210 _PyErr_ChainStackItem(NULL);
211 }
212
Victor Stinnerb9e68122019-11-14 12:20:46 +0100213 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100214 tstate->exc_info = gen->gi_exc_state.previous_item;
215 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200216
217 /* Don't keep the reference to f_back any longer than necessary. It
218 * may keep a chain of frames alive or it could create a reference
219 * cycle. */
220 assert(f->f_back == tstate->frame);
221 Py_CLEAR(f->f_back);
222
223 /* If the generator just returned (as opposed to yielding), signal
224 * that the generator is exhausted. */
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300225 if (result) {
226 if (!_PyFrameHasCompleted(f)) {
227 *presult = result;
228 return PYGEN_NEXT;
229 }
230 assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
231 if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
232 /* Return NULL if called by gen_iternext() */
233 Py_CLEAR(result);
234 }
235 }
236 else {
237 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
238 const char *msg = "generator raised StopIteration";
239 if (PyCoro_CheckExact(gen)) {
240 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700241 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300242 else if (PyAsyncGen_CheckExact(gen)) {
243 msg = "async generator raised StopIteration";
Vladimir Matveev2b053612020-09-18 18:38:38 -0700244 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300245 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
246 }
247 else if (PyAsyncGen_CheckExact(gen) &&
248 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
249 {
250 /* code in `gen` raised a StopAsyncIteration error:
251 raise a RuntimeError.
252 */
253 const char *msg = "async generator raised StopAsyncIteration";
254 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
255 }
256 }
257
258 /* generator can't be rerun, so release the frame */
259 /* first clean reference cycle through stored exception traceback */
260 _PyErr_ClearExcState(&gen->gi_exc_state);
261 gen->gi_frame->f_gen = NULL;
262 gen->gi_frame = NULL;
263 Py_DECREF(f);
264
265 *presult = result;
266 return result ? PYGEN_RETURN : PYGEN_ERROR;
267}
268
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800269static PySendResult
270PyGen_am_send(PyGenObject *gen, PyObject *arg, PyObject **result)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300271{
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800272 return gen_send_ex2(gen, arg, result, 0, 0);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300273}
274
275static PyObject *
276gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
277{
278 PyObject *result;
279 if (gen_send_ex2(gen, arg, &result, exc, closing) == PYGEN_RETURN) {
280 if (PyAsyncGen_CheckExact(gen)) {
281 assert(result == Py_None);
282 PyErr_SetNone(PyExc_StopAsyncIteration);
283 }
284 else if (result == Py_None) {
285 PyErr_SetNone(PyExc_StopIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -0700286 }
287 else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300288 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200289 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300290 Py_CLEAR(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200291 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200292 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000293}
294
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000295PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000296"send(arg) -> send 'arg' into generator,\n\
297return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000298
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300299static PyObject *
300gen_send(PyGenObject *gen, PyObject *arg)
301{
302 return gen_send_ex(gen, arg, 0, 0);
303}
304
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000305PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400306"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000307
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000308/*
309 * This helper function is used by gen_close and gen_throw to
310 * close a subiterator being delegated to by yield-from.
311 */
312
Antoine Pitrou93963562013-05-14 20:37:52 +0200313static int
314gen_close_iter(PyObject *yf)
315{
316 PyObject *retval = NULL;
317 _Py_IDENTIFIER(close);
318
Yury Selivanoveb636452016-09-08 22:01:51 -0700319 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200320 retval = gen_close((PyGenObject *)yf, NULL);
321 if (retval == NULL)
322 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700323 }
324 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200325 PyObject *meth;
326 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
327 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700328 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200329 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700330 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200331 Py_DECREF(meth);
332 if (retval == NULL)
333 return -1;
334 }
335 }
336 Py_XDECREF(retval);
337 return 0;
338}
339
Yury Selivanovc724bae2016-03-02 11:30:46 -0500340PyObject *
341_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500342{
Antoine Pitrou93963562013-05-14 20:37:52 +0200343 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500344 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200345
Mark Shannoncb9879b2020-07-17 11:44:23 +0100346 if (f) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200347 PyObject *bytecode = f->f_code->co_code;
348 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
349
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100350 if (f->f_lasti < 0) {
351 /* Return immediately if the frame didn't start yet. YIELD_FROM
352 always come after LOAD_CONST: a code object should not start
353 with YIELD_FROM */
354 assert(code[0] != YIELD_FROM);
355 return NULL;
356 }
357
Mark Shannonfcb55c02021-04-01 16:00:31 +0100358 if (code[(f->f_lasti+1)*sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200359 return NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100360 assert(f->f_stackdepth > 0);
361 yf = f->f_valuestack[f->f_stackdepth-1];
Antoine Pitrou93963562013-05-14 20:37:52 +0200362 Py_INCREF(yf);
363 }
364
365 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500366}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000367
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000368static PyObject *
369gen_close(PyGenObject *gen, PyObject *args)
370{
Antoine Pitrou93963562013-05-14 20:37:52 +0200371 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500372 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200373 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000374
Antoine Pitrou93963562013-05-14 20:37:52 +0200375 if (yf) {
Mark Shannoncb9879b2020-07-17 11:44:23 +0100376 PyFrameState state = gen->gi_frame->f_state;
377 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200378 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100379 gen->gi_frame->f_state = state;
Antoine Pitrou93963562013-05-14 20:37:52 +0200380 Py_DECREF(yf);
381 }
382 if (err == 0)
383 PyErr_SetNone(PyExc_GeneratorExit);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300384 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200385 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200386 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700387 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400388 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700389 } else if (PyAsyncGen_CheckExact(gen)) {
390 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
391 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200392 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400393 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return NULL;
395 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200396 if (PyErr_ExceptionMatches(PyExc_StopIteration)
397 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
398 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200399 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200400 }
401 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000402}
403
Antoine Pitrou93963562013-05-14 20:37:52 +0200404
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000405PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
407return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000408
409static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700410_gen_throw(PyGenObject *gen, int close_on_genexit,
411 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000412{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500413 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000414 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000415
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000416 if (yf) {
417 PyObject *ret;
418 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700419 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
420 close_on_genexit
421 ) {
422 /* Asynchronous generators *should not* be closed right away.
423 We have to allow some awaits to work it through, hence the
424 `close_on_genexit` parameter here.
425 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100426 PyFrameState state = gen->gi_frame->f_state;
427 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200428 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100429 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000430 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000431 if (err < 0)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300432 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000433 goto throw_here;
434 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700435 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
436 /* `yf` is a generator or a coroutine. */
Chris Jerdonek8b339612020-07-09 06:27:23 -0700437 PyThreadState *tstate = _PyThreadState_GET();
438 PyFrameObject *f = tstate->frame;
439
Chris Jerdonek8b339612020-07-09 06:27:23 -0700440 /* Since we are fast-tracking things by skipping the eval loop,
441 we need to update the current frame so the stack trace
442 will be reported correctly to the user. */
443 /* XXX We should probably be updating the current frame
444 somewhere in ceval.c. */
445 tstate->frame = gen->gi_frame;
Yury Selivanoveb636452016-09-08 22:01:51 -0700446 /* Close the generator that we are currently iterating with
447 'yield from' or awaiting on with 'await'. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100448 PyFrameState state = gen->gi_frame->f_state;
449 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700450 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
451 typ, val, tb);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100452 gen->gi_frame->f_state = state;
Chris Jerdonek8b339612020-07-09 06:27:23 -0700453 tstate->frame = f;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000454 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700455 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200456 PyObject *meth;
457 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
458 Py_DECREF(yf);
459 return NULL;
460 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000461 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000462 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000463 goto throw_here;
464 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100465 PyFrameState state = gen->gi_frame->f_state;
466 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700467 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100468 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000469 Py_DECREF(meth);
470 }
471 Py_DECREF(yf);
472 if (!ret) {
473 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500474 /* Pop subiterator from stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100475 assert(gen->gi_frame->f_stackdepth > 0);
476 gen->gi_frame->f_stackdepth--;
477 ret = gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth];
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500478 assert(ret == yf);
479 Py_DECREF(ret);
480 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100481 assert(gen->gi_frame->f_lasti >= 0);
Mark Shannonfcb55c02021-04-01 16:00:31 +0100482 gen->gi_frame->f_lasti += 1;
Nick Coghlanc40bc092012-06-17 15:15:49 +1000483 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300484 ret = gen_send(gen, val);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000485 Py_DECREF(val);
486 } else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300487 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000488 }
489 }
490 return ret;
491 }
492
493throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* First, check the traceback argument, replacing None with
495 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400496 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400498 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 else if (tb != NULL && !PyTraceBack_Check(tb)) {
500 PyErr_SetString(PyExc_TypeError,
501 "throw() third argument must be a traceback object");
502 return NULL;
503 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 Py_INCREF(typ);
506 Py_XINCREF(val);
507 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000508
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400509 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 else if (PyExceptionInstance_Check(typ)) {
513 /* Raising an instance. The value should be a dummy. */
514 if (val && val != Py_None) {
515 PyErr_SetString(PyExc_TypeError,
516 "instance exception may not have a separate value");
517 goto failed_throw;
518 }
519 else {
520 /* Normalize to raise <class>, <instance> */
521 Py_XDECREF(val);
522 val = typ;
523 typ = PyExceptionInstance_Class(typ);
524 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200525
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400526 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200527 /* Returns NULL if there's no traceback */
528 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 }
530 }
531 else {
532 /* Not something you can raise. throw() fails. */
533 PyErr_Format(PyExc_TypeError,
534 "exceptions must be classes or instances "
535 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000536 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 goto failed_throw;
538 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 PyErr_Restore(typ, val, tb);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300541 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000542
543failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* Didn't use our arguments, so restore their original refcounts */
545 Py_DECREF(typ);
546 Py_XDECREF(val);
547 Py_XDECREF(tb);
548 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000549}
550
551
552static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700553gen_throw(PyGenObject *gen, PyObject *args)
554{
555 PyObject *typ;
556 PyObject *tb = NULL;
557 PyObject *val = NULL;
558
559 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
560 return NULL;
561 }
562
563 return _gen_throw(gen, 1, typ, val, tb);
564}
565
566
567static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000568gen_iternext(PyGenObject *gen)
569{
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300570 PyObject *result;
571 assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
572 if (gen_send_ex2(gen, NULL, &result, 0, 0) == PYGEN_RETURN) {
573 if (result != Py_None) {
574 _PyGen_SetStopIterationValue(result);
575 }
576 Py_CLEAR(result);
577 }
578 return result;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000579}
580
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000581/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200582 * Set StopIteration with specified value. Value can be arbitrary object
583 * or NULL.
584 *
585 * Returns 0 if StopIteration is set and -1 if any other exception is set.
586 */
587int
588_PyGen_SetStopIterationValue(PyObject *value)
589{
590 PyObject *e;
591
592 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400593 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200594 {
595 /* Delay exception instantiation if we can */
596 PyErr_SetObject(PyExc_StopIteration, value);
597 return 0;
598 }
599 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100600 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200601 *
602 * We do this to handle a situation when "value" is a tuple, in which
603 * case PyErr_SetObject would set the value of StopIteration to
604 * the first element of the tuple.
605 *
606 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
607 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100608 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200609 if (e == NULL) {
610 return -1;
611 }
612 PyErr_SetObject(PyExc_StopIteration, e);
613 Py_DECREF(e);
614 return 0;
615}
616
617/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000618 * If StopIteration exception is set, fetches its 'value'
619 * attribute if any, otherwise sets pvalue to None.
620 *
621 * Returns 0 if no exception or StopIteration is set.
622 * If any other exception is set, returns -1 and leaves
623 * pvalue unchanged.
624 */
625
626int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200627_PyGen_FetchStopIterationValue(PyObject **pvalue)
628{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000629 PyObject *et, *ev, *tb;
630 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500631
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000632 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
633 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200634 if (ev) {
635 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300636 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200637 value = ((PyStopIterationObject *)ev)->value;
638 Py_INCREF(value);
639 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200640 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
641 /* Avoid normalisation and take ev as value.
642 *
643 * Normalization is required if the value is a tuple, in
644 * that case the value of StopIteration would be set to
645 * the first element of the tuple.
646 *
647 * (See _PyErr_CreateException code for details.)
648 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200649 value = ev;
650 } else {
651 /* normalisation required */
652 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300653 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200654 PyErr_Restore(et, ev, tb);
655 return -1;
656 }
657 value = ((PyStopIterationObject *)ev)->value;
658 Py_INCREF(value);
659 Py_DECREF(ev);
660 }
661 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000662 Py_XDECREF(et);
663 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000664 } else if (PyErr_Occurred()) {
665 return -1;
666 }
667 if (value == NULL) {
668 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100669 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000670 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000671 *pvalue = value;
672 return 0;
673}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000674
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000675static PyObject *
676gen_repr(PyGenObject *gen)
677{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400678 return PyUnicode_FromFormat("<generator object %S at %p>",
679 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000680}
681
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000682static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200683gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000684{
Victor Stinner40ee3012014-06-16 15:59:28 +0200685 Py_INCREF(op->gi_name);
686 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000687}
688
Victor Stinner40ee3012014-06-16 15:59:28 +0200689static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200690gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200691{
Victor Stinner40ee3012014-06-16 15:59:28 +0200692 /* Not legal to del gen.gi_name or to set it to anything
693 * other than a string object. */
694 if (value == NULL || !PyUnicode_Check(value)) {
695 PyErr_SetString(PyExc_TypeError,
696 "__name__ must be set to a string object");
697 return -1;
698 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200699 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300700 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200701 return 0;
702}
703
704static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200705gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200706{
707 Py_INCREF(op->gi_qualname);
708 return op->gi_qualname;
709}
710
711static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200712gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200713{
Victor Stinner40ee3012014-06-16 15:59:28 +0200714 /* Not legal to del gen.__qualname__ or to set it to anything
715 * other than a string object. */
716 if (value == NULL || !PyUnicode_Check(value)) {
717 PyErr_SetString(PyExc_TypeError,
718 "__qualname__ must be set to a string object");
719 return -1;
720 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200721 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300722 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200723 return 0;
724}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000725
Yury Selivanove13f8f32015-07-03 00:23:30 -0400726static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200727gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400728{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500729 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400730 if (yf == NULL)
731 Py_RETURN_NONE;
732 return yf;
733}
734
Mark Shannoncb9879b2020-07-17 11:44:23 +0100735
736static PyObject *
737gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
738{
739 if (gen->gi_frame == NULL) {
740 Py_RETURN_FALSE;
741 }
742 return PyBool_FromLong(_PyFrame_IsExecuting(gen->gi_frame));
743}
744
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000745static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200746 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
747 PyDoc_STR("name of the generator")},
748 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
749 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400750 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
751 PyDoc_STR("object being iterated by yield from, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100752 {"gi_running", (getter)gen_getrunning, NULL, NULL},
Victor Stinner40ee3012014-06-16 15:59:28 +0200753 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000754};
755
Martin v. Löwise440e472004-06-01 15:22:42 +0000756static PyMemberDef gen_memberlist[] = {
Steve Dower87655e22021-04-30 01:08:55 +0100757 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY|PY_AUDIT_READ},
758 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY|PY_AUDIT_READ},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000760};
761
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000762static PyMethodDef gen_methods[] = {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300763 {"send",(PyCFunction)gen_send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
765 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
766 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000767};
768
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800769static PyAsyncMethods gen_as_async = {
770 0, /* am_await */
771 0, /* am_aiter */
772 0, /* am_anext */
773 (sendfunc)PyGen_am_send, /* am_send */
774};
775
776
Martin v. Löwise440e472004-06-01 15:22:42 +0000777PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyVarObject_HEAD_INIT(&PyType_Type, 0)
779 "generator", /* tp_name */
780 sizeof(PyGenObject), /* tp_basicsize */
781 0, /* tp_itemsize */
782 /* methods */
783 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200784 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 0, /* tp_getattr */
786 0, /* tp_setattr */
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800787 &gen_as_async, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 (reprfunc)gen_repr, /* tp_repr */
789 0, /* tp_as_number */
790 0, /* tp_as_sequence */
791 0, /* tp_as_mapping */
792 0, /* tp_hash */
793 0, /* tp_call */
794 0, /* tp_str */
795 PyObject_GenericGetAttr, /* tp_getattro */
796 0, /* tp_setattro */
797 0, /* tp_as_buffer */
Miss Islington (bot)632e8a62021-07-23 07:56:53 -0700798 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 0, /* tp_doc */
800 (traverseproc)gen_traverse, /* tp_traverse */
801 0, /* tp_clear */
802 0, /* tp_richcompare */
803 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400804 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 (iternextfunc)gen_iternext, /* tp_iternext */
806 gen_methods, /* tp_methods */
807 gen_memberlist, /* tp_members */
808 gen_getsetlist, /* tp_getset */
809 0, /* tp_base */
810 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 0, /* tp_descr_get */
813 0, /* tp_descr_set */
814 0, /* tp_dictoffset */
815 0, /* tp_init */
816 0, /* tp_alloc */
817 0, /* tp_new */
818 0, /* tp_free */
819 0, /* tp_is_gc */
820 0, /* tp_bases */
821 0, /* tp_mro */
822 0, /* tp_cache */
823 0, /* tp_subclasses */
824 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200825 0, /* tp_del */
826 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200827 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000828};
829
Yury Selivanov5376ba92015-06-22 12:19:30 -0400830static PyObject *
831gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
832 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000833{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400834 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (gen == NULL) {
836 Py_DECREF(f);
837 return NULL;
838 }
839 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200840 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 Py_INCREF(f->f_code);
842 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100844 gen->gi_exc_state.exc_type = NULL;
845 gen->gi_exc_state.exc_value = NULL;
846 gen->gi_exc_state.exc_traceback = NULL;
847 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200848 if (name != NULL)
849 gen->gi_name = name;
850 else
851 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
852 Py_INCREF(gen->gi_name);
853 if (qualname != NULL)
854 gen->gi_qualname = qualname;
855 else
856 gen->gi_qualname = gen->gi_name;
857 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 _PyObject_GC_TRACK(gen);
859 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000860}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861
Victor Stinner40ee3012014-06-16 15:59:28 +0200862PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400863PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
864{
865 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
866}
867
868PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200869PyGen_New(PyFrameObject *f)
870{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400871 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200872}
873
Yury Selivanov5376ba92015-06-22 12:19:30 -0400874/* Coroutine Object */
875
876typedef struct {
877 PyObject_HEAD
878 PyCoroObject *cw_coroutine;
879} PyCoroWrapper;
880
881static int
882gen_is_coroutine(PyObject *o)
883{
884 if (PyGen_CheckExact(o)) {
885 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
886 if (code->co_flags & CO_ITERABLE_COROUTINE) {
887 return 1;
888 }
889 }
890 return 0;
891}
892
Yury Selivanov75445082015-05-11 22:57:16 -0400893/*
894 * This helper function returns an awaitable for `o`:
895 * - `o` if `o` is a coroutine-object;
896 * - `type(o)->tp_as_async->am_await(o)`
897 *
898 * Raises a TypeError if it's not possible to return
899 * an awaitable and returns NULL.
900 */
901PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400902_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400903{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400904 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400905 PyTypeObject *ot;
906
Yury Selivanov5376ba92015-06-22 12:19:30 -0400907 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
908 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400909 Py_INCREF(o);
910 return o;
911 }
912
913 ot = Py_TYPE(o);
914 if (ot->tp_as_async != NULL) {
915 getter = ot->tp_as_async->am_await;
916 }
917 if (getter != NULL) {
918 PyObject *res = (*getter)(o);
919 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400920 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
921 /* __await__ must return an *iterator*, not
922 a coroutine or another awaitable (see PEP 492) */
923 PyErr_SetString(PyExc_TypeError,
924 "__await__() returned a coroutine");
925 Py_CLEAR(res);
926 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400927 PyErr_Format(PyExc_TypeError,
928 "__await__() returned non-iterator "
929 "of type '%.100s'",
930 Py_TYPE(res)->tp_name);
931 Py_CLEAR(res);
932 }
Yury Selivanov75445082015-05-11 22:57:16 -0400933 }
934 return res;
935 }
936
937 PyErr_Format(PyExc_TypeError,
938 "object %.100s can't be used in 'await' expression",
939 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400940 return NULL;
941}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400942
943static PyObject *
944coro_repr(PyCoroObject *coro)
945{
946 return PyUnicode_FromFormat("<coroutine object %S at %p>",
947 coro->cr_qualname, coro);
948}
949
950static PyObject *
951coro_await(PyCoroObject *coro)
952{
953 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
954 if (cw == NULL) {
955 return NULL;
956 }
957 Py_INCREF(coro);
958 cw->cw_coroutine = coro;
959 _PyObject_GC_TRACK(cw);
960 return (PyObject *)cw;
961}
962
Yury Selivanove13f8f32015-07-03 00:23:30 -0400963static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200964coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400965{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500966 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400967 if (yf == NULL)
968 Py_RETURN_NONE;
969 return yf;
970}
971
Mark Shannoncb9879b2020-07-17 11:44:23 +0100972static PyObject *
973cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
974{
975 if (coro->cr_frame == NULL) {
976 Py_RETURN_FALSE;
977 }
978 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
979}
980
Yury Selivanov5376ba92015-06-22 12:19:30 -0400981static PyGetSetDef coro_getsetlist[] = {
982 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
983 PyDoc_STR("name of the coroutine")},
984 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
985 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400986 {"cr_await", (getter)coro_get_cr_await, NULL,
987 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100988 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400989 {NULL} /* Sentinel */
990};
991
992static PyMemberDef coro_memberlist[] = {
Steve Dower87655e22021-04-30 01:08:55 +0100993 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY|PY_AUDIT_READ},
994 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY|PY_AUDIT_READ},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800995 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400996 {NULL} /* Sentinel */
997};
998
999PyDoc_STRVAR(coro_send_doc,
1000"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001001return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001002
1003PyDoc_STRVAR(coro_throw_doc,
1004"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001005return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001006
1007PyDoc_STRVAR(coro_close_doc,
1008"close() -> raise GeneratorExit inside coroutine.");
1009
1010static PyMethodDef coro_methods[] = {
Vladimir Matveev037245c2020-10-09 17:15:15 -07001011 {"send",(PyCFunction)gen_send, METH_O, coro_send_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001012 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1013 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1014 {NULL, NULL} /* Sentinel */
1015};
1016
1017static PyAsyncMethods coro_as_async = {
1018 (unaryfunc)coro_await, /* am_await */
1019 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001020 0, /* am_anext */
1021 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001022};
1023
1024PyTypeObject PyCoro_Type = {
1025 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1026 "coroutine", /* tp_name */
1027 sizeof(PyCoroObject), /* tp_basicsize */
1028 0, /* tp_itemsize */
1029 /* methods */
1030 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001031 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001032 0, /* tp_getattr */
1033 0, /* tp_setattr */
1034 &coro_as_async, /* tp_as_async */
1035 (reprfunc)coro_repr, /* tp_repr */
1036 0, /* tp_as_number */
1037 0, /* tp_as_sequence */
1038 0, /* tp_as_mapping */
1039 0, /* tp_hash */
1040 0, /* tp_call */
1041 0, /* tp_str */
1042 PyObject_GenericGetAttr, /* tp_getattro */
1043 0, /* tp_setattro */
1044 0, /* tp_as_buffer */
Miss Islington (bot)632e8a62021-07-23 07:56:53 -07001045 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001046 0, /* tp_doc */
1047 (traverseproc)gen_traverse, /* tp_traverse */
1048 0, /* tp_clear */
1049 0, /* tp_richcompare */
1050 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1051 0, /* tp_iter */
1052 0, /* tp_iternext */
1053 coro_methods, /* tp_methods */
1054 coro_memberlist, /* tp_members */
1055 coro_getsetlist, /* tp_getset */
1056 0, /* tp_base */
1057 0, /* tp_dict */
1058 0, /* tp_descr_get */
1059 0, /* tp_descr_set */
1060 0, /* tp_dictoffset */
1061 0, /* tp_init */
1062 0, /* tp_alloc */
1063 0, /* tp_new */
1064 0, /* tp_free */
1065 0, /* tp_is_gc */
1066 0, /* tp_bases */
1067 0, /* tp_mro */
1068 0, /* tp_cache */
1069 0, /* tp_subclasses */
1070 0, /* tp_weaklist */
1071 0, /* tp_del */
1072 0, /* tp_version_tag */
1073 _PyGen_Finalize, /* tp_finalize */
1074};
1075
1076static void
1077coro_wrapper_dealloc(PyCoroWrapper *cw)
1078{
1079 _PyObject_GC_UNTRACK((PyObject *)cw);
1080 Py_CLEAR(cw->cw_coroutine);
1081 PyObject_GC_Del(cw);
1082}
1083
1084static PyObject *
1085coro_wrapper_iternext(PyCoroWrapper *cw)
1086{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001087 return gen_iternext((PyGenObject *)cw->cw_coroutine);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001088}
1089
1090static PyObject *
1091coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1092{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001093 return gen_send((PyGenObject *)cw->cw_coroutine, arg);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001094}
1095
1096static PyObject *
1097coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1098{
1099 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1100}
1101
1102static PyObject *
1103coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1104{
1105 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1106}
1107
1108static int
1109coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1110{
1111 Py_VISIT((PyObject *)cw->cw_coroutine);
1112 return 0;
1113}
1114
1115static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001116 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1117 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1118 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001119 {NULL, NULL} /* Sentinel */
1120};
1121
1122PyTypeObject _PyCoroWrapper_Type = {
1123 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1124 "coroutine_wrapper",
1125 sizeof(PyCoroWrapper), /* tp_basicsize */
1126 0, /* tp_itemsize */
1127 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001128 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001129 0, /* tp_getattr */
1130 0, /* tp_setattr */
1131 0, /* tp_as_async */
1132 0, /* tp_repr */
1133 0, /* tp_as_number */
1134 0, /* tp_as_sequence */
1135 0, /* tp_as_mapping */
1136 0, /* tp_hash */
1137 0, /* tp_call */
1138 0, /* tp_str */
1139 PyObject_GenericGetAttr, /* tp_getattro */
1140 0, /* tp_setattro */
1141 0, /* tp_as_buffer */
1142 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1143 "A wrapper object implementing __await__ for coroutines.",
1144 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1145 0, /* tp_clear */
1146 0, /* tp_richcompare */
1147 0, /* tp_weaklistoffset */
1148 PyObject_SelfIter, /* tp_iter */
1149 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1150 coro_wrapper_methods, /* tp_methods */
1151 0, /* tp_members */
1152 0, /* tp_getset */
1153 0, /* tp_base */
1154 0, /* tp_dict */
1155 0, /* tp_descr_get */
1156 0, /* tp_descr_set */
1157 0, /* tp_dictoffset */
1158 0, /* tp_init */
1159 0, /* tp_alloc */
1160 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001161 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001162};
1163
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001164static PyObject *
1165compute_cr_origin(int origin_depth)
1166{
1167 PyFrameObject *frame = PyEval_GetFrame();
1168 /* First count how many frames we have */
1169 int frame_count = 0;
1170 for (; frame && frame_count < origin_depth; ++frame_count) {
1171 frame = frame->f_back;
1172 }
1173
1174 /* Now collect them */
1175 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001176 if (cr_origin == NULL) {
1177 return NULL;
1178 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001179 frame = PyEval_GetFrame();
1180 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001181 PyCodeObject *code = frame->f_code;
1182 PyObject *frameinfo = Py_BuildValue("OiO",
1183 code->co_filename,
1184 PyFrame_GetLineNumber(frame),
1185 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001186 if (!frameinfo) {
1187 Py_DECREF(cr_origin);
1188 return NULL;
1189 }
1190 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1191 frame = frame->f_back;
1192 }
1193
1194 return cr_origin;
1195}
1196
Yury Selivanov5376ba92015-06-22 12:19:30 -04001197PyObject *
1198PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1199{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001200 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1201 if (!coro) {
1202 return NULL;
1203 }
1204
Victor Stinner50b48572018-11-01 01:51:40 +01001205 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001206 int origin_depth = tstate->coroutine_origin_tracking_depth;
1207
1208 if (origin_depth == 0) {
1209 ((PyCoroObject *)coro)->cr_origin = NULL;
1210 } else {
1211 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001212 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001213 if (!cr_origin) {
1214 Py_DECREF(coro);
1215 return NULL;
1216 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001217 }
1218
1219 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001220}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001221
1222
Yury Selivanoveb636452016-09-08 22:01:51 -07001223/* ========= Asynchronous Generators ========= */
1224
1225
1226typedef enum {
1227 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1228 AWAITABLE_STATE_ITER, /* being iterated */
1229 AWAITABLE_STATE_CLOSED, /* closed */
1230} AwaitableState;
1231
1232
Victor Stinner78a02c22020-06-05 02:34:14 +02001233typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001234 PyObject_HEAD
1235 PyAsyncGenObject *ags_gen;
1236
1237 /* Can be NULL, when in the __anext__() mode
1238 (equivalent of "asend(None)") */
1239 PyObject *ags_sendval;
1240
1241 AwaitableState ags_state;
1242} PyAsyncGenASend;
1243
1244
Victor Stinner78a02c22020-06-05 02:34:14 +02001245typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001246 PyObject_HEAD
1247 PyAsyncGenObject *agt_gen;
1248
1249 /* Can be NULL, when in the "aclose()" mode
1250 (equivalent of "athrow(GeneratorExit)") */
1251 PyObject *agt_args;
1252
1253 AwaitableState agt_state;
1254} PyAsyncGenAThrow;
1255
1256
Victor Stinner78a02c22020-06-05 02:34:14 +02001257typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001258 PyObject_HEAD
1259 PyObject *agw_val;
1260} _PyAsyncGenWrappedValue;
1261
1262
Yury Selivanoveb636452016-09-08 22:01:51 -07001263#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001264 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001265
1266#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001267 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001268
1269
1270static int
1271async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1272{
1273 Py_VISIT(gen->ag_finalizer);
1274 return gen_traverse((PyGenObject*)gen, visit, arg);
1275}
1276
1277
1278static PyObject *
1279async_gen_repr(PyAsyncGenObject *o)
1280{
1281 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1282 o->ag_qualname, o);
1283}
1284
1285
1286static int
1287async_gen_init_hooks(PyAsyncGenObject *o)
1288{
1289 PyThreadState *tstate;
1290 PyObject *finalizer;
1291 PyObject *firstiter;
1292
1293 if (o->ag_hooks_inited) {
1294 return 0;
1295 }
1296
1297 o->ag_hooks_inited = 1;
1298
Victor Stinner50b48572018-11-01 01:51:40 +01001299 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001300
1301 finalizer = tstate->async_gen_finalizer;
1302 if (finalizer) {
1303 Py_INCREF(finalizer);
1304 o->ag_finalizer = finalizer;
1305 }
1306
1307 firstiter = tstate->async_gen_firstiter;
1308 if (firstiter) {
1309 PyObject *res;
1310
1311 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001312 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001313 Py_DECREF(firstiter);
1314 if (res == NULL) {
1315 return 1;
1316 }
1317 Py_DECREF(res);
1318 }
1319
1320 return 0;
1321}
1322
1323
1324static PyObject *
1325async_gen_anext(PyAsyncGenObject *o)
1326{
1327 if (async_gen_init_hooks(o)) {
1328 return NULL;
1329 }
1330 return async_gen_asend_new(o, NULL);
1331}
1332
1333
1334static PyObject *
1335async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1336{
1337 if (async_gen_init_hooks(o)) {
1338 return NULL;
1339 }
1340 return async_gen_asend_new(o, arg);
1341}
1342
1343
1344static PyObject *
1345async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1346{
1347 if (async_gen_init_hooks(o)) {
1348 return NULL;
1349 }
1350 return async_gen_athrow_new(o, NULL);
1351}
1352
1353static PyObject *
1354async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1355{
1356 if (async_gen_init_hooks(o)) {
1357 return NULL;
1358 }
1359 return async_gen_athrow_new(o, args);
1360}
1361
1362
1363static PyGetSetDef async_gen_getsetlist[] = {
1364 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1365 PyDoc_STR("name of the async generator")},
1366 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1367 PyDoc_STR("qualified name of the async generator")},
1368 {"ag_await", (getter)coro_get_cr_await, NULL,
1369 PyDoc_STR("object being awaited on, or None")},
1370 {NULL} /* Sentinel */
1371};
1372
1373static PyMemberDef async_gen_memberlist[] = {
Steve Dower87655e22021-04-30 01:08:55 +01001374 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY|PY_AUDIT_READ},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001375 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1376 READONLY},
Steve Dower87655e22021-04-30 01:08:55 +01001377 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY|PY_AUDIT_READ},
Yury Selivanoveb636452016-09-08 22:01:51 -07001378 {NULL} /* Sentinel */
1379};
1380
1381PyDoc_STRVAR(async_aclose_doc,
1382"aclose() -> raise GeneratorExit inside generator.");
1383
1384PyDoc_STRVAR(async_asend_doc,
1385"asend(v) -> send 'v' in generator.");
1386
1387PyDoc_STRVAR(async_athrow_doc,
1388"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1389
1390static PyMethodDef async_gen_methods[] = {
1391 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1392 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1393 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001394 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1395 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001396 {NULL, NULL} /* Sentinel */
1397};
1398
1399
1400static PyAsyncMethods async_gen_as_async = {
1401 0, /* am_await */
1402 PyObject_SelfIter, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001403 (unaryfunc)async_gen_anext, /* am_anext */
1404 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001405};
1406
1407
1408PyTypeObject PyAsyncGen_Type = {
1409 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1410 "async_generator", /* tp_name */
1411 sizeof(PyAsyncGenObject), /* tp_basicsize */
1412 0, /* tp_itemsize */
1413 /* methods */
1414 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001415 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001416 0, /* tp_getattr */
1417 0, /* tp_setattr */
1418 &async_gen_as_async, /* tp_as_async */
1419 (reprfunc)async_gen_repr, /* tp_repr */
1420 0, /* tp_as_number */
1421 0, /* tp_as_sequence */
1422 0, /* tp_as_mapping */
1423 0, /* tp_hash */
1424 0, /* tp_call */
1425 0, /* tp_str */
1426 PyObject_GenericGetAttr, /* tp_getattro */
1427 0, /* tp_setattro */
1428 0, /* tp_as_buffer */
Miss Islington (bot)632e8a62021-07-23 07:56:53 -07001429 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001430 0, /* tp_doc */
1431 (traverseproc)async_gen_traverse, /* tp_traverse */
1432 0, /* tp_clear */
1433 0, /* tp_richcompare */
1434 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1435 0, /* tp_iter */
1436 0, /* tp_iternext */
1437 async_gen_methods, /* tp_methods */
1438 async_gen_memberlist, /* tp_members */
1439 async_gen_getsetlist, /* tp_getset */
1440 0, /* tp_base */
1441 0, /* tp_dict */
1442 0, /* tp_descr_get */
1443 0, /* tp_descr_set */
1444 0, /* tp_dictoffset */
1445 0, /* tp_init */
1446 0, /* tp_alloc */
1447 0, /* tp_new */
1448 0, /* tp_free */
1449 0, /* tp_is_gc */
1450 0, /* tp_bases */
1451 0, /* tp_mro */
1452 0, /* tp_cache */
1453 0, /* tp_subclasses */
1454 0, /* tp_weaklist */
1455 0, /* tp_del */
1456 0, /* tp_version_tag */
1457 _PyGen_Finalize, /* tp_finalize */
1458};
1459
1460
Victor Stinner522691c2020-06-23 16:40:40 +02001461static struct _Py_async_gen_state *
1462get_async_gen_state(void)
1463{
1464 PyInterpreterState *interp = _PyInterpreterState_GET();
1465 return &interp->async_gen;
1466}
1467
1468
Yury Selivanoveb636452016-09-08 22:01:51 -07001469PyObject *
1470PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1471{
1472 PyAsyncGenObject *o;
1473 o = (PyAsyncGenObject *)gen_new_with_qualname(
1474 &PyAsyncGen_Type, f, name, qualname);
1475 if (o == NULL) {
1476 return NULL;
1477 }
1478 o->ag_finalizer = NULL;
1479 o->ag_closed = 0;
1480 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001481 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001482 return (PyObject*)o;
1483}
1484
1485
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001486void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001487_PyAsyncGen_ClearFreeLists(PyInterpreterState *interp)
Yury Selivanoveb636452016-09-08 22:01:51 -07001488{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001489 struct _Py_async_gen_state *state = &interp->async_gen;
Victor Stinner78a02c22020-06-05 02:34:14 +02001490
1491 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001492 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001493 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001494 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001495 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001496 }
1497
Victor Stinner78a02c22020-06-05 02:34:14 +02001498 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001499 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001500 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001501 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001502 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001503 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001504}
1505
1506void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001507_PyAsyncGen_Fini(PyInterpreterState *interp)
Yury Selivanoveb636452016-09-08 22:01:51 -07001508{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001509 _PyAsyncGen_ClearFreeLists(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001510#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001511 struct _Py_async_gen_state *state = &interp->async_gen;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001512 state->value_numfree = -1;
1513 state->asend_numfree = -1;
1514#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001515}
1516
1517
1518static PyObject *
1519async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1520{
1521 if (result == NULL) {
1522 if (!PyErr_Occurred()) {
1523 PyErr_SetNone(PyExc_StopAsyncIteration);
1524 }
1525
1526 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1527 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1528 ) {
1529 gen->ag_closed = 1;
1530 }
1531
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001532 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001533 return NULL;
1534 }
1535
1536 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1537 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001538 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001539 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001540 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001541 return NULL;
1542 }
1543
1544 return result;
1545}
1546
1547
1548/* ---------- Async Generator ASend Awaitable ------------ */
1549
1550
1551static void
1552async_gen_asend_dealloc(PyAsyncGenASend *o)
1553{
Yury Selivanov29310c42016-11-08 19:46:22 -05001554 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001555 Py_CLEAR(o->ags_gen);
1556 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001557 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001558#ifdef Py_DEBUG
1559 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1560 assert(state->asend_numfree != -1);
1561#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001562 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001563 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001564 state->asend_freelist[state->asend_numfree++] = o;
1565 }
1566 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001567 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001568 }
1569}
1570
Yury Selivanov29310c42016-11-08 19:46:22 -05001571static int
1572async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1573{
1574 Py_VISIT(o->ags_gen);
1575 Py_VISIT(o->ags_sendval);
1576 return 0;
1577}
1578
Yury Selivanoveb636452016-09-08 22:01:51 -07001579
1580static PyObject *
1581async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1582{
1583 PyObject *result;
1584
1585 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001586 PyErr_SetString(
1587 PyExc_RuntimeError,
1588 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001589 return NULL;
1590 }
1591
1592 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001593 if (o->ags_gen->ag_running_async) {
1594 PyErr_SetString(
1595 PyExc_RuntimeError,
1596 "anext(): asynchronous generator is already running");
1597 return NULL;
1598 }
1599
Yury Selivanoveb636452016-09-08 22:01:51 -07001600 if (arg == NULL || arg == Py_None) {
1601 arg = o->ags_sendval;
1602 }
1603 o->ags_state = AWAITABLE_STATE_ITER;
1604 }
1605
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001606 o->ags_gen->ag_running_async = 1;
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001607 result = gen_send((PyGenObject*)o->ags_gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001608 result = async_gen_unwrap_value(o->ags_gen, result);
1609
1610 if (result == NULL) {
1611 o->ags_state = AWAITABLE_STATE_CLOSED;
1612 }
1613
1614 return result;
1615}
1616
1617
1618static PyObject *
1619async_gen_asend_iternext(PyAsyncGenASend *o)
1620{
1621 return async_gen_asend_send(o, NULL);
1622}
1623
1624
1625static PyObject *
1626async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1627{
1628 PyObject *result;
1629
1630 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001631 PyErr_SetString(
1632 PyExc_RuntimeError,
1633 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001634 return NULL;
1635 }
1636
1637 result = gen_throw((PyGenObject*)o->ags_gen, args);
1638 result = async_gen_unwrap_value(o->ags_gen, result);
1639
1640 if (result == NULL) {
1641 o->ags_state = AWAITABLE_STATE_CLOSED;
1642 }
1643
1644 return result;
1645}
1646
1647
1648static PyObject *
1649async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1650{
1651 o->ags_state = AWAITABLE_STATE_CLOSED;
1652 Py_RETURN_NONE;
1653}
1654
1655
1656static PyMethodDef async_gen_asend_methods[] = {
1657 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1658 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1659 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1660 {NULL, NULL} /* Sentinel */
1661};
1662
1663
1664static PyAsyncMethods async_gen_asend_as_async = {
1665 PyObject_SelfIter, /* am_await */
1666 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001667 0, /* am_anext */
1668 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001669};
1670
1671
1672PyTypeObject _PyAsyncGenASend_Type = {
1673 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1674 "async_generator_asend", /* tp_name */
1675 sizeof(PyAsyncGenASend), /* tp_basicsize */
1676 0, /* tp_itemsize */
1677 /* methods */
1678 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001679 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001680 0, /* tp_getattr */
1681 0, /* tp_setattr */
1682 &async_gen_asend_as_async, /* tp_as_async */
1683 0, /* tp_repr */
1684 0, /* tp_as_number */
1685 0, /* tp_as_sequence */
1686 0, /* tp_as_mapping */
1687 0, /* tp_hash */
1688 0, /* tp_call */
1689 0, /* tp_str */
1690 PyObject_GenericGetAttr, /* tp_getattro */
1691 0, /* tp_setattro */
1692 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001693 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001694 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001695 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001696 0, /* tp_clear */
1697 0, /* tp_richcompare */
1698 0, /* tp_weaklistoffset */
1699 PyObject_SelfIter, /* tp_iter */
1700 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1701 async_gen_asend_methods, /* tp_methods */
1702 0, /* tp_members */
1703 0, /* tp_getset */
1704 0, /* tp_base */
1705 0, /* tp_dict */
1706 0, /* tp_descr_get */
1707 0, /* tp_descr_set */
1708 0, /* tp_dictoffset */
1709 0, /* tp_init */
1710 0, /* tp_alloc */
1711 0, /* tp_new */
1712};
1713
1714
1715static PyObject *
1716async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1717{
1718 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001719 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001720#ifdef Py_DEBUG
1721 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1722 assert(state->asend_numfree != -1);
1723#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001724 if (state->asend_numfree) {
1725 state->asend_numfree--;
1726 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001727 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001728 }
1729 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001730 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001731 if (o == NULL) {
1732 return NULL;
1733 }
1734 }
1735
1736 Py_INCREF(gen);
1737 o->ags_gen = gen;
1738
1739 Py_XINCREF(sendval);
1740 o->ags_sendval = sendval;
1741
1742 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001743
1744 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001745 return (PyObject*)o;
1746}
1747
1748
1749/* ---------- Async Generator Value Wrapper ------------ */
1750
1751
1752static void
1753async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1754{
Yury Selivanov29310c42016-11-08 19:46:22 -05001755 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001756 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001757 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001758#ifdef Py_DEBUG
1759 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1760 assert(state->value_numfree != -1);
1761#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001762 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001763 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001764 state->value_freelist[state->value_numfree++] = o;
1765 }
1766 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001767 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001768 }
1769}
1770
1771
Yury Selivanov29310c42016-11-08 19:46:22 -05001772static int
1773async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1774 visitproc visit, void *arg)
1775{
1776 Py_VISIT(o->agw_val);
1777 return 0;
1778}
1779
1780
Yury Selivanoveb636452016-09-08 22:01:51 -07001781PyTypeObject _PyAsyncGenWrappedValue_Type = {
1782 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1783 "async_generator_wrapped_value", /* tp_name */
1784 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1785 0, /* tp_itemsize */
1786 /* methods */
1787 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001788 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001789 0, /* tp_getattr */
1790 0, /* tp_setattr */
1791 0, /* tp_as_async */
1792 0, /* tp_repr */
1793 0, /* tp_as_number */
1794 0, /* tp_as_sequence */
1795 0, /* tp_as_mapping */
1796 0, /* tp_hash */
1797 0, /* tp_call */
1798 0, /* tp_str */
1799 PyObject_GenericGetAttr, /* tp_getattro */
1800 0, /* tp_setattro */
1801 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001802 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001803 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001804 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001805 0, /* tp_clear */
1806 0, /* tp_richcompare */
1807 0, /* tp_weaklistoffset */
1808 0, /* tp_iter */
1809 0, /* tp_iternext */
1810 0, /* tp_methods */
1811 0, /* tp_members */
1812 0, /* tp_getset */
1813 0, /* tp_base */
1814 0, /* tp_dict */
1815 0, /* tp_descr_get */
1816 0, /* tp_descr_set */
1817 0, /* tp_dictoffset */
1818 0, /* tp_init */
1819 0, /* tp_alloc */
1820 0, /* tp_new */
1821};
1822
1823
1824PyObject *
1825_PyAsyncGenValueWrapperNew(PyObject *val)
1826{
1827 _PyAsyncGenWrappedValue *o;
1828 assert(val);
1829
Victor Stinner522691c2020-06-23 16:40:40 +02001830 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001831#ifdef Py_DEBUG
1832 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1833 assert(state->value_numfree != -1);
1834#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001835 if (state->value_numfree) {
1836 state->value_numfree--;
1837 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001838 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1839 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001840 }
1841 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001842 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1843 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001844 if (o == NULL) {
1845 return NULL;
1846 }
1847 }
1848 o->agw_val = val;
1849 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001850 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001851 return (PyObject*)o;
1852}
1853
1854
1855/* ---------- Async Generator AThrow awaitable ------------ */
1856
1857
1858static void
1859async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1860{
Yury Selivanov29310c42016-11-08 19:46:22 -05001861 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001862 Py_CLEAR(o->agt_gen);
1863 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001864 PyObject_GC_Del(o);
1865}
1866
1867
1868static int
1869async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1870{
1871 Py_VISIT(o->agt_gen);
1872 Py_VISIT(o->agt_args);
1873 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001874}
1875
1876
1877static PyObject *
1878async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1879{
1880 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1881 PyFrameObject *f = gen->gi_frame;
1882 PyObject *retval;
1883
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001884 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001885 PyErr_SetString(
1886 PyExc_RuntimeError,
1887 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001888 return NULL;
1889 }
1890
Mark Shannoncb9879b2020-07-17 11:44:23 +01001891 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001892 o->agt_state = AWAITABLE_STATE_CLOSED;
1893 PyErr_SetNone(PyExc_StopIteration);
1894 return NULL;
1895 }
1896
Yury Selivanoveb636452016-09-08 22:01:51 -07001897 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001898 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001899 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001900 if (o->agt_args == NULL) {
1901 PyErr_SetString(
1902 PyExc_RuntimeError,
1903 "aclose(): asynchronous generator is already running");
1904 }
1905 else {
1906 PyErr_SetString(
1907 PyExc_RuntimeError,
1908 "athrow(): asynchronous generator is already running");
1909 }
1910 return NULL;
1911 }
1912
Yury Selivanoveb636452016-09-08 22:01:51 -07001913 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001914 o->agt_state = AWAITABLE_STATE_CLOSED;
1915 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001916 return NULL;
1917 }
1918
1919 if (arg != Py_None) {
1920 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1921 return NULL;
1922 }
1923
1924 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001925 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001926
1927 if (o->agt_args == NULL) {
1928 /* aclose() mode */
1929 o->agt_gen->ag_closed = 1;
1930
1931 retval = _gen_throw((PyGenObject *)gen,
1932 0, /* Do not close generator when
1933 PyExc_GeneratorExit is passed */
1934 PyExc_GeneratorExit, NULL, NULL);
1935
1936 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1937 Py_DECREF(retval);
1938 goto yield_close;
1939 }
1940 } else {
1941 PyObject *typ;
1942 PyObject *tb = NULL;
1943 PyObject *val = NULL;
1944
1945 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1946 &typ, &val, &tb)) {
1947 return NULL;
1948 }
1949
1950 retval = _gen_throw((PyGenObject *)gen,
1951 0, /* Do not close generator when
1952 PyExc_GeneratorExit is passed */
1953 typ, val, tb);
1954 retval = async_gen_unwrap_value(o->agt_gen, retval);
1955 }
1956 if (retval == NULL) {
1957 goto check_error;
1958 }
1959 return retval;
1960 }
1961
1962 assert(o->agt_state == AWAITABLE_STATE_ITER);
1963
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001964 retval = gen_send((PyGenObject *)gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001965 if (o->agt_args) {
1966 return async_gen_unwrap_value(o->agt_gen, retval);
1967 } else {
1968 /* aclose() mode */
1969 if (retval) {
1970 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1971 Py_DECREF(retval);
1972 goto yield_close;
1973 }
1974 else {
1975 return retval;
1976 }
1977 }
1978 else {
1979 goto check_error;
1980 }
1981 }
1982
1983yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001984 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001985 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001986 PyErr_SetString(
1987 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1988 return NULL;
1989
1990check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001991 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001992 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001993 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1994 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1995 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001996 if (o->agt_args == NULL) {
1997 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001998 StopAsyncIteration or GeneratorExit; just raise
1999 StopIteration, signalling that this 'aclose()' await
2000 is done.
2001 */
Yury Selivanov41782e42016-11-16 18:16:17 -05002002 PyErr_Clear();
2003 PyErr_SetNone(PyExc_StopIteration);
2004 }
2005 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002006 return NULL;
2007}
2008
2009
2010static PyObject *
2011async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
2012{
2013 PyObject *retval;
2014
Yury Selivanoveb636452016-09-08 22:01:51 -07002015 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02002016 PyErr_SetString(
2017 PyExc_RuntimeError,
2018 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07002019 return NULL;
2020 }
2021
2022 retval = gen_throw((PyGenObject*)o->agt_gen, args);
2023 if (o->agt_args) {
2024 return async_gen_unwrap_value(o->agt_gen, retval);
2025 } else {
2026 /* aclose() mode */
2027 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002028 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002029 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07002030 Py_DECREF(retval);
2031 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2032 return NULL;
2033 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08002034 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2035 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2036 {
2037 /* when aclose() is called we don't want to propagate
2038 StopAsyncIteration or GeneratorExit; just raise
2039 StopIteration, signalling that this 'aclose()' await
2040 is done.
2041 */
2042 PyErr_Clear();
2043 PyErr_SetNone(PyExc_StopIteration);
2044 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002045 return retval;
2046 }
2047}
2048
2049
2050static PyObject *
2051async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2052{
2053 return async_gen_athrow_send(o, Py_None);
2054}
2055
2056
2057static PyObject *
2058async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2059{
2060 o->agt_state = AWAITABLE_STATE_CLOSED;
2061 Py_RETURN_NONE;
2062}
2063
2064
2065static PyMethodDef async_gen_athrow_methods[] = {
2066 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2067 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2068 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2069 {NULL, NULL} /* Sentinel */
2070};
2071
2072
2073static PyAsyncMethods async_gen_athrow_as_async = {
2074 PyObject_SelfIter, /* am_await */
2075 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08002076 0, /* am_anext */
2077 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07002078};
2079
2080
2081PyTypeObject _PyAsyncGenAThrow_Type = {
2082 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2083 "async_generator_athrow", /* tp_name */
2084 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2085 0, /* tp_itemsize */
2086 /* methods */
2087 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002088 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002089 0, /* tp_getattr */
2090 0, /* tp_setattr */
2091 &async_gen_athrow_as_async, /* tp_as_async */
2092 0, /* tp_repr */
2093 0, /* tp_as_number */
2094 0, /* tp_as_sequence */
2095 0, /* tp_as_mapping */
2096 0, /* tp_hash */
2097 0, /* tp_call */
2098 0, /* tp_str */
2099 PyObject_GenericGetAttr, /* tp_getattro */
2100 0, /* tp_setattro */
2101 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002102 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002103 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002104 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002105 0, /* tp_clear */
2106 0, /* tp_richcompare */
2107 0, /* tp_weaklistoffset */
2108 PyObject_SelfIter, /* tp_iter */
2109 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2110 async_gen_athrow_methods, /* tp_methods */
2111 0, /* tp_members */
2112 0, /* tp_getset */
2113 0, /* tp_base */
2114 0, /* tp_dict */
2115 0, /* tp_descr_get */
2116 0, /* tp_descr_set */
2117 0, /* tp_dictoffset */
2118 0, /* tp_init */
2119 0, /* tp_alloc */
2120 0, /* tp_new */
2121};
2122
2123
2124static PyObject *
2125async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2126{
2127 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002128 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002129 if (o == NULL) {
2130 return NULL;
2131 }
2132 o->agt_gen = gen;
2133 o->agt_args = args;
2134 o->agt_state = AWAITABLE_STATE_INIT;
2135 Py_INCREF(gen);
2136 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002137 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002138 return (PyObject*)o;
2139}