blob: f0943ae847c5438b487c7fc5a69eee6e8796a629 [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 Shannoncb9879b2020-07-17 11:44:23 +0100148 if (f != NULL && _PyFrame_IsExecuting(f)) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200149 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700150 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400151 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700152 }
153 else if (PyAsyncGen_CheckExact(gen)) {
154 msg = "async generator already executing";
155 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400156 PyErr_SetString(PyExc_ValueError, msg);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300157 return PYGEN_ERROR;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500158 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100159 if (f == NULL || _PyFrameHasCompleted(f)) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500160 if (PyCoro_CheckExact(gen) && !closing) {
161 /* `gen` is an exhausted coroutine: raise an error,
162 except when called from gen_close(), which should
163 always be a silent method. */
164 PyErr_SetString(
165 PyExc_RuntimeError,
166 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700167 }
168 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500169 /* `gen` is an exhausted generator:
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300170 only return value if called from send(). */
171 *presult = Py_None;
172 Py_INCREF(*presult);
173 return PYGEN_RETURN;
Yury Selivanov77c96812016-02-13 17:59:05 -0500174 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300175 return PYGEN_ERROR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000177
Mark Shannoncb9879b2020-07-17 11:44:23 +0100178 assert(_PyFrame_IsRunnable(f));
Antoine Pitrou93963562013-05-14 20:37:52 +0200179 if (f->f_lasti == -1) {
180 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200181 const char *msg = "can't send non-None value to a "
182 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700183 if (PyCoro_CheckExact(gen)) {
184 msg = NON_INIT_CORO_MSG;
185 }
186 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400187 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700188 "just-started async generator";
189 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400190 PyErr_SetString(PyExc_TypeError, msg);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300191 return PYGEN_ERROR;
Antoine Pitrou93963562013-05-14 20:37:52 +0200192 }
193 } else {
194 /* Push arg onto the frame's value stack */
195 result = arg ? arg : Py_None;
196 Py_INCREF(result);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100197 gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth] = result;
198 gen->gi_frame->f_stackdepth++;
Antoine Pitrou93963562013-05-14 20:37:52 +0200199 }
200
201 /* Generators always return to their most recent caller, not
202 * necessarily their creator. */
203 Py_XINCREF(tstate->frame);
204 assert(f->f_back == NULL);
205 f->f_back = tstate->frame;
206
Mark Shannonae3087c2017-10-22 22:41:51 +0100207 gen->gi_exc_state.previous_item = tstate->exc_info;
208 tstate->exc_info = &gen->gi_exc_state;
Chris Jerdonek7c30d122020-05-22 13:33:27 -0700209
210 if (exc) {
211 assert(_PyErr_Occurred(tstate));
212 _PyErr_ChainStackItem(NULL);
213 }
214
Victor Stinnerb9e68122019-11-14 12:20:46 +0100215 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100216 tstate->exc_info = gen->gi_exc_state.previous_item;
217 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200218
219 /* Don't keep the reference to f_back any longer than necessary. It
220 * may keep a chain of frames alive or it could create a reference
221 * cycle. */
222 assert(f->f_back == tstate->frame);
223 Py_CLEAR(f->f_back);
224
225 /* If the generator just returned (as opposed to yielding), signal
226 * that the generator is exhausted. */
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300227 if (result) {
228 if (!_PyFrameHasCompleted(f)) {
229 *presult = result;
230 return PYGEN_NEXT;
231 }
232 assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
233 if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
234 /* Return NULL if called by gen_iternext() */
235 Py_CLEAR(result);
236 }
237 }
238 else {
239 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
240 const char *msg = "generator raised StopIteration";
241 if (PyCoro_CheckExact(gen)) {
242 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700243 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300244 else if (PyAsyncGen_CheckExact(gen)) {
245 msg = "async generator raised StopIteration";
Vladimir Matveev2b053612020-09-18 18:38:38 -0700246 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300247 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
248 }
249 else if (PyAsyncGen_CheckExact(gen) &&
250 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
251 {
252 /* code in `gen` raised a StopAsyncIteration error:
253 raise a RuntimeError.
254 */
255 const char *msg = "async generator raised StopAsyncIteration";
256 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
257 }
258 }
259
260 /* generator can't be rerun, so release the frame */
261 /* first clean reference cycle through stored exception traceback */
262 _PyErr_ClearExcState(&gen->gi_exc_state);
263 gen->gi_frame->f_gen = NULL;
264 gen->gi_frame = NULL;
265 Py_DECREF(f);
266
267 *presult = result;
268 return result ? PYGEN_RETURN : PYGEN_ERROR;
269}
270
271PySendResult
272PyGen_Send(PyGenObject *gen, PyObject *arg, PyObject **result)
273{
274 assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
275 assert(result != NULL);
276 assert(arg != NULL);
277
278 return gen_send_ex2(gen, arg, result, 0, 0);
279}
280
281static PyObject *
282gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
283{
284 PyObject *result;
285 if (gen_send_ex2(gen, arg, &result, exc, closing) == PYGEN_RETURN) {
286 if (PyAsyncGen_CheckExact(gen)) {
287 assert(result == Py_None);
288 PyErr_SetNone(PyExc_StopAsyncIteration);
289 }
290 else if (result == Py_None) {
291 PyErr_SetNone(PyExc_StopIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -0700292 }
293 else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300294 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200295 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300296 Py_CLEAR(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200297 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200298 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000299}
300
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000301PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000302"send(arg) -> send 'arg' into generator,\n\
303return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000304
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300305static PyObject *
306gen_send(PyGenObject *gen, PyObject *arg)
307{
308 return gen_send_ex(gen, arg, 0, 0);
309}
310
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500311PyObject *
312_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000313{
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300314 return gen_send(gen, arg);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000315}
316
317PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400318"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000319
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000320/*
321 * This helper function is used by gen_close and gen_throw to
322 * close a subiterator being delegated to by yield-from.
323 */
324
Antoine Pitrou93963562013-05-14 20:37:52 +0200325static int
326gen_close_iter(PyObject *yf)
327{
328 PyObject *retval = NULL;
329 _Py_IDENTIFIER(close);
330
Yury Selivanoveb636452016-09-08 22:01:51 -0700331 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200332 retval = gen_close((PyGenObject *)yf, NULL);
333 if (retval == NULL)
334 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700335 }
336 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200337 PyObject *meth;
338 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
339 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700340 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200341 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700342 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200343 Py_DECREF(meth);
344 if (retval == NULL)
345 return -1;
346 }
347 }
348 Py_XDECREF(retval);
349 return 0;
350}
351
Yury Selivanovc724bae2016-03-02 11:30:46 -0500352PyObject *
353_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500354{
Antoine Pitrou93963562013-05-14 20:37:52 +0200355 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500356 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200357
Mark Shannoncb9879b2020-07-17 11:44:23 +0100358 if (f) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200359 PyObject *bytecode = f->f_code->co_code;
360 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
361
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100362 if (f->f_lasti < 0) {
363 /* Return immediately if the frame didn't start yet. YIELD_FROM
364 always come after LOAD_CONST: a code object should not start
365 with YIELD_FROM */
366 assert(code[0] != YIELD_FROM);
367 return NULL;
368 }
369
Serhiy Storchakaab874002016-09-11 13:48:15 +0300370 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200371 return NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100372 assert(f->f_stackdepth > 0);
373 yf = f->f_valuestack[f->f_stackdepth-1];
Antoine Pitrou93963562013-05-14 20:37:52 +0200374 Py_INCREF(yf);
375 }
376
377 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500378}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000379
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000380static PyObject *
381gen_close(PyGenObject *gen, PyObject *args)
382{
Antoine Pitrou93963562013-05-14 20:37:52 +0200383 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500384 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200385 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000386
Antoine Pitrou93963562013-05-14 20:37:52 +0200387 if (yf) {
Mark Shannoncb9879b2020-07-17 11:44:23 +0100388 PyFrameState state = gen->gi_frame->f_state;
389 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200390 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100391 gen->gi_frame->f_state = state;
Antoine Pitrou93963562013-05-14 20:37:52 +0200392 Py_DECREF(yf);
393 }
394 if (err == 0)
395 PyErr_SetNone(PyExc_GeneratorExit);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300396 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200397 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200398 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700399 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400400 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700401 } else if (PyAsyncGen_CheckExact(gen)) {
402 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
403 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200404 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400405 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return NULL;
407 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200408 if (PyErr_ExceptionMatches(PyExc_StopIteration)
409 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
410 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200411 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200412 }
413 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000414}
415
Antoine Pitrou93963562013-05-14 20:37:52 +0200416
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000417PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
419return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000420
421static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700422_gen_throw(PyGenObject *gen, int close_on_genexit,
423 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000424{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500425 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000426 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000427
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000428 if (yf) {
429 PyObject *ret;
430 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700431 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
432 close_on_genexit
433 ) {
434 /* Asynchronous generators *should not* be closed right away.
435 We have to allow some awaits to work it through, hence the
436 `close_on_genexit` parameter here.
437 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100438 PyFrameState state = gen->gi_frame->f_state;
439 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200440 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100441 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000442 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000443 if (err < 0)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300444 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000445 goto throw_here;
446 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700447 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
448 /* `yf` is a generator or a coroutine. */
Chris Jerdonek8b339612020-07-09 06:27:23 -0700449 PyThreadState *tstate = _PyThreadState_GET();
450 PyFrameObject *f = tstate->frame;
451
Chris Jerdonek8b339612020-07-09 06:27:23 -0700452 /* Since we are fast-tracking things by skipping the eval loop,
453 we need to update the current frame so the stack trace
454 will be reported correctly to the user. */
455 /* XXX We should probably be updating the current frame
456 somewhere in ceval.c. */
457 tstate->frame = gen->gi_frame;
Yury Selivanoveb636452016-09-08 22:01:51 -0700458 /* Close the generator that we are currently iterating with
459 'yield from' or awaiting on with 'await'. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100460 PyFrameState state = gen->gi_frame->f_state;
461 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700462 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
463 typ, val, tb);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100464 gen->gi_frame->f_state = state;
Chris Jerdonek8b339612020-07-09 06:27:23 -0700465 tstate->frame = f;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000466 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700467 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200468 PyObject *meth;
469 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
470 Py_DECREF(yf);
471 return NULL;
472 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000473 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000474 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000475 goto throw_here;
476 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100477 PyFrameState state = gen->gi_frame->f_state;
478 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700479 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100480 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000481 Py_DECREF(meth);
482 }
483 Py_DECREF(yf);
484 if (!ret) {
485 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500486 /* Pop subiterator from stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100487 assert(gen->gi_frame->f_stackdepth > 0);
488 gen->gi_frame->f_stackdepth--;
489 ret = gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth];
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500490 assert(ret == yf);
491 Py_DECREF(ret);
492 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100493 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300494 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000495 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300496 ret = gen_send(gen, val);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000497 Py_DECREF(val);
498 } else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300499 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000500 }
501 }
502 return ret;
503 }
504
505throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 /* First, check the traceback argument, replacing None with
507 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400508 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400510 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 else if (tb != NULL && !PyTraceBack_Check(tb)) {
512 PyErr_SetString(PyExc_TypeError,
513 "throw() third argument must be a traceback object");
514 return NULL;
515 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 Py_INCREF(typ);
518 Py_XINCREF(val);
519 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000520
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400521 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 else if (PyExceptionInstance_Check(typ)) {
525 /* Raising an instance. The value should be a dummy. */
526 if (val && val != Py_None) {
527 PyErr_SetString(PyExc_TypeError,
528 "instance exception may not have a separate value");
529 goto failed_throw;
530 }
531 else {
532 /* Normalize to raise <class>, <instance> */
533 Py_XDECREF(val);
534 val = typ;
535 typ = PyExceptionInstance_Class(typ);
536 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200537
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400538 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200539 /* Returns NULL if there's no traceback */
540 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 }
542 }
543 else {
544 /* Not something you can raise. throw() fails. */
545 PyErr_Format(PyExc_TypeError,
546 "exceptions must be classes or instances "
547 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000548 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 goto failed_throw;
550 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyErr_Restore(typ, val, tb);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300553 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000554
555failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 /* Didn't use our arguments, so restore their original refcounts */
557 Py_DECREF(typ);
558 Py_XDECREF(val);
559 Py_XDECREF(tb);
560 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000561}
562
563
564static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700565gen_throw(PyGenObject *gen, PyObject *args)
566{
567 PyObject *typ;
568 PyObject *tb = NULL;
569 PyObject *val = NULL;
570
571 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
572 return NULL;
573 }
574
575 return _gen_throw(gen, 1, typ, val, tb);
576}
577
578
579static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000580gen_iternext(PyGenObject *gen)
581{
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300582 PyObject *result;
583 assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
584 if (gen_send_ex2(gen, NULL, &result, 0, 0) == PYGEN_RETURN) {
585 if (result != Py_None) {
586 _PyGen_SetStopIterationValue(result);
587 }
588 Py_CLEAR(result);
589 }
590 return result;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000591}
592
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000593/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200594 * Set StopIteration with specified value. Value can be arbitrary object
595 * or NULL.
596 *
597 * Returns 0 if StopIteration is set and -1 if any other exception is set.
598 */
599int
600_PyGen_SetStopIterationValue(PyObject *value)
601{
602 PyObject *e;
603
604 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400605 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200606 {
607 /* Delay exception instantiation if we can */
608 PyErr_SetObject(PyExc_StopIteration, value);
609 return 0;
610 }
611 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100612 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200613 *
614 * We do this to handle a situation when "value" is a tuple, in which
615 * case PyErr_SetObject would set the value of StopIteration to
616 * the first element of the tuple.
617 *
618 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
619 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100620 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200621 if (e == NULL) {
622 return -1;
623 }
624 PyErr_SetObject(PyExc_StopIteration, e);
625 Py_DECREF(e);
626 return 0;
627}
628
629/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000630 * If StopIteration exception is set, fetches its 'value'
631 * attribute if any, otherwise sets pvalue to None.
632 *
633 * Returns 0 if no exception or StopIteration is set.
634 * If any other exception is set, returns -1 and leaves
635 * pvalue unchanged.
636 */
637
638int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200639_PyGen_FetchStopIterationValue(PyObject **pvalue)
640{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000641 PyObject *et, *ev, *tb;
642 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500643
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000644 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
645 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200646 if (ev) {
647 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300648 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200649 value = ((PyStopIterationObject *)ev)->value;
650 Py_INCREF(value);
651 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200652 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
653 /* Avoid normalisation and take ev as value.
654 *
655 * Normalization is required if the value is a tuple, in
656 * that case the value of StopIteration would be set to
657 * the first element of the tuple.
658 *
659 * (See _PyErr_CreateException code for details.)
660 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200661 value = ev;
662 } else {
663 /* normalisation required */
664 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300665 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200666 PyErr_Restore(et, ev, tb);
667 return -1;
668 }
669 value = ((PyStopIterationObject *)ev)->value;
670 Py_INCREF(value);
671 Py_DECREF(ev);
672 }
673 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000674 Py_XDECREF(et);
675 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000676 } else if (PyErr_Occurred()) {
677 return -1;
678 }
679 if (value == NULL) {
680 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100681 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000682 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000683 *pvalue = value;
684 return 0;
685}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000686
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000687static PyObject *
688gen_repr(PyGenObject *gen)
689{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400690 return PyUnicode_FromFormat("<generator object %S at %p>",
691 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000692}
693
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000694static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200695gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000696{
Victor Stinner40ee3012014-06-16 15:59:28 +0200697 Py_INCREF(op->gi_name);
698 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000699}
700
Victor Stinner40ee3012014-06-16 15:59:28 +0200701static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200702gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200703{
Victor Stinner40ee3012014-06-16 15:59:28 +0200704 /* Not legal to del gen.gi_name or to set it to anything
705 * other than a string object. */
706 if (value == NULL || !PyUnicode_Check(value)) {
707 PyErr_SetString(PyExc_TypeError,
708 "__name__ must be set to a string object");
709 return -1;
710 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200711 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300712 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200713 return 0;
714}
715
716static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200717gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200718{
719 Py_INCREF(op->gi_qualname);
720 return op->gi_qualname;
721}
722
723static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200724gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200725{
Victor Stinner40ee3012014-06-16 15:59:28 +0200726 /* Not legal to del gen.__qualname__ or to set it to anything
727 * other than a string object. */
728 if (value == NULL || !PyUnicode_Check(value)) {
729 PyErr_SetString(PyExc_TypeError,
730 "__qualname__ must be set to a string object");
731 return -1;
732 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200733 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300734 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200735 return 0;
736}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000737
Yury Selivanove13f8f32015-07-03 00:23:30 -0400738static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200739gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400740{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500741 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400742 if (yf == NULL)
743 Py_RETURN_NONE;
744 return yf;
745}
746
Mark Shannoncb9879b2020-07-17 11:44:23 +0100747
748static PyObject *
749gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
750{
751 if (gen->gi_frame == NULL) {
752 Py_RETURN_FALSE;
753 }
754 return PyBool_FromLong(_PyFrame_IsExecuting(gen->gi_frame));
755}
756
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000757static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200758 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
759 PyDoc_STR("name of the generator")},
760 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
761 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400762 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
763 PyDoc_STR("object being iterated by yield from, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100764 {"gi_running", (getter)gen_getrunning, NULL, NULL},
Victor Stinner40ee3012014-06-16 15:59:28 +0200765 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000766};
767
Martin v. Löwise440e472004-06-01 15:22:42 +0000768static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200769 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Victor Stinner40ee3012014-06-16 15:59:28 +0200770 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000772};
773
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000774static PyMethodDef gen_methods[] = {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300775 {"send",(PyCFunction)gen_send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
777 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
778 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000779};
780
Martin v. Löwise440e472004-06-01 15:22:42 +0000781PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyVarObject_HEAD_INIT(&PyType_Type, 0)
783 "generator", /* tp_name */
784 sizeof(PyGenObject), /* tp_basicsize */
785 0, /* tp_itemsize */
786 /* methods */
787 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200788 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 0, /* tp_getattr */
790 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400791 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 (reprfunc)gen_repr, /* tp_repr */
793 0, /* tp_as_number */
794 0, /* tp_as_sequence */
795 0, /* tp_as_mapping */
796 0, /* tp_hash */
797 0, /* tp_call */
798 0, /* tp_str */
799 PyObject_GenericGetAttr, /* tp_getattro */
800 0, /* tp_setattro */
801 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200802 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 0, /* tp_doc */
804 (traverseproc)gen_traverse, /* tp_traverse */
805 0, /* tp_clear */
806 0, /* tp_richcompare */
807 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400808 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 (iternextfunc)gen_iternext, /* tp_iternext */
810 gen_methods, /* tp_methods */
811 gen_memberlist, /* tp_members */
812 gen_getsetlist, /* tp_getset */
813 0, /* tp_base */
814 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 0, /* tp_descr_get */
817 0, /* tp_descr_set */
818 0, /* tp_dictoffset */
819 0, /* tp_init */
820 0, /* tp_alloc */
821 0, /* tp_new */
822 0, /* tp_free */
823 0, /* tp_is_gc */
824 0, /* tp_bases */
825 0, /* tp_mro */
826 0, /* tp_cache */
827 0, /* tp_subclasses */
828 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200829 0, /* tp_del */
830 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200831 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000832};
833
Yury Selivanov5376ba92015-06-22 12:19:30 -0400834static PyObject *
835gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
836 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000837{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400838 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 if (gen == NULL) {
840 Py_DECREF(f);
841 return NULL;
842 }
843 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200844 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 Py_INCREF(f->f_code);
846 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100848 gen->gi_exc_state.exc_type = NULL;
849 gen->gi_exc_state.exc_value = NULL;
850 gen->gi_exc_state.exc_traceback = NULL;
851 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200852 if (name != NULL)
853 gen->gi_name = name;
854 else
855 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
856 Py_INCREF(gen->gi_name);
857 if (qualname != NULL)
858 gen->gi_qualname = qualname;
859 else
860 gen->gi_qualname = gen->gi_name;
861 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 _PyObject_GC_TRACK(gen);
863 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000864}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000865
Victor Stinner40ee3012014-06-16 15:59:28 +0200866PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400867PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
868{
869 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
870}
871
872PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200873PyGen_New(PyFrameObject *f)
874{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400875 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200876}
877
Yury Selivanov5376ba92015-06-22 12:19:30 -0400878/* Coroutine Object */
879
880typedef struct {
881 PyObject_HEAD
882 PyCoroObject *cw_coroutine;
883} PyCoroWrapper;
884
885static int
886gen_is_coroutine(PyObject *o)
887{
888 if (PyGen_CheckExact(o)) {
889 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
890 if (code->co_flags & CO_ITERABLE_COROUTINE) {
891 return 1;
892 }
893 }
894 return 0;
895}
896
Yury Selivanov75445082015-05-11 22:57:16 -0400897/*
898 * This helper function returns an awaitable for `o`:
899 * - `o` if `o` is a coroutine-object;
900 * - `type(o)->tp_as_async->am_await(o)`
901 *
902 * Raises a TypeError if it's not possible to return
903 * an awaitable and returns NULL.
904 */
905PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400906_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400907{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400908 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400909 PyTypeObject *ot;
910
Yury Selivanov5376ba92015-06-22 12:19:30 -0400911 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
912 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400913 Py_INCREF(o);
914 return o;
915 }
916
917 ot = Py_TYPE(o);
918 if (ot->tp_as_async != NULL) {
919 getter = ot->tp_as_async->am_await;
920 }
921 if (getter != NULL) {
922 PyObject *res = (*getter)(o);
923 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400924 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
925 /* __await__ must return an *iterator*, not
926 a coroutine or another awaitable (see PEP 492) */
927 PyErr_SetString(PyExc_TypeError,
928 "__await__() returned a coroutine");
929 Py_CLEAR(res);
930 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400931 PyErr_Format(PyExc_TypeError,
932 "__await__() returned non-iterator "
933 "of type '%.100s'",
934 Py_TYPE(res)->tp_name);
935 Py_CLEAR(res);
936 }
Yury Selivanov75445082015-05-11 22:57:16 -0400937 }
938 return res;
939 }
940
941 PyErr_Format(PyExc_TypeError,
942 "object %.100s can't be used in 'await' expression",
943 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400944 return NULL;
945}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400946
947static PyObject *
948coro_repr(PyCoroObject *coro)
949{
950 return PyUnicode_FromFormat("<coroutine object %S at %p>",
951 coro->cr_qualname, coro);
952}
953
954static PyObject *
955coro_await(PyCoroObject *coro)
956{
957 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
958 if (cw == NULL) {
959 return NULL;
960 }
961 Py_INCREF(coro);
962 cw->cw_coroutine = coro;
963 _PyObject_GC_TRACK(cw);
964 return (PyObject *)cw;
965}
966
Yury Selivanove13f8f32015-07-03 00:23:30 -0400967static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200968coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400969{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500970 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400971 if (yf == NULL)
972 Py_RETURN_NONE;
973 return yf;
974}
975
Mark Shannoncb9879b2020-07-17 11:44:23 +0100976static PyObject *
977cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
978{
979 if (coro->cr_frame == NULL) {
980 Py_RETURN_FALSE;
981 }
982 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
983}
984
Yury Selivanov5376ba92015-06-22 12:19:30 -0400985static PyGetSetDef coro_getsetlist[] = {
986 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
987 PyDoc_STR("name of the coroutine")},
988 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
989 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400990 {"cr_await", (getter)coro_get_cr_await, NULL,
991 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100992 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400993 {NULL} /* Sentinel */
994};
995
996static PyMemberDef coro_memberlist[] = {
997 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400998 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800999 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001000 {NULL} /* Sentinel */
1001};
1002
1003PyDoc_STRVAR(coro_send_doc,
1004"send(arg) -> send 'arg' into 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_throw_doc,
1008"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001009return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001010
1011PyDoc_STRVAR(coro_close_doc,
1012"close() -> raise GeneratorExit inside coroutine.");
1013
1014static PyMethodDef coro_methods[] = {
1015 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
1016 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1017 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1018 {NULL, NULL} /* Sentinel */
1019};
1020
1021static PyAsyncMethods coro_as_async = {
1022 (unaryfunc)coro_await, /* am_await */
1023 0, /* am_aiter */
1024 0 /* am_anext */
1025};
1026
1027PyTypeObject PyCoro_Type = {
1028 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1029 "coroutine", /* tp_name */
1030 sizeof(PyCoroObject), /* tp_basicsize */
1031 0, /* tp_itemsize */
1032 /* methods */
1033 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001034 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001035 0, /* tp_getattr */
1036 0, /* tp_setattr */
1037 &coro_as_async, /* tp_as_async */
1038 (reprfunc)coro_repr, /* tp_repr */
1039 0, /* tp_as_number */
1040 0, /* tp_as_sequence */
1041 0, /* tp_as_mapping */
1042 0, /* tp_hash */
1043 0, /* tp_call */
1044 0, /* tp_str */
1045 PyObject_GenericGetAttr, /* tp_getattro */
1046 0, /* tp_setattro */
1047 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001048 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001049 0, /* tp_doc */
1050 (traverseproc)gen_traverse, /* tp_traverse */
1051 0, /* tp_clear */
1052 0, /* tp_richcompare */
1053 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1054 0, /* tp_iter */
1055 0, /* tp_iternext */
1056 coro_methods, /* tp_methods */
1057 coro_memberlist, /* tp_members */
1058 coro_getsetlist, /* tp_getset */
1059 0, /* tp_base */
1060 0, /* tp_dict */
1061 0, /* tp_descr_get */
1062 0, /* tp_descr_set */
1063 0, /* tp_dictoffset */
1064 0, /* tp_init */
1065 0, /* tp_alloc */
1066 0, /* tp_new */
1067 0, /* tp_free */
1068 0, /* tp_is_gc */
1069 0, /* tp_bases */
1070 0, /* tp_mro */
1071 0, /* tp_cache */
1072 0, /* tp_subclasses */
1073 0, /* tp_weaklist */
1074 0, /* tp_del */
1075 0, /* tp_version_tag */
1076 _PyGen_Finalize, /* tp_finalize */
1077};
1078
1079static void
1080coro_wrapper_dealloc(PyCoroWrapper *cw)
1081{
1082 _PyObject_GC_UNTRACK((PyObject *)cw);
1083 Py_CLEAR(cw->cw_coroutine);
1084 PyObject_GC_Del(cw);
1085}
1086
1087static PyObject *
1088coro_wrapper_iternext(PyCoroWrapper *cw)
1089{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001090 return gen_iternext((PyGenObject *)cw->cw_coroutine);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001091}
1092
1093static PyObject *
1094coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1095{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001096 return gen_send((PyGenObject *)cw->cw_coroutine, arg);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001097}
1098
1099static PyObject *
1100coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1101{
1102 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1103}
1104
1105static PyObject *
1106coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1107{
1108 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1109}
1110
1111static int
1112coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1113{
1114 Py_VISIT((PyObject *)cw->cw_coroutine);
1115 return 0;
1116}
1117
1118static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001119 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1120 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1121 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001122 {NULL, NULL} /* Sentinel */
1123};
1124
1125PyTypeObject _PyCoroWrapper_Type = {
1126 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1127 "coroutine_wrapper",
1128 sizeof(PyCoroWrapper), /* tp_basicsize */
1129 0, /* tp_itemsize */
1130 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001131 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001132 0, /* tp_getattr */
1133 0, /* tp_setattr */
1134 0, /* tp_as_async */
1135 0, /* tp_repr */
1136 0, /* tp_as_number */
1137 0, /* tp_as_sequence */
1138 0, /* tp_as_mapping */
1139 0, /* tp_hash */
1140 0, /* tp_call */
1141 0, /* tp_str */
1142 PyObject_GenericGetAttr, /* tp_getattro */
1143 0, /* tp_setattro */
1144 0, /* tp_as_buffer */
1145 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1146 "A wrapper object implementing __await__ for coroutines.",
1147 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1148 0, /* tp_clear */
1149 0, /* tp_richcompare */
1150 0, /* tp_weaklistoffset */
1151 PyObject_SelfIter, /* tp_iter */
1152 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1153 coro_wrapper_methods, /* tp_methods */
1154 0, /* tp_members */
1155 0, /* tp_getset */
1156 0, /* tp_base */
1157 0, /* tp_dict */
1158 0, /* tp_descr_get */
1159 0, /* tp_descr_set */
1160 0, /* tp_dictoffset */
1161 0, /* tp_init */
1162 0, /* tp_alloc */
1163 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001164 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001165};
1166
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001167static PyObject *
1168compute_cr_origin(int origin_depth)
1169{
1170 PyFrameObject *frame = PyEval_GetFrame();
1171 /* First count how many frames we have */
1172 int frame_count = 0;
1173 for (; frame && frame_count < origin_depth; ++frame_count) {
1174 frame = frame->f_back;
1175 }
1176
1177 /* Now collect them */
1178 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001179 if (cr_origin == NULL) {
1180 return NULL;
1181 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001182 frame = PyEval_GetFrame();
1183 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001184 PyCodeObject *code = frame->f_code;
1185 PyObject *frameinfo = Py_BuildValue("OiO",
1186 code->co_filename,
1187 PyFrame_GetLineNumber(frame),
1188 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001189 if (!frameinfo) {
1190 Py_DECREF(cr_origin);
1191 return NULL;
1192 }
1193 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1194 frame = frame->f_back;
1195 }
1196
1197 return cr_origin;
1198}
1199
Yury Selivanov5376ba92015-06-22 12:19:30 -04001200PyObject *
1201PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1202{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001203 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1204 if (!coro) {
1205 return NULL;
1206 }
1207
Victor Stinner50b48572018-11-01 01:51:40 +01001208 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001209 int origin_depth = tstate->coroutine_origin_tracking_depth;
1210
1211 if (origin_depth == 0) {
1212 ((PyCoroObject *)coro)->cr_origin = NULL;
1213 } else {
1214 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001215 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001216 if (!cr_origin) {
1217 Py_DECREF(coro);
1218 return NULL;
1219 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001220 }
1221
1222 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001223}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001224
1225
Yury Selivanoveb636452016-09-08 22:01:51 -07001226/* ========= Asynchronous Generators ========= */
1227
1228
1229typedef enum {
1230 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1231 AWAITABLE_STATE_ITER, /* being iterated */
1232 AWAITABLE_STATE_CLOSED, /* closed */
1233} AwaitableState;
1234
1235
Victor Stinner78a02c22020-06-05 02:34:14 +02001236typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001237 PyObject_HEAD
1238 PyAsyncGenObject *ags_gen;
1239
1240 /* Can be NULL, when in the __anext__() mode
1241 (equivalent of "asend(None)") */
1242 PyObject *ags_sendval;
1243
1244 AwaitableState ags_state;
1245} PyAsyncGenASend;
1246
1247
Victor Stinner78a02c22020-06-05 02:34:14 +02001248typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001249 PyObject_HEAD
1250 PyAsyncGenObject *agt_gen;
1251
1252 /* Can be NULL, when in the "aclose()" mode
1253 (equivalent of "athrow(GeneratorExit)") */
1254 PyObject *agt_args;
1255
1256 AwaitableState agt_state;
1257} PyAsyncGenAThrow;
1258
1259
Victor Stinner78a02c22020-06-05 02:34:14 +02001260typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001261 PyObject_HEAD
1262 PyObject *agw_val;
1263} _PyAsyncGenWrappedValue;
1264
1265
Yury Selivanoveb636452016-09-08 22:01:51 -07001266#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001267 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001268
1269#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001270 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001271
1272
1273static int
1274async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1275{
1276 Py_VISIT(gen->ag_finalizer);
1277 return gen_traverse((PyGenObject*)gen, visit, arg);
1278}
1279
1280
1281static PyObject *
1282async_gen_repr(PyAsyncGenObject *o)
1283{
1284 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1285 o->ag_qualname, o);
1286}
1287
1288
1289static int
1290async_gen_init_hooks(PyAsyncGenObject *o)
1291{
1292 PyThreadState *tstate;
1293 PyObject *finalizer;
1294 PyObject *firstiter;
1295
1296 if (o->ag_hooks_inited) {
1297 return 0;
1298 }
1299
1300 o->ag_hooks_inited = 1;
1301
Victor Stinner50b48572018-11-01 01:51:40 +01001302 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001303
1304 finalizer = tstate->async_gen_finalizer;
1305 if (finalizer) {
1306 Py_INCREF(finalizer);
1307 o->ag_finalizer = finalizer;
1308 }
1309
1310 firstiter = tstate->async_gen_firstiter;
1311 if (firstiter) {
1312 PyObject *res;
1313
1314 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001315 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001316 Py_DECREF(firstiter);
1317 if (res == NULL) {
1318 return 1;
1319 }
1320 Py_DECREF(res);
1321 }
1322
1323 return 0;
1324}
1325
1326
1327static PyObject *
1328async_gen_anext(PyAsyncGenObject *o)
1329{
1330 if (async_gen_init_hooks(o)) {
1331 return NULL;
1332 }
1333 return async_gen_asend_new(o, NULL);
1334}
1335
1336
1337static PyObject *
1338async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1339{
1340 if (async_gen_init_hooks(o)) {
1341 return NULL;
1342 }
1343 return async_gen_asend_new(o, arg);
1344}
1345
1346
1347static PyObject *
1348async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1349{
1350 if (async_gen_init_hooks(o)) {
1351 return NULL;
1352 }
1353 return async_gen_athrow_new(o, NULL);
1354}
1355
1356static PyObject *
1357async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1358{
1359 if (async_gen_init_hooks(o)) {
1360 return NULL;
1361 }
1362 return async_gen_athrow_new(o, args);
1363}
1364
1365
1366static PyGetSetDef async_gen_getsetlist[] = {
1367 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1368 PyDoc_STR("name of the async generator")},
1369 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1370 PyDoc_STR("qualified name of the async generator")},
1371 {"ag_await", (getter)coro_get_cr_await, NULL,
1372 PyDoc_STR("object being awaited on, or None")},
1373 {NULL} /* Sentinel */
1374};
1375
1376static PyMemberDef async_gen_memberlist[] = {
1377 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001378 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1379 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001380 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1381 {NULL} /* Sentinel */
1382};
1383
1384PyDoc_STRVAR(async_aclose_doc,
1385"aclose() -> raise GeneratorExit inside generator.");
1386
1387PyDoc_STRVAR(async_asend_doc,
1388"asend(v) -> send 'v' in generator.");
1389
1390PyDoc_STRVAR(async_athrow_doc,
1391"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1392
1393static PyMethodDef async_gen_methods[] = {
1394 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1395 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1396 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001397 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1398 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001399 {NULL, NULL} /* Sentinel */
1400};
1401
1402
1403static PyAsyncMethods async_gen_as_async = {
1404 0, /* am_await */
1405 PyObject_SelfIter, /* am_aiter */
1406 (unaryfunc)async_gen_anext /* am_anext */
1407};
1408
1409
1410PyTypeObject PyAsyncGen_Type = {
1411 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1412 "async_generator", /* tp_name */
1413 sizeof(PyAsyncGenObject), /* tp_basicsize */
1414 0, /* tp_itemsize */
1415 /* methods */
1416 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001417 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001418 0, /* tp_getattr */
1419 0, /* tp_setattr */
1420 &async_gen_as_async, /* tp_as_async */
1421 (reprfunc)async_gen_repr, /* tp_repr */
1422 0, /* tp_as_number */
1423 0, /* tp_as_sequence */
1424 0, /* tp_as_mapping */
1425 0, /* tp_hash */
1426 0, /* tp_call */
1427 0, /* tp_str */
1428 PyObject_GenericGetAttr, /* tp_getattro */
1429 0, /* tp_setattro */
1430 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001431 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001432 0, /* tp_doc */
1433 (traverseproc)async_gen_traverse, /* tp_traverse */
1434 0, /* tp_clear */
1435 0, /* tp_richcompare */
1436 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1437 0, /* tp_iter */
1438 0, /* tp_iternext */
1439 async_gen_methods, /* tp_methods */
1440 async_gen_memberlist, /* tp_members */
1441 async_gen_getsetlist, /* tp_getset */
1442 0, /* tp_base */
1443 0, /* tp_dict */
1444 0, /* tp_descr_get */
1445 0, /* tp_descr_set */
1446 0, /* tp_dictoffset */
1447 0, /* tp_init */
1448 0, /* tp_alloc */
1449 0, /* tp_new */
1450 0, /* tp_free */
1451 0, /* tp_is_gc */
1452 0, /* tp_bases */
1453 0, /* tp_mro */
1454 0, /* tp_cache */
1455 0, /* tp_subclasses */
1456 0, /* tp_weaklist */
1457 0, /* tp_del */
1458 0, /* tp_version_tag */
1459 _PyGen_Finalize, /* tp_finalize */
1460};
1461
1462
Victor Stinner522691c2020-06-23 16:40:40 +02001463static struct _Py_async_gen_state *
1464get_async_gen_state(void)
1465{
1466 PyInterpreterState *interp = _PyInterpreterState_GET();
1467 return &interp->async_gen;
1468}
1469
1470
Yury Selivanoveb636452016-09-08 22:01:51 -07001471PyObject *
1472PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1473{
1474 PyAsyncGenObject *o;
1475 o = (PyAsyncGenObject *)gen_new_with_qualname(
1476 &PyAsyncGen_Type, f, name, qualname);
1477 if (o == NULL) {
1478 return NULL;
1479 }
1480 o->ag_finalizer = NULL;
1481 o->ag_closed = 0;
1482 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001483 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001484 return (PyObject*)o;
1485}
1486
1487
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001488void
Victor Stinner78a02c22020-06-05 02:34:14 +02001489_PyAsyncGen_ClearFreeLists(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001490{
Victor Stinner78a02c22020-06-05 02:34:14 +02001491 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1492
1493 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001494 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001495 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001496 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001497 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001498 }
1499
Victor Stinner78a02c22020-06-05 02:34:14 +02001500 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001501 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001502 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001503 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001504 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001505 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001506}
1507
1508void
Victor Stinner78a02c22020-06-05 02:34:14 +02001509_PyAsyncGen_Fini(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001510{
Victor Stinner78a02c22020-06-05 02:34:14 +02001511 _PyAsyncGen_ClearFreeLists(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001512#ifdef Py_DEBUG
1513 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1514 state->value_numfree = -1;
1515 state->asend_numfree = -1;
1516#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001517}
1518
1519
1520static PyObject *
1521async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1522{
1523 if (result == NULL) {
1524 if (!PyErr_Occurred()) {
1525 PyErr_SetNone(PyExc_StopAsyncIteration);
1526 }
1527
1528 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1529 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1530 ) {
1531 gen->ag_closed = 1;
1532 }
1533
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001534 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001535 return NULL;
1536 }
1537
1538 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1539 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001540 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001541 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001542 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001543 return NULL;
1544 }
1545
1546 return result;
1547}
1548
1549
1550/* ---------- Async Generator ASend Awaitable ------------ */
1551
1552
1553static void
1554async_gen_asend_dealloc(PyAsyncGenASend *o)
1555{
Yury Selivanov29310c42016-11-08 19:46:22 -05001556 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001557 Py_CLEAR(o->ags_gen);
1558 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001559 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001560#ifdef Py_DEBUG
1561 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1562 assert(state->asend_numfree != -1);
1563#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001564 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001565 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001566 state->asend_freelist[state->asend_numfree++] = o;
1567 }
1568 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001569 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001570 }
1571}
1572
Yury Selivanov29310c42016-11-08 19:46:22 -05001573static int
1574async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1575{
1576 Py_VISIT(o->ags_gen);
1577 Py_VISIT(o->ags_sendval);
1578 return 0;
1579}
1580
Yury Selivanoveb636452016-09-08 22:01:51 -07001581
1582static PyObject *
1583async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1584{
1585 PyObject *result;
1586
1587 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001588 PyErr_SetString(
1589 PyExc_RuntimeError,
1590 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001591 return NULL;
1592 }
1593
1594 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001595 if (o->ags_gen->ag_running_async) {
1596 PyErr_SetString(
1597 PyExc_RuntimeError,
1598 "anext(): asynchronous generator is already running");
1599 return NULL;
1600 }
1601
Yury Selivanoveb636452016-09-08 22:01:51 -07001602 if (arg == NULL || arg == Py_None) {
1603 arg = o->ags_sendval;
1604 }
1605 o->ags_state = AWAITABLE_STATE_ITER;
1606 }
1607
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001608 o->ags_gen->ag_running_async = 1;
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001609 result = gen_send((PyGenObject*)o->ags_gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001610 result = async_gen_unwrap_value(o->ags_gen, result);
1611
1612 if (result == NULL) {
1613 o->ags_state = AWAITABLE_STATE_CLOSED;
1614 }
1615
1616 return result;
1617}
1618
1619
1620static PyObject *
1621async_gen_asend_iternext(PyAsyncGenASend *o)
1622{
1623 return async_gen_asend_send(o, NULL);
1624}
1625
1626
1627static PyObject *
1628async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1629{
1630 PyObject *result;
1631
1632 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001633 PyErr_SetString(
1634 PyExc_RuntimeError,
1635 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001636 return NULL;
1637 }
1638
1639 result = gen_throw((PyGenObject*)o->ags_gen, args);
1640 result = async_gen_unwrap_value(o->ags_gen, result);
1641
1642 if (result == NULL) {
1643 o->ags_state = AWAITABLE_STATE_CLOSED;
1644 }
1645
1646 return result;
1647}
1648
1649
1650static PyObject *
1651async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1652{
1653 o->ags_state = AWAITABLE_STATE_CLOSED;
1654 Py_RETURN_NONE;
1655}
1656
1657
1658static PyMethodDef async_gen_asend_methods[] = {
1659 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1660 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1661 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1662 {NULL, NULL} /* Sentinel */
1663};
1664
1665
1666static PyAsyncMethods async_gen_asend_as_async = {
1667 PyObject_SelfIter, /* am_await */
1668 0, /* am_aiter */
1669 0 /* am_anext */
1670};
1671
1672
1673PyTypeObject _PyAsyncGenASend_Type = {
1674 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1675 "async_generator_asend", /* tp_name */
1676 sizeof(PyAsyncGenASend), /* tp_basicsize */
1677 0, /* tp_itemsize */
1678 /* methods */
1679 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001680 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001681 0, /* tp_getattr */
1682 0, /* tp_setattr */
1683 &async_gen_asend_as_async, /* tp_as_async */
1684 0, /* tp_repr */
1685 0, /* tp_as_number */
1686 0, /* tp_as_sequence */
1687 0, /* tp_as_mapping */
1688 0, /* tp_hash */
1689 0, /* tp_call */
1690 0, /* tp_str */
1691 PyObject_GenericGetAttr, /* tp_getattro */
1692 0, /* tp_setattro */
1693 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001694 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001695 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001696 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001697 0, /* tp_clear */
1698 0, /* tp_richcompare */
1699 0, /* tp_weaklistoffset */
1700 PyObject_SelfIter, /* tp_iter */
1701 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1702 async_gen_asend_methods, /* tp_methods */
1703 0, /* tp_members */
1704 0, /* tp_getset */
1705 0, /* tp_base */
1706 0, /* tp_dict */
1707 0, /* tp_descr_get */
1708 0, /* tp_descr_set */
1709 0, /* tp_dictoffset */
1710 0, /* tp_init */
1711 0, /* tp_alloc */
1712 0, /* tp_new */
1713};
1714
1715
1716static PyObject *
1717async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1718{
1719 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001720 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001721#ifdef Py_DEBUG
1722 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1723 assert(state->asend_numfree != -1);
1724#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001725 if (state->asend_numfree) {
1726 state->asend_numfree--;
1727 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001728 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001729 }
1730 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001731 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001732 if (o == NULL) {
1733 return NULL;
1734 }
1735 }
1736
1737 Py_INCREF(gen);
1738 o->ags_gen = gen;
1739
1740 Py_XINCREF(sendval);
1741 o->ags_sendval = sendval;
1742
1743 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001744
1745 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001746 return (PyObject*)o;
1747}
1748
1749
1750/* ---------- Async Generator Value Wrapper ------------ */
1751
1752
1753static void
1754async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1755{
Yury Selivanov29310c42016-11-08 19:46:22 -05001756 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001757 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001758 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001759#ifdef Py_DEBUG
1760 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1761 assert(state->value_numfree != -1);
1762#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001763 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001764 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001765 state->value_freelist[state->value_numfree++] = o;
1766 }
1767 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001768 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001769 }
1770}
1771
1772
Yury Selivanov29310c42016-11-08 19:46:22 -05001773static int
1774async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1775 visitproc visit, void *arg)
1776{
1777 Py_VISIT(o->agw_val);
1778 return 0;
1779}
1780
1781
Yury Selivanoveb636452016-09-08 22:01:51 -07001782PyTypeObject _PyAsyncGenWrappedValue_Type = {
1783 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1784 "async_generator_wrapped_value", /* tp_name */
1785 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1786 0, /* tp_itemsize */
1787 /* methods */
1788 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001789 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001790 0, /* tp_getattr */
1791 0, /* tp_setattr */
1792 0, /* tp_as_async */
1793 0, /* tp_repr */
1794 0, /* tp_as_number */
1795 0, /* tp_as_sequence */
1796 0, /* tp_as_mapping */
1797 0, /* tp_hash */
1798 0, /* tp_call */
1799 0, /* tp_str */
1800 PyObject_GenericGetAttr, /* tp_getattro */
1801 0, /* tp_setattro */
1802 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001803 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001804 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001805 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001806 0, /* tp_clear */
1807 0, /* tp_richcompare */
1808 0, /* tp_weaklistoffset */
1809 0, /* tp_iter */
1810 0, /* tp_iternext */
1811 0, /* tp_methods */
1812 0, /* tp_members */
1813 0, /* tp_getset */
1814 0, /* tp_base */
1815 0, /* tp_dict */
1816 0, /* tp_descr_get */
1817 0, /* tp_descr_set */
1818 0, /* tp_dictoffset */
1819 0, /* tp_init */
1820 0, /* tp_alloc */
1821 0, /* tp_new */
1822};
1823
1824
1825PyObject *
1826_PyAsyncGenValueWrapperNew(PyObject *val)
1827{
1828 _PyAsyncGenWrappedValue *o;
1829 assert(val);
1830
Victor Stinner522691c2020-06-23 16:40:40 +02001831 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001832#ifdef Py_DEBUG
1833 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1834 assert(state->value_numfree != -1);
1835#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001836 if (state->value_numfree) {
1837 state->value_numfree--;
1838 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001839 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1840 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001841 }
1842 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001843 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1844 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001845 if (o == NULL) {
1846 return NULL;
1847 }
1848 }
1849 o->agw_val = val;
1850 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001851 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001852 return (PyObject*)o;
1853}
1854
1855
1856/* ---------- Async Generator AThrow awaitable ------------ */
1857
1858
1859static void
1860async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1861{
Yury Selivanov29310c42016-11-08 19:46:22 -05001862 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001863 Py_CLEAR(o->agt_gen);
1864 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001865 PyObject_GC_Del(o);
1866}
1867
1868
1869static int
1870async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1871{
1872 Py_VISIT(o->agt_gen);
1873 Py_VISIT(o->agt_args);
1874 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001875}
1876
1877
1878static PyObject *
1879async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1880{
1881 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1882 PyFrameObject *f = gen->gi_frame;
1883 PyObject *retval;
1884
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001885 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001886 PyErr_SetString(
1887 PyExc_RuntimeError,
1888 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001889 return NULL;
1890 }
1891
Mark Shannoncb9879b2020-07-17 11:44:23 +01001892 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001893 o->agt_state = AWAITABLE_STATE_CLOSED;
1894 PyErr_SetNone(PyExc_StopIteration);
1895 return NULL;
1896 }
1897
Yury Selivanoveb636452016-09-08 22:01:51 -07001898 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001899 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001900 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001901 if (o->agt_args == NULL) {
1902 PyErr_SetString(
1903 PyExc_RuntimeError,
1904 "aclose(): asynchronous generator is already running");
1905 }
1906 else {
1907 PyErr_SetString(
1908 PyExc_RuntimeError,
1909 "athrow(): asynchronous generator is already running");
1910 }
1911 return NULL;
1912 }
1913
Yury Selivanoveb636452016-09-08 22:01:51 -07001914 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001915 o->agt_state = AWAITABLE_STATE_CLOSED;
1916 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001917 return NULL;
1918 }
1919
1920 if (arg != Py_None) {
1921 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1922 return NULL;
1923 }
1924
1925 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001926 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001927
1928 if (o->agt_args == NULL) {
1929 /* aclose() mode */
1930 o->agt_gen->ag_closed = 1;
1931
1932 retval = _gen_throw((PyGenObject *)gen,
1933 0, /* Do not close generator when
1934 PyExc_GeneratorExit is passed */
1935 PyExc_GeneratorExit, NULL, NULL);
1936
1937 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1938 Py_DECREF(retval);
1939 goto yield_close;
1940 }
1941 } else {
1942 PyObject *typ;
1943 PyObject *tb = NULL;
1944 PyObject *val = NULL;
1945
1946 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1947 &typ, &val, &tb)) {
1948 return NULL;
1949 }
1950
1951 retval = _gen_throw((PyGenObject *)gen,
1952 0, /* Do not close generator when
1953 PyExc_GeneratorExit is passed */
1954 typ, val, tb);
1955 retval = async_gen_unwrap_value(o->agt_gen, retval);
1956 }
1957 if (retval == NULL) {
1958 goto check_error;
1959 }
1960 return retval;
1961 }
1962
1963 assert(o->agt_state == AWAITABLE_STATE_ITER);
1964
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001965 retval = gen_send((PyGenObject *)gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001966 if (o->agt_args) {
1967 return async_gen_unwrap_value(o->agt_gen, retval);
1968 } else {
1969 /* aclose() mode */
1970 if (retval) {
1971 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1972 Py_DECREF(retval);
1973 goto yield_close;
1974 }
1975 else {
1976 return retval;
1977 }
1978 }
1979 else {
1980 goto check_error;
1981 }
1982 }
1983
1984yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001985 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001986 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001987 PyErr_SetString(
1988 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1989 return NULL;
1990
1991check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001992 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001993 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001994 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1995 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1996 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001997 if (o->agt_args == NULL) {
1998 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001999 StopAsyncIteration or GeneratorExit; just raise
2000 StopIteration, signalling that this 'aclose()' await
2001 is done.
2002 */
Yury Selivanov41782e42016-11-16 18:16:17 -05002003 PyErr_Clear();
2004 PyErr_SetNone(PyExc_StopIteration);
2005 }
2006 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002007 return NULL;
2008}
2009
2010
2011static PyObject *
2012async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
2013{
2014 PyObject *retval;
2015
Yury Selivanoveb636452016-09-08 22:01:51 -07002016 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02002017 PyErr_SetString(
2018 PyExc_RuntimeError,
2019 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07002020 return NULL;
2021 }
2022
2023 retval = gen_throw((PyGenObject*)o->agt_gen, args);
2024 if (o->agt_args) {
2025 return async_gen_unwrap_value(o->agt_gen, retval);
2026 } else {
2027 /* aclose() mode */
2028 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002029 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002030 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07002031 Py_DECREF(retval);
2032 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2033 return NULL;
2034 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08002035 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2036 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2037 {
2038 /* when aclose() is called we don't want to propagate
2039 StopAsyncIteration or GeneratorExit; just raise
2040 StopIteration, signalling that this 'aclose()' await
2041 is done.
2042 */
2043 PyErr_Clear();
2044 PyErr_SetNone(PyExc_StopIteration);
2045 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002046 return retval;
2047 }
2048}
2049
2050
2051static PyObject *
2052async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2053{
2054 return async_gen_athrow_send(o, Py_None);
2055}
2056
2057
2058static PyObject *
2059async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2060{
2061 o->agt_state = AWAITABLE_STATE_CLOSED;
2062 Py_RETURN_NONE;
2063}
2064
2065
2066static PyMethodDef async_gen_athrow_methods[] = {
2067 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2068 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2069 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2070 {NULL, NULL} /* Sentinel */
2071};
2072
2073
2074static PyAsyncMethods async_gen_athrow_as_async = {
2075 PyObject_SelfIter, /* am_await */
2076 0, /* am_aiter */
2077 0 /* am_anext */
2078};
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}