blob: eb134ebf4bc8785173365d1728e8fa64b92a41f7 [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
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000311PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400312"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000313
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000314/*
315 * This helper function is used by gen_close and gen_throw to
316 * close a subiterator being delegated to by yield-from.
317 */
318
Antoine Pitrou93963562013-05-14 20:37:52 +0200319static int
320gen_close_iter(PyObject *yf)
321{
322 PyObject *retval = NULL;
323 _Py_IDENTIFIER(close);
324
Yury Selivanoveb636452016-09-08 22:01:51 -0700325 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200326 retval = gen_close((PyGenObject *)yf, NULL);
327 if (retval == NULL)
328 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700329 }
330 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200331 PyObject *meth;
332 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
333 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700334 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200335 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700336 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200337 Py_DECREF(meth);
338 if (retval == NULL)
339 return -1;
340 }
341 }
342 Py_XDECREF(retval);
343 return 0;
344}
345
Yury Selivanovc724bae2016-03-02 11:30:46 -0500346PyObject *
347_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500348{
Antoine Pitrou93963562013-05-14 20:37:52 +0200349 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500350 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200351
Mark Shannoncb9879b2020-07-17 11:44:23 +0100352 if (f) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200353 PyObject *bytecode = f->f_code->co_code;
354 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
355
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100356 if (f->f_lasti < 0) {
357 /* Return immediately if the frame didn't start yet. YIELD_FROM
358 always come after LOAD_CONST: a code object should not start
359 with YIELD_FROM */
360 assert(code[0] != YIELD_FROM);
361 return NULL;
362 }
363
Serhiy Storchakaab874002016-09-11 13:48:15 +0300364 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200365 return NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100366 assert(f->f_stackdepth > 0);
367 yf = f->f_valuestack[f->f_stackdepth-1];
Antoine Pitrou93963562013-05-14 20:37:52 +0200368 Py_INCREF(yf);
369 }
370
371 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500372}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000373
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000374static PyObject *
375gen_close(PyGenObject *gen, PyObject *args)
376{
Antoine Pitrou93963562013-05-14 20:37:52 +0200377 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500378 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200379 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000380
Antoine Pitrou93963562013-05-14 20:37:52 +0200381 if (yf) {
Mark Shannoncb9879b2020-07-17 11:44:23 +0100382 PyFrameState state = gen->gi_frame->f_state;
383 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200384 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100385 gen->gi_frame->f_state = state;
Antoine Pitrou93963562013-05-14 20:37:52 +0200386 Py_DECREF(yf);
387 }
388 if (err == 0)
389 PyErr_SetNone(PyExc_GeneratorExit);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300390 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200391 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200392 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700393 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400394 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700395 } else if (PyAsyncGen_CheckExact(gen)) {
396 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
397 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200398 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400399 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 return NULL;
401 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200402 if (PyErr_ExceptionMatches(PyExc_StopIteration)
403 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
404 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200405 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200406 }
407 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000408}
409
Antoine Pitrou93963562013-05-14 20:37:52 +0200410
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000411PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000412"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
413return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000414
415static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700416_gen_throw(PyGenObject *gen, int close_on_genexit,
417 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000418{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500419 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000420 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000421
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000422 if (yf) {
423 PyObject *ret;
424 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700425 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
426 close_on_genexit
427 ) {
428 /* Asynchronous generators *should not* be closed right away.
429 We have to allow some awaits to work it through, hence the
430 `close_on_genexit` parameter here.
431 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100432 PyFrameState state = gen->gi_frame->f_state;
433 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200434 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100435 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000436 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000437 if (err < 0)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300438 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000439 goto throw_here;
440 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700441 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
442 /* `yf` is a generator or a coroutine. */
Chris Jerdonek8b339612020-07-09 06:27:23 -0700443 PyThreadState *tstate = _PyThreadState_GET();
444 PyFrameObject *f = tstate->frame;
445
Chris Jerdonek8b339612020-07-09 06:27:23 -0700446 /* Since we are fast-tracking things by skipping the eval loop,
447 we need to update the current frame so the stack trace
448 will be reported correctly to the user. */
449 /* XXX We should probably be updating the current frame
450 somewhere in ceval.c. */
451 tstate->frame = gen->gi_frame;
Yury Selivanoveb636452016-09-08 22:01:51 -0700452 /* Close the generator that we are currently iterating with
453 'yield from' or awaiting on with 'await'. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100454 PyFrameState state = gen->gi_frame->f_state;
455 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700456 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
457 typ, val, tb);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100458 gen->gi_frame->f_state = state;
Chris Jerdonek8b339612020-07-09 06:27:23 -0700459 tstate->frame = f;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000460 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700461 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200462 PyObject *meth;
463 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
464 Py_DECREF(yf);
465 return NULL;
466 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000467 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000468 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000469 goto throw_here;
470 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100471 PyFrameState state = gen->gi_frame->f_state;
472 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700473 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100474 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000475 Py_DECREF(meth);
476 }
477 Py_DECREF(yf);
478 if (!ret) {
479 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500480 /* Pop subiterator from stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100481 assert(gen->gi_frame->f_stackdepth > 0);
482 gen->gi_frame->f_stackdepth--;
483 ret = gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth];
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500484 assert(ret == yf);
485 Py_DECREF(ret);
486 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100487 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300488 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000489 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300490 ret = gen_send(gen, val);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000491 Py_DECREF(val);
492 } else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300493 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000494 }
495 }
496 return ret;
497 }
498
499throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* First, check the traceback argument, replacing None with
501 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400502 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400504 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 else if (tb != NULL && !PyTraceBack_Check(tb)) {
506 PyErr_SetString(PyExc_TypeError,
507 "throw() third argument must be a traceback object");
508 return NULL;
509 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_INCREF(typ);
512 Py_XINCREF(val);
513 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000514
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400515 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 else if (PyExceptionInstance_Check(typ)) {
519 /* Raising an instance. The value should be a dummy. */
520 if (val && val != Py_None) {
521 PyErr_SetString(PyExc_TypeError,
522 "instance exception may not have a separate value");
523 goto failed_throw;
524 }
525 else {
526 /* Normalize to raise <class>, <instance> */
527 Py_XDECREF(val);
528 val = typ;
529 typ = PyExceptionInstance_Class(typ);
530 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200531
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400532 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200533 /* Returns NULL if there's no traceback */
534 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 }
536 }
537 else {
538 /* Not something you can raise. throw() fails. */
539 PyErr_Format(PyExc_TypeError,
540 "exceptions must be classes or instances "
541 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000542 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 goto failed_throw;
544 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 PyErr_Restore(typ, val, tb);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300547 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000548
549failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* Didn't use our arguments, so restore their original refcounts */
551 Py_DECREF(typ);
552 Py_XDECREF(val);
553 Py_XDECREF(tb);
554 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000555}
556
557
558static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700559gen_throw(PyGenObject *gen, PyObject *args)
560{
561 PyObject *typ;
562 PyObject *tb = NULL;
563 PyObject *val = NULL;
564
565 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
566 return NULL;
567 }
568
569 return _gen_throw(gen, 1, typ, val, tb);
570}
571
572
573static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000574gen_iternext(PyGenObject *gen)
575{
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300576 PyObject *result;
577 assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
578 if (gen_send_ex2(gen, NULL, &result, 0, 0) == PYGEN_RETURN) {
579 if (result != Py_None) {
580 _PyGen_SetStopIterationValue(result);
581 }
582 Py_CLEAR(result);
583 }
584 return result;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000585}
586
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000587/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200588 * Set StopIteration with specified value. Value can be arbitrary object
589 * or NULL.
590 *
591 * Returns 0 if StopIteration is set and -1 if any other exception is set.
592 */
593int
594_PyGen_SetStopIterationValue(PyObject *value)
595{
596 PyObject *e;
597
598 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400599 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200600 {
601 /* Delay exception instantiation if we can */
602 PyErr_SetObject(PyExc_StopIteration, value);
603 return 0;
604 }
605 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100606 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200607 *
608 * We do this to handle a situation when "value" is a tuple, in which
609 * case PyErr_SetObject would set the value of StopIteration to
610 * the first element of the tuple.
611 *
612 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
613 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100614 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200615 if (e == NULL) {
616 return -1;
617 }
618 PyErr_SetObject(PyExc_StopIteration, e);
619 Py_DECREF(e);
620 return 0;
621}
622
623/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000624 * If StopIteration exception is set, fetches its 'value'
625 * attribute if any, otherwise sets pvalue to None.
626 *
627 * Returns 0 if no exception or StopIteration is set.
628 * If any other exception is set, returns -1 and leaves
629 * pvalue unchanged.
630 */
631
632int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200633_PyGen_FetchStopIterationValue(PyObject **pvalue)
634{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000635 PyObject *et, *ev, *tb;
636 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500637
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000638 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
639 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200640 if (ev) {
641 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300642 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200643 value = ((PyStopIterationObject *)ev)->value;
644 Py_INCREF(value);
645 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200646 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
647 /* Avoid normalisation and take ev as value.
648 *
649 * Normalization is required if the value is a tuple, in
650 * that case the value of StopIteration would be set to
651 * the first element of the tuple.
652 *
653 * (See _PyErr_CreateException code for details.)
654 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200655 value = ev;
656 } else {
657 /* normalisation required */
658 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300659 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200660 PyErr_Restore(et, ev, tb);
661 return -1;
662 }
663 value = ((PyStopIterationObject *)ev)->value;
664 Py_INCREF(value);
665 Py_DECREF(ev);
666 }
667 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000668 Py_XDECREF(et);
669 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000670 } else if (PyErr_Occurred()) {
671 return -1;
672 }
673 if (value == NULL) {
674 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100675 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000676 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000677 *pvalue = value;
678 return 0;
679}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000680
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000681static PyObject *
682gen_repr(PyGenObject *gen)
683{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400684 return PyUnicode_FromFormat("<generator object %S at %p>",
685 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000686}
687
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000688static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200689gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000690{
Victor Stinner40ee3012014-06-16 15:59:28 +0200691 Py_INCREF(op->gi_name);
692 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000693}
694
Victor Stinner40ee3012014-06-16 15:59:28 +0200695static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200696gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200697{
Victor Stinner40ee3012014-06-16 15:59:28 +0200698 /* Not legal to del gen.gi_name or to set it to anything
699 * other than a string object. */
700 if (value == NULL || !PyUnicode_Check(value)) {
701 PyErr_SetString(PyExc_TypeError,
702 "__name__ must be set to a string object");
703 return -1;
704 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200705 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300706 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200707 return 0;
708}
709
710static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200711gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200712{
713 Py_INCREF(op->gi_qualname);
714 return op->gi_qualname;
715}
716
717static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200718gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200719{
Victor Stinner40ee3012014-06-16 15:59:28 +0200720 /* Not legal to del gen.__qualname__ or to set it to anything
721 * other than a string object. */
722 if (value == NULL || !PyUnicode_Check(value)) {
723 PyErr_SetString(PyExc_TypeError,
724 "__qualname__ must be set to a string object");
725 return -1;
726 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200727 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300728 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200729 return 0;
730}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000731
Yury Selivanove13f8f32015-07-03 00:23:30 -0400732static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200733gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400734{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500735 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400736 if (yf == NULL)
737 Py_RETURN_NONE;
738 return yf;
739}
740
Mark Shannoncb9879b2020-07-17 11:44:23 +0100741
742static PyObject *
743gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
744{
745 if (gen->gi_frame == NULL) {
746 Py_RETURN_FALSE;
747 }
748 return PyBool_FromLong(_PyFrame_IsExecuting(gen->gi_frame));
749}
750
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000751static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200752 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
753 PyDoc_STR("name of the generator")},
754 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
755 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400756 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
757 PyDoc_STR("object being iterated by yield from, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100758 {"gi_running", (getter)gen_getrunning, NULL, NULL},
Victor Stinner40ee3012014-06-16 15:59:28 +0200759 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000760};
761
Martin v. Löwise440e472004-06-01 15:22:42 +0000762static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200763 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Victor Stinner40ee3012014-06-16 15:59:28 +0200764 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000766};
767
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000768static PyMethodDef gen_methods[] = {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300769 {"send",(PyCFunction)gen_send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
771 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
772 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000773};
774
Martin v. Löwise440e472004-06-01 15:22:42 +0000775PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyVarObject_HEAD_INIT(&PyType_Type, 0)
777 "generator", /* tp_name */
778 sizeof(PyGenObject), /* tp_basicsize */
779 0, /* tp_itemsize */
780 /* methods */
781 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200782 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 0, /* tp_getattr */
784 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400785 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 (reprfunc)gen_repr, /* tp_repr */
787 0, /* tp_as_number */
788 0, /* tp_as_sequence */
789 0, /* tp_as_mapping */
790 0, /* tp_hash */
791 0, /* tp_call */
792 0, /* tp_str */
793 PyObject_GenericGetAttr, /* tp_getattro */
794 0, /* tp_setattro */
795 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200796 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 0, /* tp_doc */
798 (traverseproc)gen_traverse, /* tp_traverse */
799 0, /* tp_clear */
800 0, /* tp_richcompare */
801 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400802 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 (iternextfunc)gen_iternext, /* tp_iternext */
804 gen_methods, /* tp_methods */
805 gen_memberlist, /* tp_members */
806 gen_getsetlist, /* tp_getset */
807 0, /* tp_base */
808 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 0, /* tp_descr_get */
811 0, /* tp_descr_set */
812 0, /* tp_dictoffset */
813 0, /* tp_init */
814 0, /* tp_alloc */
815 0, /* tp_new */
816 0, /* tp_free */
817 0, /* tp_is_gc */
818 0, /* tp_bases */
819 0, /* tp_mro */
820 0, /* tp_cache */
821 0, /* tp_subclasses */
822 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200823 0, /* tp_del */
824 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200825 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000826};
827
Yury Selivanov5376ba92015-06-22 12:19:30 -0400828static PyObject *
829gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
830 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000831{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400832 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (gen == NULL) {
834 Py_DECREF(f);
835 return NULL;
836 }
837 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200838 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 Py_INCREF(f->f_code);
840 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100842 gen->gi_exc_state.exc_type = NULL;
843 gen->gi_exc_state.exc_value = NULL;
844 gen->gi_exc_state.exc_traceback = NULL;
845 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200846 if (name != NULL)
847 gen->gi_name = name;
848 else
849 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
850 Py_INCREF(gen->gi_name);
851 if (qualname != NULL)
852 gen->gi_qualname = qualname;
853 else
854 gen->gi_qualname = gen->gi_name;
855 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 _PyObject_GC_TRACK(gen);
857 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000858}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000859
Victor Stinner40ee3012014-06-16 15:59:28 +0200860PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400861PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
862{
863 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
864}
865
866PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200867PyGen_New(PyFrameObject *f)
868{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400869 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200870}
871
Yury Selivanov5376ba92015-06-22 12:19:30 -0400872/* Coroutine Object */
873
874typedef struct {
875 PyObject_HEAD
876 PyCoroObject *cw_coroutine;
877} PyCoroWrapper;
878
879static int
880gen_is_coroutine(PyObject *o)
881{
882 if (PyGen_CheckExact(o)) {
883 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
884 if (code->co_flags & CO_ITERABLE_COROUTINE) {
885 return 1;
886 }
887 }
888 return 0;
889}
890
Yury Selivanov75445082015-05-11 22:57:16 -0400891/*
892 * This helper function returns an awaitable for `o`:
893 * - `o` if `o` is a coroutine-object;
894 * - `type(o)->tp_as_async->am_await(o)`
895 *
896 * Raises a TypeError if it's not possible to return
897 * an awaitable and returns NULL.
898 */
899PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400900_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400901{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400902 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400903 PyTypeObject *ot;
904
Yury Selivanov5376ba92015-06-22 12:19:30 -0400905 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
906 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400907 Py_INCREF(o);
908 return o;
909 }
910
911 ot = Py_TYPE(o);
912 if (ot->tp_as_async != NULL) {
913 getter = ot->tp_as_async->am_await;
914 }
915 if (getter != NULL) {
916 PyObject *res = (*getter)(o);
917 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400918 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
919 /* __await__ must return an *iterator*, not
920 a coroutine or another awaitable (see PEP 492) */
921 PyErr_SetString(PyExc_TypeError,
922 "__await__() returned a coroutine");
923 Py_CLEAR(res);
924 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400925 PyErr_Format(PyExc_TypeError,
926 "__await__() returned non-iterator "
927 "of type '%.100s'",
928 Py_TYPE(res)->tp_name);
929 Py_CLEAR(res);
930 }
Yury Selivanov75445082015-05-11 22:57:16 -0400931 }
932 return res;
933 }
934
935 PyErr_Format(PyExc_TypeError,
936 "object %.100s can't be used in 'await' expression",
937 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400938 return NULL;
939}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400940
941static PyObject *
942coro_repr(PyCoroObject *coro)
943{
944 return PyUnicode_FromFormat("<coroutine object %S at %p>",
945 coro->cr_qualname, coro);
946}
947
948static PyObject *
949coro_await(PyCoroObject *coro)
950{
951 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
952 if (cw == NULL) {
953 return NULL;
954 }
955 Py_INCREF(coro);
956 cw->cw_coroutine = coro;
957 _PyObject_GC_TRACK(cw);
958 return (PyObject *)cw;
959}
960
Yury Selivanove13f8f32015-07-03 00:23:30 -0400961static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200962coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400963{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500964 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400965 if (yf == NULL)
966 Py_RETURN_NONE;
967 return yf;
968}
969
Mark Shannoncb9879b2020-07-17 11:44:23 +0100970static PyObject *
971cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
972{
973 if (coro->cr_frame == NULL) {
974 Py_RETURN_FALSE;
975 }
976 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
977}
978
Yury Selivanov5376ba92015-06-22 12:19:30 -0400979static PyGetSetDef coro_getsetlist[] = {
980 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
981 PyDoc_STR("name of the coroutine")},
982 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
983 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400984 {"cr_await", (getter)coro_get_cr_await, NULL,
985 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100986 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400987 {NULL} /* Sentinel */
988};
989
990static PyMemberDef coro_memberlist[] = {
991 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400992 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800993 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400994 {NULL} /* Sentinel */
995};
996
997PyDoc_STRVAR(coro_send_doc,
998"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400999return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001000
1001PyDoc_STRVAR(coro_throw_doc,
1002"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001003return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001004
1005PyDoc_STRVAR(coro_close_doc,
1006"close() -> raise GeneratorExit inside coroutine.");
1007
1008static PyMethodDef coro_methods[] = {
Vladimir Matveev037245c2020-10-09 17:15:15 -07001009 {"send",(PyCFunction)gen_send, METH_O, coro_send_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001010 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1011 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1012 {NULL, NULL} /* Sentinel */
1013};
1014
1015static PyAsyncMethods coro_as_async = {
1016 (unaryfunc)coro_await, /* am_await */
1017 0, /* am_aiter */
1018 0 /* am_anext */
1019};
1020
1021PyTypeObject PyCoro_Type = {
1022 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1023 "coroutine", /* tp_name */
1024 sizeof(PyCoroObject), /* tp_basicsize */
1025 0, /* tp_itemsize */
1026 /* methods */
1027 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001028 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001029 0, /* tp_getattr */
1030 0, /* tp_setattr */
1031 &coro_as_async, /* tp_as_async */
1032 (reprfunc)coro_repr, /* tp_repr */
1033 0, /* tp_as_number */
1034 0, /* tp_as_sequence */
1035 0, /* tp_as_mapping */
1036 0, /* tp_hash */
1037 0, /* tp_call */
1038 0, /* tp_str */
1039 PyObject_GenericGetAttr, /* tp_getattro */
1040 0, /* tp_setattro */
1041 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001042 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001043 0, /* tp_doc */
1044 (traverseproc)gen_traverse, /* tp_traverse */
1045 0, /* tp_clear */
1046 0, /* tp_richcompare */
1047 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1048 0, /* tp_iter */
1049 0, /* tp_iternext */
1050 coro_methods, /* tp_methods */
1051 coro_memberlist, /* tp_members */
1052 coro_getsetlist, /* tp_getset */
1053 0, /* tp_base */
1054 0, /* tp_dict */
1055 0, /* tp_descr_get */
1056 0, /* tp_descr_set */
1057 0, /* tp_dictoffset */
1058 0, /* tp_init */
1059 0, /* tp_alloc */
1060 0, /* tp_new */
1061 0, /* tp_free */
1062 0, /* tp_is_gc */
1063 0, /* tp_bases */
1064 0, /* tp_mro */
1065 0, /* tp_cache */
1066 0, /* tp_subclasses */
1067 0, /* tp_weaklist */
1068 0, /* tp_del */
1069 0, /* tp_version_tag */
1070 _PyGen_Finalize, /* tp_finalize */
1071};
1072
1073static void
1074coro_wrapper_dealloc(PyCoroWrapper *cw)
1075{
1076 _PyObject_GC_UNTRACK((PyObject *)cw);
1077 Py_CLEAR(cw->cw_coroutine);
1078 PyObject_GC_Del(cw);
1079}
1080
1081static PyObject *
1082coro_wrapper_iternext(PyCoroWrapper *cw)
1083{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001084 return gen_iternext((PyGenObject *)cw->cw_coroutine);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001085}
1086
1087static PyObject *
1088coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1089{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001090 return gen_send((PyGenObject *)cw->cw_coroutine, arg);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001091}
1092
1093static PyObject *
1094coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1095{
1096 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1097}
1098
1099static PyObject *
1100coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1101{
1102 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1103}
1104
1105static int
1106coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1107{
1108 Py_VISIT((PyObject *)cw->cw_coroutine);
1109 return 0;
1110}
1111
1112static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001113 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1114 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1115 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001116 {NULL, NULL} /* Sentinel */
1117};
1118
1119PyTypeObject _PyCoroWrapper_Type = {
1120 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1121 "coroutine_wrapper",
1122 sizeof(PyCoroWrapper), /* tp_basicsize */
1123 0, /* tp_itemsize */
1124 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001125 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001126 0, /* tp_getattr */
1127 0, /* tp_setattr */
1128 0, /* tp_as_async */
1129 0, /* tp_repr */
1130 0, /* tp_as_number */
1131 0, /* tp_as_sequence */
1132 0, /* tp_as_mapping */
1133 0, /* tp_hash */
1134 0, /* tp_call */
1135 0, /* tp_str */
1136 PyObject_GenericGetAttr, /* tp_getattro */
1137 0, /* tp_setattro */
1138 0, /* tp_as_buffer */
1139 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1140 "A wrapper object implementing __await__ for coroutines.",
1141 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1142 0, /* tp_clear */
1143 0, /* tp_richcompare */
1144 0, /* tp_weaklistoffset */
1145 PyObject_SelfIter, /* tp_iter */
1146 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1147 coro_wrapper_methods, /* tp_methods */
1148 0, /* tp_members */
1149 0, /* tp_getset */
1150 0, /* tp_base */
1151 0, /* tp_dict */
1152 0, /* tp_descr_get */
1153 0, /* tp_descr_set */
1154 0, /* tp_dictoffset */
1155 0, /* tp_init */
1156 0, /* tp_alloc */
1157 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001158 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001159};
1160
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001161static PyObject *
1162compute_cr_origin(int origin_depth)
1163{
1164 PyFrameObject *frame = PyEval_GetFrame();
1165 /* First count how many frames we have */
1166 int frame_count = 0;
1167 for (; frame && frame_count < origin_depth; ++frame_count) {
1168 frame = frame->f_back;
1169 }
1170
1171 /* Now collect them */
1172 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001173 if (cr_origin == NULL) {
1174 return NULL;
1175 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001176 frame = PyEval_GetFrame();
1177 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001178 PyCodeObject *code = frame->f_code;
1179 PyObject *frameinfo = Py_BuildValue("OiO",
1180 code->co_filename,
1181 PyFrame_GetLineNumber(frame),
1182 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001183 if (!frameinfo) {
1184 Py_DECREF(cr_origin);
1185 return NULL;
1186 }
1187 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1188 frame = frame->f_back;
1189 }
1190
1191 return cr_origin;
1192}
1193
Yury Selivanov5376ba92015-06-22 12:19:30 -04001194PyObject *
1195PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1196{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001197 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1198 if (!coro) {
1199 return NULL;
1200 }
1201
Victor Stinner50b48572018-11-01 01:51:40 +01001202 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001203 int origin_depth = tstate->coroutine_origin_tracking_depth;
1204
1205 if (origin_depth == 0) {
1206 ((PyCoroObject *)coro)->cr_origin = NULL;
1207 } else {
1208 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001209 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001210 if (!cr_origin) {
1211 Py_DECREF(coro);
1212 return NULL;
1213 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001214 }
1215
1216 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001217}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001218
1219
Yury Selivanoveb636452016-09-08 22:01:51 -07001220/* ========= Asynchronous Generators ========= */
1221
1222
1223typedef enum {
1224 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1225 AWAITABLE_STATE_ITER, /* being iterated */
1226 AWAITABLE_STATE_CLOSED, /* closed */
1227} AwaitableState;
1228
1229
Victor Stinner78a02c22020-06-05 02:34:14 +02001230typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001231 PyObject_HEAD
1232 PyAsyncGenObject *ags_gen;
1233
1234 /* Can be NULL, when in the __anext__() mode
1235 (equivalent of "asend(None)") */
1236 PyObject *ags_sendval;
1237
1238 AwaitableState ags_state;
1239} PyAsyncGenASend;
1240
1241
Victor Stinner78a02c22020-06-05 02:34:14 +02001242typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001243 PyObject_HEAD
1244 PyAsyncGenObject *agt_gen;
1245
1246 /* Can be NULL, when in the "aclose()" mode
1247 (equivalent of "athrow(GeneratorExit)") */
1248 PyObject *agt_args;
1249
1250 AwaitableState agt_state;
1251} PyAsyncGenAThrow;
1252
1253
Victor Stinner78a02c22020-06-05 02:34:14 +02001254typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001255 PyObject_HEAD
1256 PyObject *agw_val;
1257} _PyAsyncGenWrappedValue;
1258
1259
Yury Selivanoveb636452016-09-08 22:01:51 -07001260#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001261 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001262
1263#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001264 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001265
1266
1267static int
1268async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1269{
1270 Py_VISIT(gen->ag_finalizer);
1271 return gen_traverse((PyGenObject*)gen, visit, arg);
1272}
1273
1274
1275static PyObject *
1276async_gen_repr(PyAsyncGenObject *o)
1277{
1278 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1279 o->ag_qualname, o);
1280}
1281
1282
1283static int
1284async_gen_init_hooks(PyAsyncGenObject *o)
1285{
1286 PyThreadState *tstate;
1287 PyObject *finalizer;
1288 PyObject *firstiter;
1289
1290 if (o->ag_hooks_inited) {
1291 return 0;
1292 }
1293
1294 o->ag_hooks_inited = 1;
1295
Victor Stinner50b48572018-11-01 01:51:40 +01001296 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001297
1298 finalizer = tstate->async_gen_finalizer;
1299 if (finalizer) {
1300 Py_INCREF(finalizer);
1301 o->ag_finalizer = finalizer;
1302 }
1303
1304 firstiter = tstate->async_gen_firstiter;
1305 if (firstiter) {
1306 PyObject *res;
1307
1308 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001309 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001310 Py_DECREF(firstiter);
1311 if (res == NULL) {
1312 return 1;
1313 }
1314 Py_DECREF(res);
1315 }
1316
1317 return 0;
1318}
1319
1320
1321static PyObject *
1322async_gen_anext(PyAsyncGenObject *o)
1323{
1324 if (async_gen_init_hooks(o)) {
1325 return NULL;
1326 }
1327 return async_gen_asend_new(o, NULL);
1328}
1329
1330
1331static PyObject *
1332async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1333{
1334 if (async_gen_init_hooks(o)) {
1335 return NULL;
1336 }
1337 return async_gen_asend_new(o, arg);
1338}
1339
1340
1341static PyObject *
1342async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1343{
1344 if (async_gen_init_hooks(o)) {
1345 return NULL;
1346 }
1347 return async_gen_athrow_new(o, NULL);
1348}
1349
1350static PyObject *
1351async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1352{
1353 if (async_gen_init_hooks(o)) {
1354 return NULL;
1355 }
1356 return async_gen_athrow_new(o, args);
1357}
1358
1359
1360static PyGetSetDef async_gen_getsetlist[] = {
1361 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1362 PyDoc_STR("name of the async generator")},
1363 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1364 PyDoc_STR("qualified name of the async generator")},
1365 {"ag_await", (getter)coro_get_cr_await, NULL,
1366 PyDoc_STR("object being awaited on, or None")},
1367 {NULL} /* Sentinel */
1368};
1369
1370static PyMemberDef async_gen_memberlist[] = {
1371 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001372 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1373 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001374 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1375 {NULL} /* Sentinel */
1376};
1377
1378PyDoc_STRVAR(async_aclose_doc,
1379"aclose() -> raise GeneratorExit inside generator.");
1380
1381PyDoc_STRVAR(async_asend_doc,
1382"asend(v) -> send 'v' in generator.");
1383
1384PyDoc_STRVAR(async_athrow_doc,
1385"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1386
1387static PyMethodDef async_gen_methods[] = {
1388 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1389 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1390 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001391 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1392 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001393 {NULL, NULL} /* Sentinel */
1394};
1395
1396
1397static PyAsyncMethods async_gen_as_async = {
1398 0, /* am_await */
1399 PyObject_SelfIter, /* am_aiter */
1400 (unaryfunc)async_gen_anext /* am_anext */
1401};
1402
1403
1404PyTypeObject PyAsyncGen_Type = {
1405 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1406 "async_generator", /* tp_name */
1407 sizeof(PyAsyncGenObject), /* tp_basicsize */
1408 0, /* tp_itemsize */
1409 /* methods */
1410 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001411 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001412 0, /* tp_getattr */
1413 0, /* tp_setattr */
1414 &async_gen_as_async, /* tp_as_async */
1415 (reprfunc)async_gen_repr, /* tp_repr */
1416 0, /* tp_as_number */
1417 0, /* tp_as_sequence */
1418 0, /* tp_as_mapping */
1419 0, /* tp_hash */
1420 0, /* tp_call */
1421 0, /* tp_str */
1422 PyObject_GenericGetAttr, /* tp_getattro */
1423 0, /* tp_setattro */
1424 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001426 0, /* tp_doc */
1427 (traverseproc)async_gen_traverse, /* tp_traverse */
1428 0, /* tp_clear */
1429 0, /* tp_richcompare */
1430 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1431 0, /* tp_iter */
1432 0, /* tp_iternext */
1433 async_gen_methods, /* tp_methods */
1434 async_gen_memberlist, /* tp_members */
1435 async_gen_getsetlist, /* tp_getset */
1436 0, /* tp_base */
1437 0, /* tp_dict */
1438 0, /* tp_descr_get */
1439 0, /* tp_descr_set */
1440 0, /* tp_dictoffset */
1441 0, /* tp_init */
1442 0, /* tp_alloc */
1443 0, /* tp_new */
1444 0, /* tp_free */
1445 0, /* tp_is_gc */
1446 0, /* tp_bases */
1447 0, /* tp_mro */
1448 0, /* tp_cache */
1449 0, /* tp_subclasses */
1450 0, /* tp_weaklist */
1451 0, /* tp_del */
1452 0, /* tp_version_tag */
1453 _PyGen_Finalize, /* tp_finalize */
1454};
1455
1456
Victor Stinner522691c2020-06-23 16:40:40 +02001457static struct _Py_async_gen_state *
1458get_async_gen_state(void)
1459{
1460 PyInterpreterState *interp = _PyInterpreterState_GET();
1461 return &interp->async_gen;
1462}
1463
1464
Yury Selivanoveb636452016-09-08 22:01:51 -07001465PyObject *
1466PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1467{
1468 PyAsyncGenObject *o;
1469 o = (PyAsyncGenObject *)gen_new_with_qualname(
1470 &PyAsyncGen_Type, f, name, qualname);
1471 if (o == NULL) {
1472 return NULL;
1473 }
1474 o->ag_finalizer = NULL;
1475 o->ag_closed = 0;
1476 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001477 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001478 return (PyObject*)o;
1479}
1480
1481
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001482void
Victor Stinner78a02c22020-06-05 02:34:14 +02001483_PyAsyncGen_ClearFreeLists(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001484{
Victor Stinner78a02c22020-06-05 02:34:14 +02001485 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1486
1487 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001488 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001489 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001490 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001491 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001492 }
1493
Victor Stinner78a02c22020-06-05 02:34:14 +02001494 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001495 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001496 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001497 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001498 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001499 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001500}
1501
1502void
Victor Stinner78a02c22020-06-05 02:34:14 +02001503_PyAsyncGen_Fini(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001504{
Victor Stinner78a02c22020-06-05 02:34:14 +02001505 _PyAsyncGen_ClearFreeLists(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001506#ifdef Py_DEBUG
1507 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1508 state->value_numfree = -1;
1509 state->asend_numfree = -1;
1510#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001511}
1512
1513
1514static PyObject *
1515async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1516{
1517 if (result == NULL) {
1518 if (!PyErr_Occurred()) {
1519 PyErr_SetNone(PyExc_StopAsyncIteration);
1520 }
1521
1522 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1523 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1524 ) {
1525 gen->ag_closed = 1;
1526 }
1527
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001528 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001529 return NULL;
1530 }
1531
1532 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1533 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001534 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001535 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001536 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001537 return NULL;
1538 }
1539
1540 return result;
1541}
1542
1543
1544/* ---------- Async Generator ASend Awaitable ------------ */
1545
1546
1547static void
1548async_gen_asend_dealloc(PyAsyncGenASend *o)
1549{
Yury Selivanov29310c42016-11-08 19:46:22 -05001550 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001551 Py_CLEAR(o->ags_gen);
1552 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001553 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001554#ifdef Py_DEBUG
1555 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1556 assert(state->asend_numfree != -1);
1557#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001558 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001559 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001560 state->asend_freelist[state->asend_numfree++] = o;
1561 }
1562 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001563 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001564 }
1565}
1566
Yury Selivanov29310c42016-11-08 19:46:22 -05001567static int
1568async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1569{
1570 Py_VISIT(o->ags_gen);
1571 Py_VISIT(o->ags_sendval);
1572 return 0;
1573}
1574
Yury Selivanoveb636452016-09-08 22:01:51 -07001575
1576static PyObject *
1577async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1578{
1579 PyObject *result;
1580
1581 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001582 PyErr_SetString(
1583 PyExc_RuntimeError,
1584 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001585 return NULL;
1586 }
1587
1588 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001589 if (o->ags_gen->ag_running_async) {
1590 PyErr_SetString(
1591 PyExc_RuntimeError,
1592 "anext(): asynchronous generator is already running");
1593 return NULL;
1594 }
1595
Yury Selivanoveb636452016-09-08 22:01:51 -07001596 if (arg == NULL || arg == Py_None) {
1597 arg = o->ags_sendval;
1598 }
1599 o->ags_state = AWAITABLE_STATE_ITER;
1600 }
1601
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001602 o->ags_gen->ag_running_async = 1;
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001603 result = gen_send((PyGenObject*)o->ags_gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001604 result = async_gen_unwrap_value(o->ags_gen, result);
1605
1606 if (result == NULL) {
1607 o->ags_state = AWAITABLE_STATE_CLOSED;
1608 }
1609
1610 return result;
1611}
1612
1613
1614static PyObject *
1615async_gen_asend_iternext(PyAsyncGenASend *o)
1616{
1617 return async_gen_asend_send(o, NULL);
1618}
1619
1620
1621static PyObject *
1622async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1623{
1624 PyObject *result;
1625
1626 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001627 PyErr_SetString(
1628 PyExc_RuntimeError,
1629 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001630 return NULL;
1631 }
1632
1633 result = gen_throw((PyGenObject*)o->ags_gen, args);
1634 result = async_gen_unwrap_value(o->ags_gen, result);
1635
1636 if (result == NULL) {
1637 o->ags_state = AWAITABLE_STATE_CLOSED;
1638 }
1639
1640 return result;
1641}
1642
1643
1644static PyObject *
1645async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1646{
1647 o->ags_state = AWAITABLE_STATE_CLOSED;
1648 Py_RETURN_NONE;
1649}
1650
1651
1652static PyMethodDef async_gen_asend_methods[] = {
1653 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1654 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1655 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1656 {NULL, NULL} /* Sentinel */
1657};
1658
1659
1660static PyAsyncMethods async_gen_asend_as_async = {
1661 PyObject_SelfIter, /* am_await */
1662 0, /* am_aiter */
1663 0 /* am_anext */
1664};
1665
1666
1667PyTypeObject _PyAsyncGenASend_Type = {
1668 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1669 "async_generator_asend", /* tp_name */
1670 sizeof(PyAsyncGenASend), /* tp_basicsize */
1671 0, /* tp_itemsize */
1672 /* methods */
1673 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001674 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001675 0, /* tp_getattr */
1676 0, /* tp_setattr */
1677 &async_gen_asend_as_async, /* tp_as_async */
1678 0, /* tp_repr */
1679 0, /* tp_as_number */
1680 0, /* tp_as_sequence */
1681 0, /* tp_as_mapping */
1682 0, /* tp_hash */
1683 0, /* tp_call */
1684 0, /* tp_str */
1685 PyObject_GenericGetAttr, /* tp_getattro */
1686 0, /* tp_setattro */
1687 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001688 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001689 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001690 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001691 0, /* tp_clear */
1692 0, /* tp_richcompare */
1693 0, /* tp_weaklistoffset */
1694 PyObject_SelfIter, /* tp_iter */
1695 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1696 async_gen_asend_methods, /* tp_methods */
1697 0, /* tp_members */
1698 0, /* tp_getset */
1699 0, /* tp_base */
1700 0, /* tp_dict */
1701 0, /* tp_descr_get */
1702 0, /* tp_descr_set */
1703 0, /* tp_dictoffset */
1704 0, /* tp_init */
1705 0, /* tp_alloc */
1706 0, /* tp_new */
1707};
1708
1709
1710static PyObject *
1711async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1712{
1713 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001714 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001715#ifdef Py_DEBUG
1716 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1717 assert(state->asend_numfree != -1);
1718#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001719 if (state->asend_numfree) {
1720 state->asend_numfree--;
1721 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001722 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001723 }
1724 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001725 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001726 if (o == NULL) {
1727 return NULL;
1728 }
1729 }
1730
1731 Py_INCREF(gen);
1732 o->ags_gen = gen;
1733
1734 Py_XINCREF(sendval);
1735 o->ags_sendval = sendval;
1736
1737 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001738
1739 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001740 return (PyObject*)o;
1741}
1742
1743
1744/* ---------- Async Generator Value Wrapper ------------ */
1745
1746
1747static void
1748async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1749{
Yury Selivanov29310c42016-11-08 19:46:22 -05001750 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001751 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001752 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001753#ifdef Py_DEBUG
1754 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1755 assert(state->value_numfree != -1);
1756#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001757 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001758 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001759 state->value_freelist[state->value_numfree++] = o;
1760 }
1761 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001762 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001763 }
1764}
1765
1766
Yury Selivanov29310c42016-11-08 19:46:22 -05001767static int
1768async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1769 visitproc visit, void *arg)
1770{
1771 Py_VISIT(o->agw_val);
1772 return 0;
1773}
1774
1775
Yury Selivanoveb636452016-09-08 22:01:51 -07001776PyTypeObject _PyAsyncGenWrappedValue_Type = {
1777 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1778 "async_generator_wrapped_value", /* tp_name */
1779 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1780 0, /* tp_itemsize */
1781 /* methods */
1782 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001783 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001784 0, /* tp_getattr */
1785 0, /* tp_setattr */
1786 0, /* tp_as_async */
1787 0, /* tp_repr */
1788 0, /* tp_as_number */
1789 0, /* tp_as_sequence */
1790 0, /* tp_as_mapping */
1791 0, /* tp_hash */
1792 0, /* tp_call */
1793 0, /* tp_str */
1794 PyObject_GenericGetAttr, /* tp_getattro */
1795 0, /* tp_setattro */
1796 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001797 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001798 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001799 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001800 0, /* tp_clear */
1801 0, /* tp_richcompare */
1802 0, /* tp_weaklistoffset */
1803 0, /* tp_iter */
1804 0, /* tp_iternext */
1805 0, /* tp_methods */
1806 0, /* tp_members */
1807 0, /* tp_getset */
1808 0, /* tp_base */
1809 0, /* tp_dict */
1810 0, /* tp_descr_get */
1811 0, /* tp_descr_set */
1812 0, /* tp_dictoffset */
1813 0, /* tp_init */
1814 0, /* tp_alloc */
1815 0, /* tp_new */
1816};
1817
1818
1819PyObject *
1820_PyAsyncGenValueWrapperNew(PyObject *val)
1821{
1822 _PyAsyncGenWrappedValue *o;
1823 assert(val);
1824
Victor Stinner522691c2020-06-23 16:40:40 +02001825 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001826#ifdef Py_DEBUG
1827 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1828 assert(state->value_numfree != -1);
1829#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001830 if (state->value_numfree) {
1831 state->value_numfree--;
1832 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001833 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1834 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001835 }
1836 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001837 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1838 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001839 if (o == NULL) {
1840 return NULL;
1841 }
1842 }
1843 o->agw_val = val;
1844 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001845 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001846 return (PyObject*)o;
1847}
1848
1849
1850/* ---------- Async Generator AThrow awaitable ------------ */
1851
1852
1853static void
1854async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1855{
Yury Selivanov29310c42016-11-08 19:46:22 -05001856 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001857 Py_CLEAR(o->agt_gen);
1858 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001859 PyObject_GC_Del(o);
1860}
1861
1862
1863static int
1864async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1865{
1866 Py_VISIT(o->agt_gen);
1867 Py_VISIT(o->agt_args);
1868 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001869}
1870
1871
1872static PyObject *
1873async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1874{
1875 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1876 PyFrameObject *f = gen->gi_frame;
1877 PyObject *retval;
1878
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001879 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001880 PyErr_SetString(
1881 PyExc_RuntimeError,
1882 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001883 return NULL;
1884 }
1885
Mark Shannoncb9879b2020-07-17 11:44:23 +01001886 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001887 o->agt_state = AWAITABLE_STATE_CLOSED;
1888 PyErr_SetNone(PyExc_StopIteration);
1889 return NULL;
1890 }
1891
Yury Selivanoveb636452016-09-08 22:01:51 -07001892 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001893 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001894 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001895 if (o->agt_args == NULL) {
1896 PyErr_SetString(
1897 PyExc_RuntimeError,
1898 "aclose(): asynchronous generator is already running");
1899 }
1900 else {
1901 PyErr_SetString(
1902 PyExc_RuntimeError,
1903 "athrow(): asynchronous generator is already running");
1904 }
1905 return NULL;
1906 }
1907
Yury Selivanoveb636452016-09-08 22:01:51 -07001908 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001909 o->agt_state = AWAITABLE_STATE_CLOSED;
1910 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001911 return NULL;
1912 }
1913
1914 if (arg != Py_None) {
1915 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1916 return NULL;
1917 }
1918
1919 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001920 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001921
1922 if (o->agt_args == NULL) {
1923 /* aclose() mode */
1924 o->agt_gen->ag_closed = 1;
1925
1926 retval = _gen_throw((PyGenObject *)gen,
1927 0, /* Do not close generator when
1928 PyExc_GeneratorExit is passed */
1929 PyExc_GeneratorExit, NULL, NULL);
1930
1931 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1932 Py_DECREF(retval);
1933 goto yield_close;
1934 }
1935 } else {
1936 PyObject *typ;
1937 PyObject *tb = NULL;
1938 PyObject *val = NULL;
1939
1940 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1941 &typ, &val, &tb)) {
1942 return NULL;
1943 }
1944
1945 retval = _gen_throw((PyGenObject *)gen,
1946 0, /* Do not close generator when
1947 PyExc_GeneratorExit is passed */
1948 typ, val, tb);
1949 retval = async_gen_unwrap_value(o->agt_gen, retval);
1950 }
1951 if (retval == NULL) {
1952 goto check_error;
1953 }
1954 return retval;
1955 }
1956
1957 assert(o->agt_state == AWAITABLE_STATE_ITER);
1958
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001959 retval = gen_send((PyGenObject *)gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001960 if (o->agt_args) {
1961 return async_gen_unwrap_value(o->agt_gen, retval);
1962 } else {
1963 /* aclose() mode */
1964 if (retval) {
1965 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1966 Py_DECREF(retval);
1967 goto yield_close;
1968 }
1969 else {
1970 return retval;
1971 }
1972 }
1973 else {
1974 goto check_error;
1975 }
1976 }
1977
1978yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001979 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001980 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001981 PyErr_SetString(
1982 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1983 return NULL;
1984
1985check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001986 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001987 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001988 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1989 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1990 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001991 if (o->agt_args == NULL) {
1992 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001993 StopAsyncIteration or GeneratorExit; just raise
1994 StopIteration, signalling that this 'aclose()' await
1995 is done.
1996 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001997 PyErr_Clear();
1998 PyErr_SetNone(PyExc_StopIteration);
1999 }
2000 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002001 return NULL;
2002}
2003
2004
2005static PyObject *
2006async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
2007{
2008 PyObject *retval;
2009
Yury Selivanoveb636452016-09-08 22:01:51 -07002010 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02002011 PyErr_SetString(
2012 PyExc_RuntimeError,
2013 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07002014 return NULL;
2015 }
2016
2017 retval = gen_throw((PyGenObject*)o->agt_gen, args);
2018 if (o->agt_args) {
2019 return async_gen_unwrap_value(o->agt_gen, retval);
2020 } else {
2021 /* aclose() mode */
2022 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002023 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002024 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07002025 Py_DECREF(retval);
2026 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2027 return NULL;
2028 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08002029 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2030 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2031 {
2032 /* when aclose() is called we don't want to propagate
2033 StopAsyncIteration or GeneratorExit; just raise
2034 StopIteration, signalling that this 'aclose()' await
2035 is done.
2036 */
2037 PyErr_Clear();
2038 PyErr_SetNone(PyExc_StopIteration);
2039 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002040 return retval;
2041 }
2042}
2043
2044
2045static PyObject *
2046async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2047{
2048 return async_gen_athrow_send(o, Py_None);
2049}
2050
2051
2052static PyObject *
2053async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2054{
2055 o->agt_state = AWAITABLE_STATE_CLOSED;
2056 Py_RETURN_NONE;
2057}
2058
2059
2060static PyMethodDef async_gen_athrow_methods[] = {
2061 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2062 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2063 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2064 {NULL, NULL} /* Sentinel */
2065};
2066
2067
2068static PyAsyncMethods async_gen_athrow_as_async = {
2069 PyObject_SelfIter, /* am_await */
2070 0, /* am_aiter */
2071 0 /* am_anext */
2072};
2073
2074
2075PyTypeObject _PyAsyncGenAThrow_Type = {
2076 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2077 "async_generator_athrow", /* tp_name */
2078 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2079 0, /* tp_itemsize */
2080 /* methods */
2081 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002082 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002083 0, /* tp_getattr */
2084 0, /* tp_setattr */
2085 &async_gen_athrow_as_async, /* tp_as_async */
2086 0, /* tp_repr */
2087 0, /* tp_as_number */
2088 0, /* tp_as_sequence */
2089 0, /* tp_as_mapping */
2090 0, /* tp_hash */
2091 0, /* tp_call */
2092 0, /* tp_str */
2093 PyObject_GenericGetAttr, /* tp_getattro */
2094 0, /* tp_setattro */
2095 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002096 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002097 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002098 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002099 0, /* tp_clear */
2100 0, /* tp_richcompare */
2101 0, /* tp_weaklistoffset */
2102 PyObject_SelfIter, /* tp_iter */
2103 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2104 async_gen_athrow_methods, /* tp_methods */
2105 0, /* tp_members */
2106 0, /* tp_getset */
2107 0, /* tp_base */
2108 0, /* tp_dict */
2109 0, /* tp_descr_get */
2110 0, /* tp_descr_set */
2111 0, /* tp_dictoffset */
2112 0, /* tp_init */
2113 0, /* tp_alloc */
2114 0, /* tp_new */
2115};
2116
2117
2118static PyObject *
2119async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2120{
2121 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002122 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002123 if (o == NULL) {
2124 return NULL;
2125 }
2126 o->agt_gen = gen;
2127 o->agt_args = args;
2128 o->agt_state = AWAITABLE_STATE_INIT;
2129 Py_INCREF(gen);
2130 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002131 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002132 return (PyObject*)o;
2133}