blob: bde92b462da19978e7d049382cc277f44f90745f [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
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800271static PySendResult
272PyGen_am_send(PyGenObject *gen, PyObject *arg, PyObject **result)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300273{
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800274 return gen_send_ex2(gen, arg, result, 0, 0);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300275}
276
277static PyObject *
278gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
279{
280 PyObject *result;
281 if (gen_send_ex2(gen, arg, &result, exc, closing) == PYGEN_RETURN) {
282 if (PyAsyncGen_CheckExact(gen)) {
283 assert(result == Py_None);
284 PyErr_SetNone(PyExc_StopAsyncIteration);
285 }
286 else if (result == Py_None) {
287 PyErr_SetNone(PyExc_StopIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -0700288 }
289 else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300290 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200291 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300292 Py_CLEAR(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200293 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200294 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000295}
296
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000297PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298"send(arg) -> send 'arg' into generator,\n\
299return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000300
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300301static PyObject *
302gen_send(PyGenObject *gen, PyObject *arg)
303{
304 return gen_send_ex(gen, arg, 0, 0);
305}
306
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000307PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400308"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000309
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000310/*
311 * This helper function is used by gen_close and gen_throw to
312 * close a subiterator being delegated to by yield-from.
313 */
314
Antoine Pitrou93963562013-05-14 20:37:52 +0200315static int
316gen_close_iter(PyObject *yf)
317{
318 PyObject *retval = NULL;
319 _Py_IDENTIFIER(close);
320
Yury Selivanoveb636452016-09-08 22:01:51 -0700321 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200322 retval = gen_close((PyGenObject *)yf, NULL);
323 if (retval == NULL)
324 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700325 }
326 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200327 PyObject *meth;
328 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
329 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700330 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200331 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700332 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200333 Py_DECREF(meth);
334 if (retval == NULL)
335 return -1;
336 }
337 }
338 Py_XDECREF(retval);
339 return 0;
340}
341
Yury Selivanovc724bae2016-03-02 11:30:46 -0500342PyObject *
343_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500344{
Antoine Pitrou93963562013-05-14 20:37:52 +0200345 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500346 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200347
Mark Shannoncb9879b2020-07-17 11:44:23 +0100348 if (f) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200349 PyObject *bytecode = f->f_code->co_code;
350 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
351
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100352 if (f->f_lasti < 0) {
353 /* Return immediately if the frame didn't start yet. YIELD_FROM
354 always come after LOAD_CONST: a code object should not start
355 with YIELD_FROM */
356 assert(code[0] != YIELD_FROM);
357 return NULL;
358 }
359
Serhiy Storchakaab874002016-09-11 13:48:15 +0300360 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200361 return NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100362 assert(f->f_stackdepth > 0);
363 yf = f->f_valuestack[f->f_stackdepth-1];
Antoine Pitrou93963562013-05-14 20:37:52 +0200364 Py_INCREF(yf);
365 }
366
367 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500368}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000369
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000370static PyObject *
371gen_close(PyGenObject *gen, PyObject *args)
372{
Antoine Pitrou93963562013-05-14 20:37:52 +0200373 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500374 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200375 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000376
Antoine Pitrou93963562013-05-14 20:37:52 +0200377 if (yf) {
Mark Shannoncb9879b2020-07-17 11:44:23 +0100378 PyFrameState state = gen->gi_frame->f_state;
379 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200380 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100381 gen->gi_frame->f_state = state;
Antoine Pitrou93963562013-05-14 20:37:52 +0200382 Py_DECREF(yf);
383 }
384 if (err == 0)
385 PyErr_SetNone(PyExc_GeneratorExit);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300386 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200387 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200388 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700389 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400390 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700391 } else if (PyAsyncGen_CheckExact(gen)) {
392 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
393 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200394 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400395 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 return NULL;
397 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200398 if (PyErr_ExceptionMatches(PyExc_StopIteration)
399 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
400 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200401 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200402 }
403 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000404}
405
Antoine Pitrou93963562013-05-14 20:37:52 +0200406
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000407PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000408"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
409return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000410
411static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700412_gen_throw(PyGenObject *gen, int close_on_genexit,
413 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000414{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500415 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000416 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000417
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000418 if (yf) {
419 PyObject *ret;
420 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700421 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
422 close_on_genexit
423 ) {
424 /* Asynchronous generators *should not* be closed right away.
425 We have to allow some awaits to work it through, hence the
426 `close_on_genexit` parameter here.
427 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100428 PyFrameState state = gen->gi_frame->f_state;
429 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200430 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100431 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000432 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000433 if (err < 0)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300434 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000435 goto throw_here;
436 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700437 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
438 /* `yf` is a generator or a coroutine. */
Chris Jerdonek8b339612020-07-09 06:27:23 -0700439 PyThreadState *tstate = _PyThreadState_GET();
440 PyFrameObject *f = tstate->frame;
441
Chris Jerdonek8b339612020-07-09 06:27:23 -0700442 /* Since we are fast-tracking things by skipping the eval loop,
443 we need to update the current frame so the stack trace
444 will be reported correctly to the user. */
445 /* XXX We should probably be updating the current frame
446 somewhere in ceval.c. */
447 tstate->frame = gen->gi_frame;
Yury Selivanoveb636452016-09-08 22:01:51 -0700448 /* Close the generator that we are currently iterating with
449 'yield from' or awaiting on with 'await'. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100450 PyFrameState state = gen->gi_frame->f_state;
451 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700452 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
453 typ, val, tb);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100454 gen->gi_frame->f_state = state;
Chris Jerdonek8b339612020-07-09 06:27:23 -0700455 tstate->frame = f;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000456 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700457 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200458 PyObject *meth;
459 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
460 Py_DECREF(yf);
461 return NULL;
462 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000463 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000464 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000465 goto throw_here;
466 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100467 PyFrameState state = gen->gi_frame->f_state;
468 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700469 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100470 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000471 Py_DECREF(meth);
472 }
473 Py_DECREF(yf);
474 if (!ret) {
475 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500476 /* Pop subiterator from stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100477 assert(gen->gi_frame->f_stackdepth > 0);
478 gen->gi_frame->f_stackdepth--;
479 ret = gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth];
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500480 assert(ret == yf);
481 Py_DECREF(ret);
482 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100483 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300484 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000485 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300486 ret = gen_send(gen, val);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000487 Py_DECREF(val);
488 } else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300489 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000490 }
491 }
492 return ret;
493 }
494
495throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* First, check the traceback argument, replacing None with
497 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400498 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400500 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 else if (tb != NULL && !PyTraceBack_Check(tb)) {
502 PyErr_SetString(PyExc_TypeError,
503 "throw() third argument must be a traceback object");
504 return NULL;
505 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 Py_INCREF(typ);
508 Py_XINCREF(val);
509 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000510
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400511 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 else if (PyExceptionInstance_Check(typ)) {
515 /* Raising an instance. The value should be a dummy. */
516 if (val && val != Py_None) {
517 PyErr_SetString(PyExc_TypeError,
518 "instance exception may not have a separate value");
519 goto failed_throw;
520 }
521 else {
522 /* Normalize to raise <class>, <instance> */
523 Py_XDECREF(val);
524 val = typ;
525 typ = PyExceptionInstance_Class(typ);
526 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200527
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400528 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200529 /* Returns NULL if there's no traceback */
530 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 }
532 }
533 else {
534 /* Not something you can raise. throw() fails. */
535 PyErr_Format(PyExc_TypeError,
536 "exceptions must be classes or instances "
537 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000538 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 goto failed_throw;
540 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 PyErr_Restore(typ, val, tb);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300543 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000544
545failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 /* Didn't use our arguments, so restore their original refcounts */
547 Py_DECREF(typ);
548 Py_XDECREF(val);
549 Py_XDECREF(tb);
550 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000551}
552
553
554static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700555gen_throw(PyGenObject *gen, PyObject *args)
556{
557 PyObject *typ;
558 PyObject *tb = NULL;
559 PyObject *val = NULL;
560
561 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
562 return NULL;
563 }
564
565 return _gen_throw(gen, 1, typ, val, tb);
566}
567
568
569static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000570gen_iternext(PyGenObject *gen)
571{
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300572 PyObject *result;
573 assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
574 if (gen_send_ex2(gen, NULL, &result, 0, 0) == PYGEN_RETURN) {
575 if (result != Py_None) {
576 _PyGen_SetStopIterationValue(result);
577 }
578 Py_CLEAR(result);
579 }
580 return result;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000581}
582
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000583/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200584 * Set StopIteration with specified value. Value can be arbitrary object
585 * or NULL.
586 *
587 * Returns 0 if StopIteration is set and -1 if any other exception is set.
588 */
589int
590_PyGen_SetStopIterationValue(PyObject *value)
591{
592 PyObject *e;
593
594 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400595 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200596 {
597 /* Delay exception instantiation if we can */
598 PyErr_SetObject(PyExc_StopIteration, value);
599 return 0;
600 }
601 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100602 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200603 *
604 * We do this to handle a situation when "value" is a tuple, in which
605 * case PyErr_SetObject would set the value of StopIteration to
606 * the first element of the tuple.
607 *
608 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
609 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100610 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200611 if (e == NULL) {
612 return -1;
613 }
614 PyErr_SetObject(PyExc_StopIteration, e);
615 Py_DECREF(e);
616 return 0;
617}
618
619/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000620 * If StopIteration exception is set, fetches its 'value'
621 * attribute if any, otherwise sets pvalue to None.
622 *
623 * Returns 0 if no exception or StopIteration is set.
624 * If any other exception is set, returns -1 and leaves
625 * pvalue unchanged.
626 */
627
628int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200629_PyGen_FetchStopIterationValue(PyObject **pvalue)
630{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000631 PyObject *et, *ev, *tb;
632 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500633
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000634 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
635 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200636 if (ev) {
637 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300638 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200639 value = ((PyStopIterationObject *)ev)->value;
640 Py_INCREF(value);
641 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200642 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
643 /* Avoid normalisation and take ev as value.
644 *
645 * Normalization is required if the value is a tuple, in
646 * that case the value of StopIteration would be set to
647 * the first element of the tuple.
648 *
649 * (See _PyErr_CreateException code for details.)
650 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200651 value = ev;
652 } else {
653 /* normalisation required */
654 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300655 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200656 PyErr_Restore(et, ev, tb);
657 return -1;
658 }
659 value = ((PyStopIterationObject *)ev)->value;
660 Py_INCREF(value);
661 Py_DECREF(ev);
662 }
663 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000664 Py_XDECREF(et);
665 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000666 } else if (PyErr_Occurred()) {
667 return -1;
668 }
669 if (value == NULL) {
670 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100671 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000672 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000673 *pvalue = value;
674 return 0;
675}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000676
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000677static PyObject *
678gen_repr(PyGenObject *gen)
679{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400680 return PyUnicode_FromFormat("<generator object %S at %p>",
681 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000682}
683
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000684static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200685gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000686{
Victor Stinner40ee3012014-06-16 15:59:28 +0200687 Py_INCREF(op->gi_name);
688 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000689}
690
Victor Stinner40ee3012014-06-16 15:59:28 +0200691static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200692gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200693{
Victor Stinner40ee3012014-06-16 15:59:28 +0200694 /* Not legal to del gen.gi_name or to set it to anything
695 * other than a string object. */
696 if (value == NULL || !PyUnicode_Check(value)) {
697 PyErr_SetString(PyExc_TypeError,
698 "__name__ must be set to a string object");
699 return -1;
700 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200701 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300702 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200703 return 0;
704}
705
706static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200707gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200708{
709 Py_INCREF(op->gi_qualname);
710 return op->gi_qualname;
711}
712
713static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200714gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200715{
Victor Stinner40ee3012014-06-16 15:59:28 +0200716 /* Not legal to del gen.__qualname__ or to set it to anything
717 * other than a string object. */
718 if (value == NULL || !PyUnicode_Check(value)) {
719 PyErr_SetString(PyExc_TypeError,
720 "__qualname__ must be set to a string object");
721 return -1;
722 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200723 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300724 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200725 return 0;
726}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000727
Yury Selivanove13f8f32015-07-03 00:23:30 -0400728static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200729gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400730{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500731 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400732 if (yf == NULL)
733 Py_RETURN_NONE;
734 return yf;
735}
736
Mark Shannoncb9879b2020-07-17 11:44:23 +0100737
738static PyObject *
739gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
740{
741 if (gen->gi_frame == NULL) {
742 Py_RETURN_FALSE;
743 }
744 return PyBool_FromLong(_PyFrame_IsExecuting(gen->gi_frame));
745}
746
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000747static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200748 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
749 PyDoc_STR("name of the generator")},
750 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
751 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400752 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
753 PyDoc_STR("object being iterated by yield from, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100754 {"gi_running", (getter)gen_getrunning, NULL, NULL},
Victor Stinner40ee3012014-06-16 15:59:28 +0200755 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000756};
757
Martin v. Löwise440e472004-06-01 15:22:42 +0000758static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200759 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Victor Stinner40ee3012014-06-16 15:59:28 +0200760 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000762};
763
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000764static PyMethodDef gen_methods[] = {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300765 {"send",(PyCFunction)gen_send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
767 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
768 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000769};
770
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800771static PyAsyncMethods gen_as_async = {
772 0, /* am_await */
773 0, /* am_aiter */
774 0, /* am_anext */
775 (sendfunc)PyGen_am_send, /* am_send */
776};
777
778
Martin v. Löwise440e472004-06-01 15:22:42 +0000779PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyVarObject_HEAD_INIT(&PyType_Type, 0)
781 "generator", /* tp_name */
782 sizeof(PyGenObject), /* tp_basicsize */
783 0, /* tp_itemsize */
784 /* methods */
785 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200786 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 0, /* tp_getattr */
788 0, /* tp_setattr */
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800789 &gen_as_async, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 (reprfunc)gen_repr, /* tp_repr */
791 0, /* tp_as_number */
792 0, /* tp_as_sequence */
793 0, /* tp_as_mapping */
794 0, /* tp_hash */
795 0, /* tp_call */
796 0, /* tp_str */
797 PyObject_GenericGetAttr, /* tp_getattro */
798 0, /* tp_setattro */
799 0, /* tp_as_buffer */
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800800 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
801 Py_TPFLAGS_HAVE_AM_SEND, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 0, /* tp_doc */
803 (traverseproc)gen_traverse, /* tp_traverse */
804 0, /* tp_clear */
805 0, /* tp_richcompare */
806 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400807 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 (iternextfunc)gen_iternext, /* tp_iternext */
809 gen_methods, /* tp_methods */
810 gen_memberlist, /* tp_members */
811 gen_getsetlist, /* tp_getset */
812 0, /* tp_base */
813 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 0, /* tp_descr_get */
816 0, /* tp_descr_set */
817 0, /* tp_dictoffset */
818 0, /* tp_init */
819 0, /* tp_alloc */
820 0, /* tp_new */
821 0, /* tp_free */
822 0, /* tp_is_gc */
823 0, /* tp_bases */
824 0, /* tp_mro */
825 0, /* tp_cache */
826 0, /* tp_subclasses */
827 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200828 0, /* tp_del */
829 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200830 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000831};
832
Yury Selivanov5376ba92015-06-22 12:19:30 -0400833static PyObject *
834gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
835 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000836{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400837 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (gen == NULL) {
839 Py_DECREF(f);
840 return NULL;
841 }
842 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200843 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 Py_INCREF(f->f_code);
845 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100847 gen->gi_exc_state.exc_type = NULL;
848 gen->gi_exc_state.exc_value = NULL;
849 gen->gi_exc_state.exc_traceback = NULL;
850 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200851 if (name != NULL)
852 gen->gi_name = name;
853 else
854 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
855 Py_INCREF(gen->gi_name);
856 if (qualname != NULL)
857 gen->gi_qualname = qualname;
858 else
859 gen->gi_qualname = gen->gi_name;
860 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 _PyObject_GC_TRACK(gen);
862 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000863}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000864
Victor Stinner40ee3012014-06-16 15:59:28 +0200865PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400866PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
867{
868 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
869}
870
871PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200872PyGen_New(PyFrameObject *f)
873{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400874 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200875}
876
Yury Selivanov5376ba92015-06-22 12:19:30 -0400877/* Coroutine Object */
878
879typedef struct {
880 PyObject_HEAD
881 PyCoroObject *cw_coroutine;
882} PyCoroWrapper;
883
884static int
885gen_is_coroutine(PyObject *o)
886{
887 if (PyGen_CheckExact(o)) {
888 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
889 if (code->co_flags & CO_ITERABLE_COROUTINE) {
890 return 1;
891 }
892 }
893 return 0;
894}
895
Yury Selivanov75445082015-05-11 22:57:16 -0400896/*
897 * This helper function returns an awaitable for `o`:
898 * - `o` if `o` is a coroutine-object;
899 * - `type(o)->tp_as_async->am_await(o)`
900 *
901 * Raises a TypeError if it's not possible to return
902 * an awaitable and returns NULL.
903 */
904PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400905_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400906{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400907 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400908 PyTypeObject *ot;
909
Yury Selivanov5376ba92015-06-22 12:19:30 -0400910 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
911 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400912 Py_INCREF(o);
913 return o;
914 }
915
916 ot = Py_TYPE(o);
917 if (ot->tp_as_async != NULL) {
918 getter = ot->tp_as_async->am_await;
919 }
920 if (getter != NULL) {
921 PyObject *res = (*getter)(o);
922 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400923 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
924 /* __await__ must return an *iterator*, not
925 a coroutine or another awaitable (see PEP 492) */
926 PyErr_SetString(PyExc_TypeError,
927 "__await__() returned a coroutine");
928 Py_CLEAR(res);
929 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400930 PyErr_Format(PyExc_TypeError,
931 "__await__() returned non-iterator "
932 "of type '%.100s'",
933 Py_TYPE(res)->tp_name);
934 Py_CLEAR(res);
935 }
Yury Selivanov75445082015-05-11 22:57:16 -0400936 }
937 return res;
938 }
939
940 PyErr_Format(PyExc_TypeError,
941 "object %.100s can't be used in 'await' expression",
942 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400943 return NULL;
944}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400945
946static PyObject *
947coro_repr(PyCoroObject *coro)
948{
949 return PyUnicode_FromFormat("<coroutine object %S at %p>",
950 coro->cr_qualname, coro);
951}
952
953static PyObject *
954coro_await(PyCoroObject *coro)
955{
956 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
957 if (cw == NULL) {
958 return NULL;
959 }
960 Py_INCREF(coro);
961 cw->cw_coroutine = coro;
962 _PyObject_GC_TRACK(cw);
963 return (PyObject *)cw;
964}
965
Yury Selivanove13f8f32015-07-03 00:23:30 -0400966static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200967coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400968{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500969 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400970 if (yf == NULL)
971 Py_RETURN_NONE;
972 return yf;
973}
974
Mark Shannoncb9879b2020-07-17 11:44:23 +0100975static PyObject *
976cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
977{
978 if (coro->cr_frame == NULL) {
979 Py_RETURN_FALSE;
980 }
981 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
982}
983
Yury Selivanov5376ba92015-06-22 12:19:30 -0400984static PyGetSetDef coro_getsetlist[] = {
985 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
986 PyDoc_STR("name of the coroutine")},
987 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
988 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400989 {"cr_await", (getter)coro_get_cr_await, NULL,
990 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100991 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400992 {NULL} /* Sentinel */
993};
994
995static PyMemberDef coro_memberlist[] = {
996 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400997 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800998 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400999 {NULL} /* Sentinel */
1000};
1001
1002PyDoc_STRVAR(coro_send_doc,
1003"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001004return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001005
1006PyDoc_STRVAR(coro_throw_doc,
1007"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001008return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001009
1010PyDoc_STRVAR(coro_close_doc,
1011"close() -> raise GeneratorExit inside coroutine.");
1012
1013static PyMethodDef coro_methods[] = {
Vladimir Matveev037245c2020-10-09 17:15:15 -07001014 {"send",(PyCFunction)gen_send, METH_O, coro_send_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001015 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1016 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1017 {NULL, NULL} /* Sentinel */
1018};
1019
1020static PyAsyncMethods coro_as_async = {
1021 (unaryfunc)coro_await, /* am_await */
1022 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001023 0, /* am_anext */
1024 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001025};
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 */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001048 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1049 Py_TPFLAGS_HAVE_AM_SEND, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001050 0, /* tp_doc */
1051 (traverseproc)gen_traverse, /* tp_traverse */
1052 0, /* tp_clear */
1053 0, /* tp_richcompare */
1054 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1055 0, /* tp_iter */
1056 0, /* tp_iternext */
1057 coro_methods, /* tp_methods */
1058 coro_memberlist, /* tp_members */
1059 coro_getsetlist, /* tp_getset */
1060 0, /* tp_base */
1061 0, /* tp_dict */
1062 0, /* tp_descr_get */
1063 0, /* tp_descr_set */
1064 0, /* tp_dictoffset */
1065 0, /* tp_init */
1066 0, /* tp_alloc */
1067 0, /* tp_new */
1068 0, /* tp_free */
1069 0, /* tp_is_gc */
1070 0, /* tp_bases */
1071 0, /* tp_mro */
1072 0, /* tp_cache */
1073 0, /* tp_subclasses */
1074 0, /* tp_weaklist */
1075 0, /* tp_del */
1076 0, /* tp_version_tag */
1077 _PyGen_Finalize, /* tp_finalize */
1078};
1079
1080static void
1081coro_wrapper_dealloc(PyCoroWrapper *cw)
1082{
1083 _PyObject_GC_UNTRACK((PyObject *)cw);
1084 Py_CLEAR(cw->cw_coroutine);
1085 PyObject_GC_Del(cw);
1086}
1087
1088static PyObject *
1089coro_wrapper_iternext(PyCoroWrapper *cw)
1090{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001091 return gen_iternext((PyGenObject *)cw->cw_coroutine);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001092}
1093
1094static PyObject *
1095coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1096{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001097 return gen_send((PyGenObject *)cw->cw_coroutine, arg);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001098}
1099
1100static PyObject *
1101coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1102{
1103 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1104}
1105
1106static PyObject *
1107coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1108{
1109 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1110}
1111
1112static int
1113coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1114{
1115 Py_VISIT((PyObject *)cw->cw_coroutine);
1116 return 0;
1117}
1118
1119static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001120 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1121 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1122 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001123 {NULL, NULL} /* Sentinel */
1124};
1125
1126PyTypeObject _PyCoroWrapper_Type = {
1127 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1128 "coroutine_wrapper",
1129 sizeof(PyCoroWrapper), /* tp_basicsize */
1130 0, /* tp_itemsize */
1131 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001132 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001133 0, /* tp_getattr */
1134 0, /* tp_setattr */
1135 0, /* tp_as_async */
1136 0, /* tp_repr */
1137 0, /* tp_as_number */
1138 0, /* tp_as_sequence */
1139 0, /* tp_as_mapping */
1140 0, /* tp_hash */
1141 0, /* tp_call */
1142 0, /* tp_str */
1143 PyObject_GenericGetAttr, /* tp_getattro */
1144 0, /* tp_setattro */
1145 0, /* tp_as_buffer */
1146 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1147 "A wrapper object implementing __await__ for coroutines.",
1148 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1149 0, /* tp_clear */
1150 0, /* tp_richcompare */
1151 0, /* tp_weaklistoffset */
1152 PyObject_SelfIter, /* tp_iter */
1153 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1154 coro_wrapper_methods, /* tp_methods */
1155 0, /* tp_members */
1156 0, /* tp_getset */
1157 0, /* tp_base */
1158 0, /* tp_dict */
1159 0, /* tp_descr_get */
1160 0, /* tp_descr_set */
1161 0, /* tp_dictoffset */
1162 0, /* tp_init */
1163 0, /* tp_alloc */
1164 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001165 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001166};
1167
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001168static PyObject *
1169compute_cr_origin(int origin_depth)
1170{
1171 PyFrameObject *frame = PyEval_GetFrame();
1172 /* First count how many frames we have */
1173 int frame_count = 0;
1174 for (; frame && frame_count < origin_depth; ++frame_count) {
1175 frame = frame->f_back;
1176 }
1177
1178 /* Now collect them */
1179 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001180 if (cr_origin == NULL) {
1181 return NULL;
1182 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001183 frame = PyEval_GetFrame();
1184 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001185 PyCodeObject *code = frame->f_code;
1186 PyObject *frameinfo = Py_BuildValue("OiO",
1187 code->co_filename,
1188 PyFrame_GetLineNumber(frame),
1189 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001190 if (!frameinfo) {
1191 Py_DECREF(cr_origin);
1192 return NULL;
1193 }
1194 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1195 frame = frame->f_back;
1196 }
1197
1198 return cr_origin;
1199}
1200
Yury Selivanov5376ba92015-06-22 12:19:30 -04001201PyObject *
1202PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1203{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001204 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1205 if (!coro) {
1206 return NULL;
1207 }
1208
Victor Stinner50b48572018-11-01 01:51:40 +01001209 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001210 int origin_depth = tstate->coroutine_origin_tracking_depth;
1211
1212 if (origin_depth == 0) {
1213 ((PyCoroObject *)coro)->cr_origin = NULL;
1214 } else {
1215 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001216 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001217 if (!cr_origin) {
1218 Py_DECREF(coro);
1219 return NULL;
1220 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001221 }
1222
1223 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001224}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001225
1226
Yury Selivanoveb636452016-09-08 22:01:51 -07001227/* ========= Asynchronous Generators ========= */
1228
1229
1230typedef enum {
1231 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1232 AWAITABLE_STATE_ITER, /* being iterated */
1233 AWAITABLE_STATE_CLOSED, /* closed */
1234} AwaitableState;
1235
1236
Victor Stinner78a02c22020-06-05 02:34:14 +02001237typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001238 PyObject_HEAD
1239 PyAsyncGenObject *ags_gen;
1240
1241 /* Can be NULL, when in the __anext__() mode
1242 (equivalent of "asend(None)") */
1243 PyObject *ags_sendval;
1244
1245 AwaitableState ags_state;
1246} PyAsyncGenASend;
1247
1248
Victor Stinner78a02c22020-06-05 02:34:14 +02001249typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001250 PyObject_HEAD
1251 PyAsyncGenObject *agt_gen;
1252
1253 /* Can be NULL, when in the "aclose()" mode
1254 (equivalent of "athrow(GeneratorExit)") */
1255 PyObject *agt_args;
1256
1257 AwaitableState agt_state;
1258} PyAsyncGenAThrow;
1259
1260
Victor Stinner78a02c22020-06-05 02:34:14 +02001261typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001262 PyObject_HEAD
1263 PyObject *agw_val;
1264} _PyAsyncGenWrappedValue;
1265
1266
Yury Selivanoveb636452016-09-08 22:01:51 -07001267#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001268 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001269
1270#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001271 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001272
1273
1274static int
1275async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1276{
1277 Py_VISIT(gen->ag_finalizer);
1278 return gen_traverse((PyGenObject*)gen, visit, arg);
1279}
1280
1281
1282static PyObject *
1283async_gen_repr(PyAsyncGenObject *o)
1284{
1285 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1286 o->ag_qualname, o);
1287}
1288
1289
1290static int
1291async_gen_init_hooks(PyAsyncGenObject *o)
1292{
1293 PyThreadState *tstate;
1294 PyObject *finalizer;
1295 PyObject *firstiter;
1296
1297 if (o->ag_hooks_inited) {
1298 return 0;
1299 }
1300
1301 o->ag_hooks_inited = 1;
1302
Victor Stinner50b48572018-11-01 01:51:40 +01001303 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001304
1305 finalizer = tstate->async_gen_finalizer;
1306 if (finalizer) {
1307 Py_INCREF(finalizer);
1308 o->ag_finalizer = finalizer;
1309 }
1310
1311 firstiter = tstate->async_gen_firstiter;
1312 if (firstiter) {
1313 PyObject *res;
1314
1315 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001316 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001317 Py_DECREF(firstiter);
1318 if (res == NULL) {
1319 return 1;
1320 }
1321 Py_DECREF(res);
1322 }
1323
1324 return 0;
1325}
1326
1327
1328static PyObject *
1329async_gen_anext(PyAsyncGenObject *o)
1330{
1331 if (async_gen_init_hooks(o)) {
1332 return NULL;
1333 }
1334 return async_gen_asend_new(o, NULL);
1335}
1336
1337
1338static PyObject *
1339async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1340{
1341 if (async_gen_init_hooks(o)) {
1342 return NULL;
1343 }
1344 return async_gen_asend_new(o, arg);
1345}
1346
1347
1348static PyObject *
1349async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1350{
1351 if (async_gen_init_hooks(o)) {
1352 return NULL;
1353 }
1354 return async_gen_athrow_new(o, NULL);
1355}
1356
1357static PyObject *
1358async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1359{
1360 if (async_gen_init_hooks(o)) {
1361 return NULL;
1362 }
1363 return async_gen_athrow_new(o, args);
1364}
1365
1366
1367static PyGetSetDef async_gen_getsetlist[] = {
1368 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1369 PyDoc_STR("name of the async generator")},
1370 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1371 PyDoc_STR("qualified name of the async generator")},
1372 {"ag_await", (getter)coro_get_cr_await, NULL,
1373 PyDoc_STR("object being awaited on, or None")},
1374 {NULL} /* Sentinel */
1375};
1376
1377static PyMemberDef async_gen_memberlist[] = {
1378 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001379 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1380 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001381 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1382 {NULL} /* Sentinel */
1383};
1384
1385PyDoc_STRVAR(async_aclose_doc,
1386"aclose() -> raise GeneratorExit inside generator.");
1387
1388PyDoc_STRVAR(async_asend_doc,
1389"asend(v) -> send 'v' in generator.");
1390
1391PyDoc_STRVAR(async_athrow_doc,
1392"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1393
1394static PyMethodDef async_gen_methods[] = {
1395 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1396 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1397 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001398 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1399 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001400 {NULL, NULL} /* Sentinel */
1401};
1402
1403
1404static PyAsyncMethods async_gen_as_async = {
1405 0, /* am_await */
1406 PyObject_SelfIter, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001407 (unaryfunc)async_gen_anext, /* am_anext */
1408 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001409};
1410
1411
1412PyTypeObject PyAsyncGen_Type = {
1413 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1414 "async_generator", /* tp_name */
1415 sizeof(PyAsyncGenObject), /* tp_basicsize */
1416 0, /* tp_itemsize */
1417 /* methods */
1418 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001419 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001420 0, /* tp_getattr */
1421 0, /* tp_setattr */
1422 &async_gen_as_async, /* tp_as_async */
1423 (reprfunc)async_gen_repr, /* tp_repr */
1424 0, /* tp_as_number */
1425 0, /* tp_as_sequence */
1426 0, /* tp_as_mapping */
1427 0, /* tp_hash */
1428 0, /* tp_call */
1429 0, /* tp_str */
1430 PyObject_GenericGetAttr, /* tp_getattro */
1431 0, /* tp_setattro */
1432 0, /* tp_as_buffer */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001433 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1434 Py_TPFLAGS_HAVE_AM_SEND, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001435 0, /* tp_doc */
1436 (traverseproc)async_gen_traverse, /* tp_traverse */
1437 0, /* tp_clear */
1438 0, /* tp_richcompare */
1439 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1440 0, /* tp_iter */
1441 0, /* tp_iternext */
1442 async_gen_methods, /* tp_methods */
1443 async_gen_memberlist, /* tp_members */
1444 async_gen_getsetlist, /* tp_getset */
1445 0, /* tp_base */
1446 0, /* tp_dict */
1447 0, /* tp_descr_get */
1448 0, /* tp_descr_set */
1449 0, /* tp_dictoffset */
1450 0, /* tp_init */
1451 0, /* tp_alloc */
1452 0, /* tp_new */
1453 0, /* tp_free */
1454 0, /* tp_is_gc */
1455 0, /* tp_bases */
1456 0, /* tp_mro */
1457 0, /* tp_cache */
1458 0, /* tp_subclasses */
1459 0, /* tp_weaklist */
1460 0, /* tp_del */
1461 0, /* tp_version_tag */
1462 _PyGen_Finalize, /* tp_finalize */
1463};
1464
1465
Victor Stinner522691c2020-06-23 16:40:40 +02001466static struct _Py_async_gen_state *
1467get_async_gen_state(void)
1468{
1469 PyInterpreterState *interp = _PyInterpreterState_GET();
1470 return &interp->async_gen;
1471}
1472
1473
Yury Selivanoveb636452016-09-08 22:01:51 -07001474PyObject *
1475PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1476{
1477 PyAsyncGenObject *o;
1478 o = (PyAsyncGenObject *)gen_new_with_qualname(
1479 &PyAsyncGen_Type, f, name, qualname);
1480 if (o == NULL) {
1481 return NULL;
1482 }
1483 o->ag_finalizer = NULL;
1484 o->ag_closed = 0;
1485 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001486 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001487 return (PyObject*)o;
1488}
1489
1490
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001491void
Victor Stinner78a02c22020-06-05 02:34:14 +02001492_PyAsyncGen_ClearFreeLists(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001493{
Victor Stinner78a02c22020-06-05 02:34:14 +02001494 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1495
1496 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001497 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001498 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001499 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001500 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001501 }
1502
Victor Stinner78a02c22020-06-05 02:34:14 +02001503 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001504 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001505 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001506 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001507 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001508 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001509}
1510
1511void
Victor Stinner78a02c22020-06-05 02:34:14 +02001512_PyAsyncGen_Fini(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001513{
Victor Stinner78a02c22020-06-05 02:34:14 +02001514 _PyAsyncGen_ClearFreeLists(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001515#ifdef Py_DEBUG
1516 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1517 state->value_numfree = -1;
1518 state->asend_numfree = -1;
1519#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001520}
1521
1522
1523static PyObject *
1524async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1525{
1526 if (result == NULL) {
1527 if (!PyErr_Occurred()) {
1528 PyErr_SetNone(PyExc_StopAsyncIteration);
1529 }
1530
1531 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1532 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1533 ) {
1534 gen->ag_closed = 1;
1535 }
1536
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001537 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001538 return NULL;
1539 }
1540
1541 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1542 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001543 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001544 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001545 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001546 return NULL;
1547 }
1548
1549 return result;
1550}
1551
1552
1553/* ---------- Async Generator ASend Awaitable ------------ */
1554
1555
1556static void
1557async_gen_asend_dealloc(PyAsyncGenASend *o)
1558{
Yury Selivanov29310c42016-11-08 19:46:22 -05001559 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001560 Py_CLEAR(o->ags_gen);
1561 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001562 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001563#ifdef Py_DEBUG
1564 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1565 assert(state->asend_numfree != -1);
1566#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001567 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001568 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001569 state->asend_freelist[state->asend_numfree++] = o;
1570 }
1571 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001572 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001573 }
1574}
1575
Yury Selivanov29310c42016-11-08 19:46:22 -05001576static int
1577async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1578{
1579 Py_VISIT(o->ags_gen);
1580 Py_VISIT(o->ags_sendval);
1581 return 0;
1582}
1583
Yury Selivanoveb636452016-09-08 22:01:51 -07001584
1585static PyObject *
1586async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1587{
1588 PyObject *result;
1589
1590 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001591 PyErr_SetString(
1592 PyExc_RuntimeError,
1593 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001594 return NULL;
1595 }
1596
1597 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001598 if (o->ags_gen->ag_running_async) {
1599 PyErr_SetString(
1600 PyExc_RuntimeError,
1601 "anext(): asynchronous generator is already running");
1602 return NULL;
1603 }
1604
Yury Selivanoveb636452016-09-08 22:01:51 -07001605 if (arg == NULL || arg == Py_None) {
1606 arg = o->ags_sendval;
1607 }
1608 o->ags_state = AWAITABLE_STATE_ITER;
1609 }
1610
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001611 o->ags_gen->ag_running_async = 1;
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001612 result = gen_send((PyGenObject*)o->ags_gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001613 result = async_gen_unwrap_value(o->ags_gen, result);
1614
1615 if (result == NULL) {
1616 o->ags_state = AWAITABLE_STATE_CLOSED;
1617 }
1618
1619 return result;
1620}
1621
1622
1623static PyObject *
1624async_gen_asend_iternext(PyAsyncGenASend *o)
1625{
1626 return async_gen_asend_send(o, NULL);
1627}
1628
1629
1630static PyObject *
1631async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1632{
1633 PyObject *result;
1634
1635 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001636 PyErr_SetString(
1637 PyExc_RuntimeError,
1638 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001639 return NULL;
1640 }
1641
1642 result = gen_throw((PyGenObject*)o->ags_gen, args);
1643 result = async_gen_unwrap_value(o->ags_gen, result);
1644
1645 if (result == NULL) {
1646 o->ags_state = AWAITABLE_STATE_CLOSED;
1647 }
1648
1649 return result;
1650}
1651
1652
1653static PyObject *
1654async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1655{
1656 o->ags_state = AWAITABLE_STATE_CLOSED;
1657 Py_RETURN_NONE;
1658}
1659
1660
1661static PyMethodDef async_gen_asend_methods[] = {
1662 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1663 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1664 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1665 {NULL, NULL} /* Sentinel */
1666};
1667
1668
1669static PyAsyncMethods async_gen_asend_as_async = {
1670 PyObject_SelfIter, /* am_await */
1671 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001672 0, /* am_anext */
1673 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001674};
1675
1676
1677PyTypeObject _PyAsyncGenASend_Type = {
1678 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1679 "async_generator_asend", /* tp_name */
1680 sizeof(PyAsyncGenASend), /* tp_basicsize */
1681 0, /* tp_itemsize */
1682 /* methods */
1683 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001684 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001685 0, /* tp_getattr */
1686 0, /* tp_setattr */
1687 &async_gen_asend_as_async, /* tp_as_async */
1688 0, /* tp_repr */
1689 0, /* tp_as_number */
1690 0, /* tp_as_sequence */
1691 0, /* tp_as_mapping */
1692 0, /* tp_hash */
1693 0, /* tp_call */
1694 0, /* tp_str */
1695 PyObject_GenericGetAttr, /* tp_getattro */
1696 0, /* tp_setattro */
1697 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001698 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001699 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001700 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001701 0, /* tp_clear */
1702 0, /* tp_richcompare */
1703 0, /* tp_weaklistoffset */
1704 PyObject_SelfIter, /* tp_iter */
1705 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1706 async_gen_asend_methods, /* tp_methods */
1707 0, /* tp_members */
1708 0, /* tp_getset */
1709 0, /* tp_base */
1710 0, /* tp_dict */
1711 0, /* tp_descr_get */
1712 0, /* tp_descr_set */
1713 0, /* tp_dictoffset */
1714 0, /* tp_init */
1715 0, /* tp_alloc */
1716 0, /* tp_new */
1717};
1718
1719
1720static PyObject *
1721async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1722{
1723 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001724 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001725#ifdef Py_DEBUG
1726 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1727 assert(state->asend_numfree != -1);
1728#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001729 if (state->asend_numfree) {
1730 state->asend_numfree--;
1731 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001732 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001733 }
1734 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001735 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001736 if (o == NULL) {
1737 return NULL;
1738 }
1739 }
1740
1741 Py_INCREF(gen);
1742 o->ags_gen = gen;
1743
1744 Py_XINCREF(sendval);
1745 o->ags_sendval = sendval;
1746
1747 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001748
1749 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001750 return (PyObject*)o;
1751}
1752
1753
1754/* ---------- Async Generator Value Wrapper ------------ */
1755
1756
1757static void
1758async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1759{
Yury Selivanov29310c42016-11-08 19:46:22 -05001760 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001761 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001762 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001763#ifdef Py_DEBUG
1764 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1765 assert(state->value_numfree != -1);
1766#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001767 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001768 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001769 state->value_freelist[state->value_numfree++] = o;
1770 }
1771 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001772 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001773 }
1774}
1775
1776
Yury Selivanov29310c42016-11-08 19:46:22 -05001777static int
1778async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1779 visitproc visit, void *arg)
1780{
1781 Py_VISIT(o->agw_val);
1782 return 0;
1783}
1784
1785
Yury Selivanoveb636452016-09-08 22:01:51 -07001786PyTypeObject _PyAsyncGenWrappedValue_Type = {
1787 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1788 "async_generator_wrapped_value", /* tp_name */
1789 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1790 0, /* tp_itemsize */
1791 /* methods */
1792 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001793 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001794 0, /* tp_getattr */
1795 0, /* tp_setattr */
1796 0, /* tp_as_async */
1797 0, /* tp_repr */
1798 0, /* tp_as_number */
1799 0, /* tp_as_sequence */
1800 0, /* tp_as_mapping */
1801 0, /* tp_hash */
1802 0, /* tp_call */
1803 0, /* tp_str */
1804 PyObject_GenericGetAttr, /* tp_getattro */
1805 0, /* tp_setattro */
1806 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001807 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001808 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001809 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001810 0, /* tp_clear */
1811 0, /* tp_richcompare */
1812 0, /* tp_weaklistoffset */
1813 0, /* tp_iter */
1814 0, /* tp_iternext */
1815 0, /* tp_methods */
1816 0, /* tp_members */
1817 0, /* tp_getset */
1818 0, /* tp_base */
1819 0, /* tp_dict */
1820 0, /* tp_descr_get */
1821 0, /* tp_descr_set */
1822 0, /* tp_dictoffset */
1823 0, /* tp_init */
1824 0, /* tp_alloc */
1825 0, /* tp_new */
1826};
1827
1828
1829PyObject *
1830_PyAsyncGenValueWrapperNew(PyObject *val)
1831{
1832 _PyAsyncGenWrappedValue *o;
1833 assert(val);
1834
Victor Stinner522691c2020-06-23 16:40:40 +02001835 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001836#ifdef Py_DEBUG
1837 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1838 assert(state->value_numfree != -1);
1839#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001840 if (state->value_numfree) {
1841 state->value_numfree--;
1842 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001843 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1844 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001845 }
1846 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001847 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1848 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001849 if (o == NULL) {
1850 return NULL;
1851 }
1852 }
1853 o->agw_val = val;
1854 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001855 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001856 return (PyObject*)o;
1857}
1858
1859
1860/* ---------- Async Generator AThrow awaitable ------------ */
1861
1862
1863static void
1864async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1865{
Yury Selivanov29310c42016-11-08 19:46:22 -05001866 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001867 Py_CLEAR(o->agt_gen);
1868 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001869 PyObject_GC_Del(o);
1870}
1871
1872
1873static int
1874async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1875{
1876 Py_VISIT(o->agt_gen);
1877 Py_VISIT(o->agt_args);
1878 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001879}
1880
1881
1882static PyObject *
1883async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1884{
1885 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1886 PyFrameObject *f = gen->gi_frame;
1887 PyObject *retval;
1888
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001889 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001890 PyErr_SetString(
1891 PyExc_RuntimeError,
1892 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001893 return NULL;
1894 }
1895
Mark Shannoncb9879b2020-07-17 11:44:23 +01001896 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001897 o->agt_state = AWAITABLE_STATE_CLOSED;
1898 PyErr_SetNone(PyExc_StopIteration);
1899 return NULL;
1900 }
1901
Yury Selivanoveb636452016-09-08 22:01:51 -07001902 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001903 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001904 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001905 if (o->agt_args == NULL) {
1906 PyErr_SetString(
1907 PyExc_RuntimeError,
1908 "aclose(): asynchronous generator is already running");
1909 }
1910 else {
1911 PyErr_SetString(
1912 PyExc_RuntimeError,
1913 "athrow(): asynchronous generator is already running");
1914 }
1915 return NULL;
1916 }
1917
Yury Selivanoveb636452016-09-08 22:01:51 -07001918 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001919 o->agt_state = AWAITABLE_STATE_CLOSED;
1920 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001921 return NULL;
1922 }
1923
1924 if (arg != Py_None) {
1925 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1926 return NULL;
1927 }
1928
1929 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001930 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001931
1932 if (o->agt_args == NULL) {
1933 /* aclose() mode */
1934 o->agt_gen->ag_closed = 1;
1935
1936 retval = _gen_throw((PyGenObject *)gen,
1937 0, /* Do not close generator when
1938 PyExc_GeneratorExit is passed */
1939 PyExc_GeneratorExit, NULL, NULL);
1940
1941 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1942 Py_DECREF(retval);
1943 goto yield_close;
1944 }
1945 } else {
1946 PyObject *typ;
1947 PyObject *tb = NULL;
1948 PyObject *val = NULL;
1949
1950 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1951 &typ, &val, &tb)) {
1952 return NULL;
1953 }
1954
1955 retval = _gen_throw((PyGenObject *)gen,
1956 0, /* Do not close generator when
1957 PyExc_GeneratorExit is passed */
1958 typ, val, tb);
1959 retval = async_gen_unwrap_value(o->agt_gen, retval);
1960 }
1961 if (retval == NULL) {
1962 goto check_error;
1963 }
1964 return retval;
1965 }
1966
1967 assert(o->agt_state == AWAITABLE_STATE_ITER);
1968
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001969 retval = gen_send((PyGenObject *)gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001970 if (o->agt_args) {
1971 return async_gen_unwrap_value(o->agt_gen, retval);
1972 } else {
1973 /* aclose() mode */
1974 if (retval) {
1975 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1976 Py_DECREF(retval);
1977 goto yield_close;
1978 }
1979 else {
1980 return retval;
1981 }
1982 }
1983 else {
1984 goto check_error;
1985 }
1986 }
1987
1988yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001989 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001990 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001991 PyErr_SetString(
1992 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1993 return NULL;
1994
1995check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001996 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001997 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001998 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1999 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2000 {
Yury Selivanov41782e42016-11-16 18:16:17 -05002001 if (o->agt_args == NULL) {
2002 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04002003 StopAsyncIteration or GeneratorExit; just raise
2004 StopIteration, signalling that this 'aclose()' await
2005 is done.
2006 */
Yury Selivanov41782e42016-11-16 18:16:17 -05002007 PyErr_Clear();
2008 PyErr_SetNone(PyExc_StopIteration);
2009 }
2010 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002011 return NULL;
2012}
2013
2014
2015static PyObject *
2016async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
2017{
2018 PyObject *retval;
2019
Yury Selivanoveb636452016-09-08 22:01:51 -07002020 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02002021 PyErr_SetString(
2022 PyExc_RuntimeError,
2023 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07002024 return NULL;
2025 }
2026
2027 retval = gen_throw((PyGenObject*)o->agt_gen, args);
2028 if (o->agt_args) {
2029 return async_gen_unwrap_value(o->agt_gen, retval);
2030 } else {
2031 /* aclose() mode */
2032 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002033 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002034 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07002035 Py_DECREF(retval);
2036 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2037 return NULL;
2038 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08002039 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2040 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2041 {
2042 /* when aclose() is called we don't want to propagate
2043 StopAsyncIteration or GeneratorExit; just raise
2044 StopIteration, signalling that this 'aclose()' await
2045 is done.
2046 */
2047 PyErr_Clear();
2048 PyErr_SetNone(PyExc_StopIteration);
2049 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002050 return retval;
2051 }
2052}
2053
2054
2055static PyObject *
2056async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2057{
2058 return async_gen_athrow_send(o, Py_None);
2059}
2060
2061
2062static PyObject *
2063async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2064{
2065 o->agt_state = AWAITABLE_STATE_CLOSED;
2066 Py_RETURN_NONE;
2067}
2068
2069
2070static PyMethodDef async_gen_athrow_methods[] = {
2071 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2072 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2073 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2074 {NULL, NULL} /* Sentinel */
2075};
2076
2077
2078static PyAsyncMethods async_gen_athrow_as_async = {
2079 PyObject_SelfIter, /* am_await */
2080 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08002081 0, /* am_anext */
2082 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07002083};
2084
2085
2086PyTypeObject _PyAsyncGenAThrow_Type = {
2087 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2088 "async_generator_athrow", /* tp_name */
2089 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2090 0, /* tp_itemsize */
2091 /* methods */
2092 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002093 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002094 0, /* tp_getattr */
2095 0, /* tp_setattr */
2096 &async_gen_athrow_as_async, /* tp_as_async */
2097 0, /* tp_repr */
2098 0, /* tp_as_number */
2099 0, /* tp_as_sequence */
2100 0, /* tp_as_mapping */
2101 0, /* tp_hash */
2102 0, /* tp_call */
2103 0, /* tp_str */
2104 PyObject_GenericGetAttr, /* tp_getattro */
2105 0, /* tp_setattro */
2106 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002107 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002108 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002109 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002110 0, /* tp_clear */
2111 0, /* tp_richcompare */
2112 0, /* tp_weaklistoffset */
2113 PyObject_SelfIter, /* tp_iter */
2114 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2115 async_gen_athrow_methods, /* tp_methods */
2116 0, /* tp_members */
2117 0, /* tp_getset */
2118 0, /* tp_base */
2119 0, /* tp_dict */
2120 0, /* tp_descr_get */
2121 0, /* tp_descr_set */
2122 0, /* tp_dictoffset */
2123 0, /* tp_init */
2124 0, /* tp_alloc */
2125 0, /* tp_new */
2126};
2127
2128
2129static PyObject *
2130async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2131{
2132 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002133 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002134 if (o == NULL) {
2135 return NULL;
2136 }
2137 o->agt_gen = gen;
2138 o->agt_args = args;
2139 o->agt_state = AWAITABLE_STATE_INIT;
2140 Py_INCREF(gen);
2141 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002142 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002143 return (PyObject*)o;
2144}