blob: 809838a4cd2f3b50863aabc4d34f07507b55cef8 [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
139static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500140gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000141{
Victor Stinner50b48572018-11-01 01:51:40 +0100142 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200144 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000145
Mark Shannoncb9879b2020-07-17 11:44:23 +0100146 if (f != NULL && _PyFrame_IsExecuting(f)) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200147 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700148 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400149 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700150 }
151 else if (PyAsyncGen_CheckExact(gen)) {
152 msg = "async generator already executing";
153 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400154 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500155 return NULL;
156 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100157 if (f == NULL || _PyFrameHasCompleted(f)) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500158 if (PyCoro_CheckExact(gen) && !closing) {
159 /* `gen` is an exhausted coroutine: raise an error,
160 except when called from gen_close(), which should
161 always be a silent method. */
162 PyErr_SetString(
163 PyExc_RuntimeError,
164 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700165 }
166 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500167 /* `gen` is an exhausted generator:
168 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700169 if (PyAsyncGen_CheckExact(gen)) {
170 PyErr_SetNone(PyExc_StopAsyncIteration);
171 }
172 else {
173 PyErr_SetNone(PyExc_StopIteration);
174 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return NULL;
177 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000178
Mark Shannoncb9879b2020-07-17 11:44:23 +0100179 assert(_PyFrame_IsRunnable(f));
Antoine Pitrou93963562013-05-14 20:37:52 +0200180 if (f->f_lasti == -1) {
181 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200182 const char *msg = "can't send non-None value to a "
183 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700184 if (PyCoro_CheckExact(gen)) {
185 msg = NON_INIT_CORO_MSG;
186 }
187 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400188 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700189 "just-started async generator";
190 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400191 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200192 return NULL;
193 }
194 } else {
195 /* Push arg onto the frame's value stack */
196 result = arg ? arg : Py_None;
197 Py_INCREF(result);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100198 gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth] = result;
199 gen->gi_frame->f_stackdepth++;
Antoine Pitrou93963562013-05-14 20:37:52 +0200200 }
201
202 /* Generators always return to their most recent caller, not
203 * necessarily their creator. */
204 Py_XINCREF(tstate->frame);
205 assert(f->f_back == NULL);
206 f->f_back = tstate->frame;
207
Mark Shannonae3087c2017-10-22 22:41:51 +0100208 gen->gi_exc_state.previous_item = tstate->exc_info;
209 tstate->exc_info = &gen->gi_exc_state;
Chris Jerdonek7c30d122020-05-22 13:33:27 -0700210
211 if (exc) {
212 assert(_PyErr_Occurred(tstate));
213 _PyErr_ChainStackItem(NULL);
214 }
215
Victor Stinnerb9e68122019-11-14 12:20:46 +0100216 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100217 tstate->exc_info = gen->gi_exc_state.previous_item;
218 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200219
220 /* Don't keep the reference to f_back any longer than necessary. It
221 * may keep a chain of frames alive or it could create a reference
222 * cycle. */
223 assert(f->f_back == tstate->frame);
224 Py_CLEAR(f->f_back);
225
226 /* If the generator just returned (as opposed to yielding), signal
227 * that the generator is exhausted. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100228 if (result && _PyFrameHasCompleted(f)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200229 if (result == Py_None) {
230 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700231 if (PyAsyncGen_CheckExact(gen)) {
232 PyErr_SetNone(PyExc_StopAsyncIteration);
233 }
Mark Shannon50a48da2020-06-04 13:23:35 +0100234 else if (arg) {
235 /* Set exception if not called by gen_iternext() */
Yury Selivanoveb636452016-09-08 22:01:51 -0700236 PyErr_SetNone(PyExc_StopIteration);
237 }
238 }
239 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700240 /* Async generators cannot return anything but None */
241 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200242 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200243 }
244 Py_CLEAR(result);
245 }
Yury Selivanov68333392015-05-22 11:16:47 -0400246 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500247 const char *msg = "generator raised StopIteration";
248 if (PyCoro_CheckExact(gen)) {
249 msg = "coroutine raised StopIteration";
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400250 }
Dong-hee Nad905df72020-02-14 02:37:17 +0900251 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500252 msg = "async generator raised StopIteration";
Yury Selivanov68333392015-05-22 11:16:47 -0400253 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500254 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
255
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400256 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500257 else if (!result && PyAsyncGen_CheckExact(gen) &&
Yury Selivanoveb636452016-09-08 22:01:51 -0700258 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
259 {
260 /* code in `gen` raised a StopAsyncIteration error:
261 raise a RuntimeError.
262 */
263 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300264 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700265 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200266
Mark Shannoncb9879b2020-07-17 11:44:23 +0100267 if (!result || _PyFrameHasCompleted(f)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200268 /* generator can't be rerun, so release the frame */
269 /* first clean reference cycle through stored exception traceback */
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700270 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200271 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200272 gen->gi_frame = NULL;
273 Py_DECREF(f);
274 }
275
276 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000277}
278
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000279PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000280"send(arg) -> send 'arg' into generator,\n\
281return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000282
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500283PyObject *
284_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000285{
Yury Selivanov77c96812016-02-13 17:59:05 -0500286 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000287}
288
289PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400290"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000291
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000292/*
293 * This helper function is used by gen_close and gen_throw to
294 * close a subiterator being delegated to by yield-from.
295 */
296
Antoine Pitrou93963562013-05-14 20:37:52 +0200297static int
298gen_close_iter(PyObject *yf)
299{
300 PyObject *retval = NULL;
301 _Py_IDENTIFIER(close);
302
Yury Selivanoveb636452016-09-08 22:01:51 -0700303 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200304 retval = gen_close((PyGenObject *)yf, NULL);
305 if (retval == NULL)
306 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700307 }
308 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200309 PyObject *meth;
310 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
311 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700312 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200313 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700314 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200315 Py_DECREF(meth);
316 if (retval == NULL)
317 return -1;
318 }
319 }
320 Py_XDECREF(retval);
321 return 0;
322}
323
Yury Selivanovc724bae2016-03-02 11:30:46 -0500324PyObject *
325_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500326{
Antoine Pitrou93963562013-05-14 20:37:52 +0200327 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500328 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200329
Mark Shannoncb9879b2020-07-17 11:44:23 +0100330 if (f) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200331 PyObject *bytecode = f->f_code->co_code;
332 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
333
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100334 if (f->f_lasti < 0) {
335 /* Return immediately if the frame didn't start yet. YIELD_FROM
336 always come after LOAD_CONST: a code object should not start
337 with YIELD_FROM */
338 assert(code[0] != YIELD_FROM);
339 return NULL;
340 }
341
Serhiy Storchakaab874002016-09-11 13:48:15 +0300342 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200343 return NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100344 assert(f->f_stackdepth > 0);
345 yf = f->f_valuestack[f->f_stackdepth-1];
Antoine Pitrou93963562013-05-14 20:37:52 +0200346 Py_INCREF(yf);
347 }
348
349 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500350}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000351
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000352static PyObject *
353gen_close(PyGenObject *gen, PyObject *args)
354{
Antoine Pitrou93963562013-05-14 20:37:52 +0200355 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500356 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200357 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000358
Antoine Pitrou93963562013-05-14 20:37:52 +0200359 if (yf) {
Mark Shannoncb9879b2020-07-17 11:44:23 +0100360 PyFrameState state = gen->gi_frame->f_state;
361 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200362 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100363 gen->gi_frame->f_state = state;
Antoine Pitrou93963562013-05-14 20:37:52 +0200364 Py_DECREF(yf);
365 }
366 if (err == 0)
367 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500368 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200369 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200370 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700371 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400372 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700373 } else if (PyAsyncGen_CheckExact(gen)) {
374 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
375 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200376 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400377 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 return NULL;
379 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200380 if (PyErr_ExceptionMatches(PyExc_StopIteration)
381 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
382 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200383 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200384 }
385 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000386}
387
Antoine Pitrou93963562013-05-14 20:37:52 +0200388
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000389PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000390"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
391return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000392
393static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700394_gen_throw(PyGenObject *gen, int close_on_genexit,
395 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000396{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500397 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000398 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000399
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000400 if (yf) {
401 PyObject *ret;
402 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700403 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
404 close_on_genexit
405 ) {
406 /* Asynchronous generators *should not* be closed right away.
407 We have to allow some awaits to work it through, hence the
408 `close_on_genexit` parameter here.
409 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100410 PyFrameState state = gen->gi_frame->f_state;
411 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200412 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100413 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000414 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000415 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500416 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000417 goto throw_here;
418 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700419 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
420 /* `yf` is a generator or a coroutine. */
Chris Jerdonek8b339612020-07-09 06:27:23 -0700421 PyThreadState *tstate = _PyThreadState_GET();
422 PyFrameObject *f = tstate->frame;
423
Chris Jerdonek8b339612020-07-09 06:27:23 -0700424 /* Since we are fast-tracking things by skipping the eval loop,
425 we need to update the current frame so the stack trace
426 will be reported correctly to the user. */
427 /* XXX We should probably be updating the current frame
428 somewhere in ceval.c. */
429 tstate->frame = gen->gi_frame;
Yury Selivanoveb636452016-09-08 22:01:51 -0700430 /* Close the generator that we are currently iterating with
431 'yield from' or awaiting on with 'await'. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100432 PyFrameState state = gen->gi_frame->f_state;
433 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700434 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
435 typ, val, tb);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100436 gen->gi_frame->f_state = state;
Chris Jerdonek8b339612020-07-09 06:27:23 -0700437 tstate->frame = f;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700439 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200440 PyObject *meth;
441 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
442 Py_DECREF(yf);
443 return NULL;
444 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000445 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000446 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000447 goto throw_here;
448 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100449 PyFrameState state = gen->gi_frame->f_state;
450 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700451 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100452 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000453 Py_DECREF(meth);
454 }
455 Py_DECREF(yf);
456 if (!ret) {
457 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500458 /* Pop subiterator from stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100459 assert(gen->gi_frame->f_stackdepth > 0);
460 gen->gi_frame->f_stackdepth--;
461 ret = gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth];
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500462 assert(ret == yf);
463 Py_DECREF(ret);
464 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100465 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300466 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000467 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500468 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000469 Py_DECREF(val);
470 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500471 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000472 }
473 }
474 return ret;
475 }
476
477throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* First, check the traceback argument, replacing None with
479 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400480 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400482 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 else if (tb != NULL && !PyTraceBack_Check(tb)) {
484 PyErr_SetString(PyExc_TypeError,
485 "throw() third argument must be a traceback object");
486 return NULL;
487 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_INCREF(typ);
490 Py_XINCREF(val);
491 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000492
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400493 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 else if (PyExceptionInstance_Check(typ)) {
497 /* Raising an instance. The value should be a dummy. */
498 if (val && val != Py_None) {
499 PyErr_SetString(PyExc_TypeError,
500 "instance exception may not have a separate value");
501 goto failed_throw;
502 }
503 else {
504 /* Normalize to raise <class>, <instance> */
505 Py_XDECREF(val);
506 val = typ;
507 typ = PyExceptionInstance_Class(typ);
508 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200509
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400510 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200511 /* Returns NULL if there's no traceback */
512 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 }
514 }
515 else {
516 /* Not something you can raise. throw() fails. */
517 PyErr_Format(PyExc_TypeError,
518 "exceptions must be classes or instances "
519 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000520 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 goto failed_throw;
522 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500525 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000526
527failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* Didn't use our arguments, so restore their original refcounts */
529 Py_DECREF(typ);
530 Py_XDECREF(val);
531 Py_XDECREF(tb);
532 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000533}
534
535
536static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700537gen_throw(PyGenObject *gen, PyObject *args)
538{
539 PyObject *typ;
540 PyObject *tb = NULL;
541 PyObject *val = NULL;
542
543 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
544 return NULL;
545 }
546
547 return _gen_throw(gen, 1, typ, val, tb);
548}
549
550
551static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000552gen_iternext(PyGenObject *gen)
553{
Yury Selivanov77c96812016-02-13 17:59:05 -0500554 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000555}
556
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000557/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200558 * Set StopIteration with specified value. Value can be arbitrary object
559 * or NULL.
560 *
561 * Returns 0 if StopIteration is set and -1 if any other exception is set.
562 */
563int
564_PyGen_SetStopIterationValue(PyObject *value)
565{
566 PyObject *e;
567
568 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400569 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200570 {
571 /* Delay exception instantiation if we can */
572 PyErr_SetObject(PyExc_StopIteration, value);
573 return 0;
574 }
575 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100576 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200577 *
578 * We do this to handle a situation when "value" is a tuple, in which
579 * case PyErr_SetObject would set the value of StopIteration to
580 * the first element of the tuple.
581 *
582 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
583 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100584 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200585 if (e == NULL) {
586 return -1;
587 }
588 PyErr_SetObject(PyExc_StopIteration, e);
589 Py_DECREF(e);
590 return 0;
591}
592
593/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000594 * If StopIteration exception is set, fetches its 'value'
595 * attribute if any, otherwise sets pvalue to None.
596 *
597 * Returns 0 if no exception or StopIteration is set.
598 * If any other exception is set, returns -1 and leaves
599 * pvalue unchanged.
600 */
601
602int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200603_PyGen_FetchStopIterationValue(PyObject **pvalue)
604{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000605 PyObject *et, *ev, *tb;
606 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500607
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000608 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
609 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200610 if (ev) {
611 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300612 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200613 value = ((PyStopIterationObject *)ev)->value;
614 Py_INCREF(value);
615 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200616 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
617 /* Avoid normalisation and take ev as value.
618 *
619 * Normalization is required if the value is a tuple, in
620 * that case the value of StopIteration would be set to
621 * the first element of the tuple.
622 *
623 * (See _PyErr_CreateException code for details.)
624 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200625 value = ev;
626 } else {
627 /* normalisation required */
628 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300629 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200630 PyErr_Restore(et, ev, tb);
631 return -1;
632 }
633 value = ((PyStopIterationObject *)ev)->value;
634 Py_INCREF(value);
635 Py_DECREF(ev);
636 }
637 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000638 Py_XDECREF(et);
639 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000640 } else if (PyErr_Occurred()) {
641 return -1;
642 }
643 if (value == NULL) {
644 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100645 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000646 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000647 *pvalue = value;
648 return 0;
649}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000650
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000651static PyObject *
652gen_repr(PyGenObject *gen)
653{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400654 return PyUnicode_FromFormat("<generator object %S at %p>",
655 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000656}
657
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000658static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200659gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000660{
Victor Stinner40ee3012014-06-16 15:59:28 +0200661 Py_INCREF(op->gi_name);
662 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000663}
664
Victor Stinner40ee3012014-06-16 15:59:28 +0200665static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200666gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200667{
Victor Stinner40ee3012014-06-16 15:59:28 +0200668 /* Not legal to del gen.gi_name or to set it to anything
669 * other than a string object. */
670 if (value == NULL || !PyUnicode_Check(value)) {
671 PyErr_SetString(PyExc_TypeError,
672 "__name__ must be set to a string object");
673 return -1;
674 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200675 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300676 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200677 return 0;
678}
679
680static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200681gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200682{
683 Py_INCREF(op->gi_qualname);
684 return op->gi_qualname;
685}
686
687static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200688gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200689{
Victor Stinner40ee3012014-06-16 15:59:28 +0200690 /* Not legal to del gen.__qualname__ or to set it to anything
691 * other than a string object. */
692 if (value == NULL || !PyUnicode_Check(value)) {
693 PyErr_SetString(PyExc_TypeError,
694 "__qualname__ must be set to a string object");
695 return -1;
696 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200697 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300698 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200699 return 0;
700}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000701
Yury Selivanove13f8f32015-07-03 00:23:30 -0400702static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200703gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400704{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500705 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400706 if (yf == NULL)
707 Py_RETURN_NONE;
708 return yf;
709}
710
Mark Shannoncb9879b2020-07-17 11:44:23 +0100711
712static PyObject *
713gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
714{
715 if (gen->gi_frame == NULL) {
716 Py_RETURN_FALSE;
717 }
718 return PyBool_FromLong(_PyFrame_IsExecuting(gen->gi_frame));
719}
720
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000721static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200722 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
723 PyDoc_STR("name of the generator")},
724 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
725 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400726 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
727 PyDoc_STR("object being iterated by yield from, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100728 {"gi_running", (getter)gen_getrunning, NULL, NULL},
Victor Stinner40ee3012014-06-16 15:59:28 +0200729 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000730};
731
Martin v. Löwise440e472004-06-01 15:22:42 +0000732static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200733 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Victor Stinner40ee3012014-06-16 15:59:28 +0200734 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000736};
737
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000738static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500739 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
741 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
742 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000743};
744
Martin v. Löwise440e472004-06-01 15:22:42 +0000745PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyVarObject_HEAD_INIT(&PyType_Type, 0)
747 "generator", /* tp_name */
748 sizeof(PyGenObject), /* tp_basicsize */
749 0, /* tp_itemsize */
750 /* methods */
751 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200752 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 0, /* tp_getattr */
754 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400755 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 (reprfunc)gen_repr, /* tp_repr */
757 0, /* tp_as_number */
758 0, /* tp_as_sequence */
759 0, /* tp_as_mapping */
760 0, /* tp_hash */
761 0, /* tp_call */
762 0, /* tp_str */
763 PyObject_GenericGetAttr, /* tp_getattro */
764 0, /* tp_setattro */
765 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200766 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 0, /* tp_doc */
768 (traverseproc)gen_traverse, /* tp_traverse */
769 0, /* tp_clear */
770 0, /* tp_richcompare */
771 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400772 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 (iternextfunc)gen_iternext, /* tp_iternext */
774 gen_methods, /* tp_methods */
775 gen_memberlist, /* tp_members */
776 gen_getsetlist, /* tp_getset */
777 0, /* tp_base */
778 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 0, /* tp_descr_get */
781 0, /* tp_descr_set */
782 0, /* tp_dictoffset */
783 0, /* tp_init */
784 0, /* tp_alloc */
785 0, /* tp_new */
786 0, /* tp_free */
787 0, /* tp_is_gc */
788 0, /* tp_bases */
789 0, /* tp_mro */
790 0, /* tp_cache */
791 0, /* tp_subclasses */
792 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200793 0, /* tp_del */
794 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200795 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000796};
797
Yury Selivanov5376ba92015-06-22 12:19:30 -0400798static PyObject *
799gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
800 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000801{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400802 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (gen == NULL) {
804 Py_DECREF(f);
805 return NULL;
806 }
807 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200808 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 Py_INCREF(f->f_code);
810 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100812 gen->gi_exc_state.exc_type = NULL;
813 gen->gi_exc_state.exc_value = NULL;
814 gen->gi_exc_state.exc_traceback = NULL;
815 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200816 if (name != NULL)
817 gen->gi_name = name;
818 else
819 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
820 Py_INCREF(gen->gi_name);
821 if (qualname != NULL)
822 gen->gi_qualname = qualname;
823 else
824 gen->gi_qualname = gen->gi_name;
825 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 _PyObject_GC_TRACK(gen);
827 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000828}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000829
Victor Stinner40ee3012014-06-16 15:59:28 +0200830PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400831PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
832{
833 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
834}
835
836PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200837PyGen_New(PyFrameObject *f)
838{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400839 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200840}
841
Yury Selivanov5376ba92015-06-22 12:19:30 -0400842/* Coroutine Object */
843
844typedef struct {
845 PyObject_HEAD
846 PyCoroObject *cw_coroutine;
847} PyCoroWrapper;
848
849static int
850gen_is_coroutine(PyObject *o)
851{
852 if (PyGen_CheckExact(o)) {
853 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
854 if (code->co_flags & CO_ITERABLE_COROUTINE) {
855 return 1;
856 }
857 }
858 return 0;
859}
860
Yury Selivanov75445082015-05-11 22:57:16 -0400861/*
862 * This helper function returns an awaitable for `o`:
863 * - `o` if `o` is a coroutine-object;
864 * - `type(o)->tp_as_async->am_await(o)`
865 *
866 * Raises a TypeError if it's not possible to return
867 * an awaitable and returns NULL.
868 */
869PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400870_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400871{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400872 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400873 PyTypeObject *ot;
874
Yury Selivanov5376ba92015-06-22 12:19:30 -0400875 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
876 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400877 Py_INCREF(o);
878 return o;
879 }
880
881 ot = Py_TYPE(o);
882 if (ot->tp_as_async != NULL) {
883 getter = ot->tp_as_async->am_await;
884 }
885 if (getter != NULL) {
886 PyObject *res = (*getter)(o);
887 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400888 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
889 /* __await__ must return an *iterator*, not
890 a coroutine or another awaitable (see PEP 492) */
891 PyErr_SetString(PyExc_TypeError,
892 "__await__() returned a coroutine");
893 Py_CLEAR(res);
894 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400895 PyErr_Format(PyExc_TypeError,
896 "__await__() returned non-iterator "
897 "of type '%.100s'",
898 Py_TYPE(res)->tp_name);
899 Py_CLEAR(res);
900 }
Yury Selivanov75445082015-05-11 22:57:16 -0400901 }
902 return res;
903 }
904
905 PyErr_Format(PyExc_TypeError,
906 "object %.100s can't be used in 'await' expression",
907 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400908 return NULL;
909}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400910
911static PyObject *
912coro_repr(PyCoroObject *coro)
913{
914 return PyUnicode_FromFormat("<coroutine object %S at %p>",
915 coro->cr_qualname, coro);
916}
917
918static PyObject *
919coro_await(PyCoroObject *coro)
920{
921 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
922 if (cw == NULL) {
923 return NULL;
924 }
925 Py_INCREF(coro);
926 cw->cw_coroutine = coro;
927 _PyObject_GC_TRACK(cw);
928 return (PyObject *)cw;
929}
930
Yury Selivanove13f8f32015-07-03 00:23:30 -0400931static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200932coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400933{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500934 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400935 if (yf == NULL)
936 Py_RETURN_NONE;
937 return yf;
938}
939
Mark Shannoncb9879b2020-07-17 11:44:23 +0100940static PyObject *
941cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
942{
943 if (coro->cr_frame == NULL) {
944 Py_RETURN_FALSE;
945 }
946 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
947}
948
Yury Selivanov5376ba92015-06-22 12:19:30 -0400949static PyGetSetDef coro_getsetlist[] = {
950 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
951 PyDoc_STR("name of the coroutine")},
952 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
953 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400954 {"cr_await", (getter)coro_get_cr_await, NULL,
955 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100956 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400957 {NULL} /* Sentinel */
958};
959
960static PyMemberDef coro_memberlist[] = {
961 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400962 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800963 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400964 {NULL} /* Sentinel */
965};
966
967PyDoc_STRVAR(coro_send_doc,
968"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400969return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400970
971PyDoc_STRVAR(coro_throw_doc,
972"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400973return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400974
975PyDoc_STRVAR(coro_close_doc,
976"close() -> raise GeneratorExit inside coroutine.");
977
978static PyMethodDef coro_methods[] = {
979 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
980 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
981 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
982 {NULL, NULL} /* Sentinel */
983};
984
985static PyAsyncMethods coro_as_async = {
986 (unaryfunc)coro_await, /* am_await */
987 0, /* am_aiter */
988 0 /* am_anext */
989};
990
991PyTypeObject PyCoro_Type = {
992 PyVarObject_HEAD_INIT(&PyType_Type, 0)
993 "coroutine", /* tp_name */
994 sizeof(PyCoroObject), /* tp_basicsize */
995 0, /* tp_itemsize */
996 /* methods */
997 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200998 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400999 0, /* tp_getattr */
1000 0, /* tp_setattr */
1001 &coro_as_async, /* tp_as_async */
1002 (reprfunc)coro_repr, /* tp_repr */
1003 0, /* tp_as_number */
1004 0, /* tp_as_sequence */
1005 0, /* tp_as_mapping */
1006 0, /* tp_hash */
1007 0, /* tp_call */
1008 0, /* tp_str */
1009 PyObject_GenericGetAttr, /* tp_getattro */
1010 0, /* tp_setattro */
1011 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001012 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001013 0, /* tp_doc */
1014 (traverseproc)gen_traverse, /* tp_traverse */
1015 0, /* tp_clear */
1016 0, /* tp_richcompare */
1017 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1018 0, /* tp_iter */
1019 0, /* tp_iternext */
1020 coro_methods, /* tp_methods */
1021 coro_memberlist, /* tp_members */
1022 coro_getsetlist, /* tp_getset */
1023 0, /* tp_base */
1024 0, /* tp_dict */
1025 0, /* tp_descr_get */
1026 0, /* tp_descr_set */
1027 0, /* tp_dictoffset */
1028 0, /* tp_init */
1029 0, /* tp_alloc */
1030 0, /* tp_new */
1031 0, /* tp_free */
1032 0, /* tp_is_gc */
1033 0, /* tp_bases */
1034 0, /* tp_mro */
1035 0, /* tp_cache */
1036 0, /* tp_subclasses */
1037 0, /* tp_weaklist */
1038 0, /* tp_del */
1039 0, /* tp_version_tag */
1040 _PyGen_Finalize, /* tp_finalize */
1041};
1042
1043static void
1044coro_wrapper_dealloc(PyCoroWrapper *cw)
1045{
1046 _PyObject_GC_UNTRACK((PyObject *)cw);
1047 Py_CLEAR(cw->cw_coroutine);
1048 PyObject_GC_Del(cw);
1049}
1050
1051static PyObject *
1052coro_wrapper_iternext(PyCoroWrapper *cw)
1053{
Yury Selivanov77c96812016-02-13 17:59:05 -05001054 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001055}
1056
1057static PyObject *
1058coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1059{
Yury Selivanov77c96812016-02-13 17:59:05 -05001060 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001061}
1062
1063static PyObject *
1064coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1065{
1066 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1067}
1068
1069static PyObject *
1070coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1071{
1072 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1073}
1074
1075static int
1076coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1077{
1078 Py_VISIT((PyObject *)cw->cw_coroutine);
1079 return 0;
1080}
1081
1082static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001083 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1084 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1085 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001086 {NULL, NULL} /* Sentinel */
1087};
1088
1089PyTypeObject _PyCoroWrapper_Type = {
1090 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1091 "coroutine_wrapper",
1092 sizeof(PyCoroWrapper), /* tp_basicsize */
1093 0, /* tp_itemsize */
1094 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001095 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001096 0, /* tp_getattr */
1097 0, /* tp_setattr */
1098 0, /* tp_as_async */
1099 0, /* tp_repr */
1100 0, /* tp_as_number */
1101 0, /* tp_as_sequence */
1102 0, /* tp_as_mapping */
1103 0, /* tp_hash */
1104 0, /* tp_call */
1105 0, /* tp_str */
1106 PyObject_GenericGetAttr, /* tp_getattro */
1107 0, /* tp_setattro */
1108 0, /* tp_as_buffer */
1109 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1110 "A wrapper object implementing __await__ for coroutines.",
1111 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1112 0, /* tp_clear */
1113 0, /* tp_richcompare */
1114 0, /* tp_weaklistoffset */
1115 PyObject_SelfIter, /* tp_iter */
1116 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1117 coro_wrapper_methods, /* tp_methods */
1118 0, /* tp_members */
1119 0, /* tp_getset */
1120 0, /* tp_base */
1121 0, /* tp_dict */
1122 0, /* tp_descr_get */
1123 0, /* tp_descr_set */
1124 0, /* tp_dictoffset */
1125 0, /* tp_init */
1126 0, /* tp_alloc */
1127 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001128 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001129};
1130
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001131static PyObject *
1132compute_cr_origin(int origin_depth)
1133{
1134 PyFrameObject *frame = PyEval_GetFrame();
1135 /* First count how many frames we have */
1136 int frame_count = 0;
1137 for (; frame && frame_count < origin_depth; ++frame_count) {
1138 frame = frame->f_back;
1139 }
1140
1141 /* Now collect them */
1142 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001143 if (cr_origin == NULL) {
1144 return NULL;
1145 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001146 frame = PyEval_GetFrame();
1147 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001148 PyCodeObject *code = frame->f_code;
1149 PyObject *frameinfo = Py_BuildValue("OiO",
1150 code->co_filename,
1151 PyFrame_GetLineNumber(frame),
1152 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001153 if (!frameinfo) {
1154 Py_DECREF(cr_origin);
1155 return NULL;
1156 }
1157 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1158 frame = frame->f_back;
1159 }
1160
1161 return cr_origin;
1162}
1163
Yury Selivanov5376ba92015-06-22 12:19:30 -04001164PyObject *
1165PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1166{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001167 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1168 if (!coro) {
1169 return NULL;
1170 }
1171
Victor Stinner50b48572018-11-01 01:51:40 +01001172 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001173 int origin_depth = tstate->coroutine_origin_tracking_depth;
1174
1175 if (origin_depth == 0) {
1176 ((PyCoroObject *)coro)->cr_origin = NULL;
1177 } else {
1178 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001179 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001180 if (!cr_origin) {
1181 Py_DECREF(coro);
1182 return NULL;
1183 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001184 }
1185
1186 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001187}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001188
1189
Yury Selivanoveb636452016-09-08 22:01:51 -07001190/* ========= Asynchronous Generators ========= */
1191
1192
1193typedef enum {
1194 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1195 AWAITABLE_STATE_ITER, /* being iterated */
1196 AWAITABLE_STATE_CLOSED, /* closed */
1197} AwaitableState;
1198
1199
Victor Stinner78a02c22020-06-05 02:34:14 +02001200typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001201 PyObject_HEAD
1202 PyAsyncGenObject *ags_gen;
1203
1204 /* Can be NULL, when in the __anext__() mode
1205 (equivalent of "asend(None)") */
1206 PyObject *ags_sendval;
1207
1208 AwaitableState ags_state;
1209} PyAsyncGenASend;
1210
1211
Victor Stinner78a02c22020-06-05 02:34:14 +02001212typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001213 PyObject_HEAD
1214 PyAsyncGenObject *agt_gen;
1215
1216 /* Can be NULL, when in the "aclose()" mode
1217 (equivalent of "athrow(GeneratorExit)") */
1218 PyObject *agt_args;
1219
1220 AwaitableState agt_state;
1221} PyAsyncGenAThrow;
1222
1223
Victor Stinner78a02c22020-06-05 02:34:14 +02001224typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001225 PyObject_HEAD
1226 PyObject *agw_val;
1227} _PyAsyncGenWrappedValue;
1228
1229
Yury Selivanoveb636452016-09-08 22:01:51 -07001230#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001231 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001232
1233#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001234 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001235
1236
1237static int
1238async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1239{
1240 Py_VISIT(gen->ag_finalizer);
1241 return gen_traverse((PyGenObject*)gen, visit, arg);
1242}
1243
1244
1245static PyObject *
1246async_gen_repr(PyAsyncGenObject *o)
1247{
1248 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1249 o->ag_qualname, o);
1250}
1251
1252
1253static int
1254async_gen_init_hooks(PyAsyncGenObject *o)
1255{
1256 PyThreadState *tstate;
1257 PyObject *finalizer;
1258 PyObject *firstiter;
1259
1260 if (o->ag_hooks_inited) {
1261 return 0;
1262 }
1263
1264 o->ag_hooks_inited = 1;
1265
Victor Stinner50b48572018-11-01 01:51:40 +01001266 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001267
1268 finalizer = tstate->async_gen_finalizer;
1269 if (finalizer) {
1270 Py_INCREF(finalizer);
1271 o->ag_finalizer = finalizer;
1272 }
1273
1274 firstiter = tstate->async_gen_firstiter;
1275 if (firstiter) {
1276 PyObject *res;
1277
1278 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001279 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001280 Py_DECREF(firstiter);
1281 if (res == NULL) {
1282 return 1;
1283 }
1284 Py_DECREF(res);
1285 }
1286
1287 return 0;
1288}
1289
1290
1291static PyObject *
1292async_gen_anext(PyAsyncGenObject *o)
1293{
1294 if (async_gen_init_hooks(o)) {
1295 return NULL;
1296 }
1297 return async_gen_asend_new(o, NULL);
1298}
1299
1300
1301static PyObject *
1302async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1303{
1304 if (async_gen_init_hooks(o)) {
1305 return NULL;
1306 }
1307 return async_gen_asend_new(o, arg);
1308}
1309
1310
1311static PyObject *
1312async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1313{
1314 if (async_gen_init_hooks(o)) {
1315 return NULL;
1316 }
1317 return async_gen_athrow_new(o, NULL);
1318}
1319
1320static PyObject *
1321async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1322{
1323 if (async_gen_init_hooks(o)) {
1324 return NULL;
1325 }
1326 return async_gen_athrow_new(o, args);
1327}
1328
1329
1330static PyGetSetDef async_gen_getsetlist[] = {
1331 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1332 PyDoc_STR("name of the async generator")},
1333 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1334 PyDoc_STR("qualified name of the async generator")},
1335 {"ag_await", (getter)coro_get_cr_await, NULL,
1336 PyDoc_STR("object being awaited on, or None")},
1337 {NULL} /* Sentinel */
1338};
1339
1340static PyMemberDef async_gen_memberlist[] = {
1341 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001342 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1343 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001344 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1345 {NULL} /* Sentinel */
1346};
1347
1348PyDoc_STRVAR(async_aclose_doc,
1349"aclose() -> raise GeneratorExit inside generator.");
1350
1351PyDoc_STRVAR(async_asend_doc,
1352"asend(v) -> send 'v' in generator.");
1353
1354PyDoc_STRVAR(async_athrow_doc,
1355"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1356
1357static PyMethodDef async_gen_methods[] = {
1358 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1359 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1360 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001361 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1362 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001363 {NULL, NULL} /* Sentinel */
1364};
1365
1366
1367static PyAsyncMethods async_gen_as_async = {
1368 0, /* am_await */
1369 PyObject_SelfIter, /* am_aiter */
1370 (unaryfunc)async_gen_anext /* am_anext */
1371};
1372
1373
1374PyTypeObject PyAsyncGen_Type = {
1375 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1376 "async_generator", /* tp_name */
1377 sizeof(PyAsyncGenObject), /* tp_basicsize */
1378 0, /* tp_itemsize */
1379 /* methods */
1380 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001381 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001382 0, /* tp_getattr */
1383 0, /* tp_setattr */
1384 &async_gen_as_async, /* tp_as_async */
1385 (reprfunc)async_gen_repr, /* tp_repr */
1386 0, /* tp_as_number */
1387 0, /* tp_as_sequence */
1388 0, /* tp_as_mapping */
1389 0, /* tp_hash */
1390 0, /* tp_call */
1391 0, /* tp_str */
1392 PyObject_GenericGetAttr, /* tp_getattro */
1393 0, /* tp_setattro */
1394 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001395 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001396 0, /* tp_doc */
1397 (traverseproc)async_gen_traverse, /* tp_traverse */
1398 0, /* tp_clear */
1399 0, /* tp_richcompare */
1400 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1401 0, /* tp_iter */
1402 0, /* tp_iternext */
1403 async_gen_methods, /* tp_methods */
1404 async_gen_memberlist, /* tp_members */
1405 async_gen_getsetlist, /* tp_getset */
1406 0, /* tp_base */
1407 0, /* tp_dict */
1408 0, /* tp_descr_get */
1409 0, /* tp_descr_set */
1410 0, /* tp_dictoffset */
1411 0, /* tp_init */
1412 0, /* tp_alloc */
1413 0, /* tp_new */
1414 0, /* tp_free */
1415 0, /* tp_is_gc */
1416 0, /* tp_bases */
1417 0, /* tp_mro */
1418 0, /* tp_cache */
1419 0, /* tp_subclasses */
1420 0, /* tp_weaklist */
1421 0, /* tp_del */
1422 0, /* tp_version_tag */
1423 _PyGen_Finalize, /* tp_finalize */
1424};
1425
1426
Victor Stinner522691c2020-06-23 16:40:40 +02001427static struct _Py_async_gen_state *
1428get_async_gen_state(void)
1429{
1430 PyInterpreterState *interp = _PyInterpreterState_GET();
1431 return &interp->async_gen;
1432}
1433
1434
Yury Selivanoveb636452016-09-08 22:01:51 -07001435PyObject *
1436PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1437{
1438 PyAsyncGenObject *o;
1439 o = (PyAsyncGenObject *)gen_new_with_qualname(
1440 &PyAsyncGen_Type, f, name, qualname);
1441 if (o == NULL) {
1442 return NULL;
1443 }
1444 o->ag_finalizer = NULL;
1445 o->ag_closed = 0;
1446 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001447 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001448 return (PyObject*)o;
1449}
1450
1451
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001452void
Victor Stinner78a02c22020-06-05 02:34:14 +02001453_PyAsyncGen_ClearFreeLists(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001454{
Victor Stinner78a02c22020-06-05 02:34:14 +02001455 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1456
1457 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001458 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001459 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001460 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001461 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001462 }
1463
Victor Stinner78a02c22020-06-05 02:34:14 +02001464 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001465 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001466 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001467 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001468 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001469 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001470}
1471
1472void
Victor Stinner78a02c22020-06-05 02:34:14 +02001473_PyAsyncGen_Fini(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001474{
Victor Stinner78a02c22020-06-05 02:34:14 +02001475 _PyAsyncGen_ClearFreeLists(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001476#ifdef Py_DEBUG
1477 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1478 state->value_numfree = -1;
1479 state->asend_numfree = -1;
1480#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001481}
1482
1483
1484static PyObject *
1485async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1486{
1487 if (result == NULL) {
1488 if (!PyErr_Occurred()) {
1489 PyErr_SetNone(PyExc_StopAsyncIteration);
1490 }
1491
1492 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1493 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1494 ) {
1495 gen->ag_closed = 1;
1496 }
1497
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001498 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001499 return NULL;
1500 }
1501
1502 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1503 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001504 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001505 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001506 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001507 return NULL;
1508 }
1509
1510 return result;
1511}
1512
1513
1514/* ---------- Async Generator ASend Awaitable ------------ */
1515
1516
1517static void
1518async_gen_asend_dealloc(PyAsyncGenASend *o)
1519{
Yury Selivanov29310c42016-11-08 19:46:22 -05001520 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001521 Py_CLEAR(o->ags_gen);
1522 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001523 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001524#ifdef Py_DEBUG
1525 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1526 assert(state->asend_numfree != -1);
1527#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001528 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001529 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001530 state->asend_freelist[state->asend_numfree++] = o;
1531 }
1532 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001533 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001534 }
1535}
1536
Yury Selivanov29310c42016-11-08 19:46:22 -05001537static int
1538async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1539{
1540 Py_VISIT(o->ags_gen);
1541 Py_VISIT(o->ags_sendval);
1542 return 0;
1543}
1544
Yury Selivanoveb636452016-09-08 22:01:51 -07001545
1546static PyObject *
1547async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1548{
1549 PyObject *result;
1550
1551 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001552 PyErr_SetString(
1553 PyExc_RuntimeError,
1554 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001555 return NULL;
1556 }
1557
1558 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001559 if (o->ags_gen->ag_running_async) {
1560 PyErr_SetString(
1561 PyExc_RuntimeError,
1562 "anext(): asynchronous generator is already running");
1563 return NULL;
1564 }
1565
Yury Selivanoveb636452016-09-08 22:01:51 -07001566 if (arg == NULL || arg == Py_None) {
1567 arg = o->ags_sendval;
1568 }
1569 o->ags_state = AWAITABLE_STATE_ITER;
1570 }
1571
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001572 o->ags_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001573 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1574 result = async_gen_unwrap_value(o->ags_gen, result);
1575
1576 if (result == NULL) {
1577 o->ags_state = AWAITABLE_STATE_CLOSED;
1578 }
1579
1580 return result;
1581}
1582
1583
1584static PyObject *
1585async_gen_asend_iternext(PyAsyncGenASend *o)
1586{
1587 return async_gen_asend_send(o, NULL);
1588}
1589
1590
1591static PyObject *
1592async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1593{
1594 PyObject *result;
1595
1596 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001597 PyErr_SetString(
1598 PyExc_RuntimeError,
1599 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001600 return NULL;
1601 }
1602
1603 result = gen_throw((PyGenObject*)o->ags_gen, args);
1604 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_close(PyAsyncGenASend *o, PyObject *args)
1616{
1617 o->ags_state = AWAITABLE_STATE_CLOSED;
1618 Py_RETURN_NONE;
1619}
1620
1621
1622static PyMethodDef async_gen_asend_methods[] = {
1623 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1624 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1625 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1626 {NULL, NULL} /* Sentinel */
1627};
1628
1629
1630static PyAsyncMethods async_gen_asend_as_async = {
1631 PyObject_SelfIter, /* am_await */
1632 0, /* am_aiter */
1633 0 /* am_anext */
1634};
1635
1636
1637PyTypeObject _PyAsyncGenASend_Type = {
1638 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1639 "async_generator_asend", /* tp_name */
1640 sizeof(PyAsyncGenASend), /* tp_basicsize */
1641 0, /* tp_itemsize */
1642 /* methods */
1643 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001644 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001645 0, /* tp_getattr */
1646 0, /* tp_setattr */
1647 &async_gen_asend_as_async, /* tp_as_async */
1648 0, /* tp_repr */
1649 0, /* tp_as_number */
1650 0, /* tp_as_sequence */
1651 0, /* tp_as_mapping */
1652 0, /* tp_hash */
1653 0, /* tp_call */
1654 0, /* tp_str */
1655 PyObject_GenericGetAttr, /* tp_getattro */
1656 0, /* tp_setattro */
1657 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001658 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001659 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001660 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001661 0, /* tp_clear */
1662 0, /* tp_richcompare */
1663 0, /* tp_weaklistoffset */
1664 PyObject_SelfIter, /* tp_iter */
1665 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1666 async_gen_asend_methods, /* tp_methods */
1667 0, /* tp_members */
1668 0, /* tp_getset */
1669 0, /* tp_base */
1670 0, /* tp_dict */
1671 0, /* tp_descr_get */
1672 0, /* tp_descr_set */
1673 0, /* tp_dictoffset */
1674 0, /* tp_init */
1675 0, /* tp_alloc */
1676 0, /* tp_new */
1677};
1678
1679
1680static PyObject *
1681async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1682{
1683 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001684 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001685#ifdef Py_DEBUG
1686 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1687 assert(state->asend_numfree != -1);
1688#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001689 if (state->asend_numfree) {
1690 state->asend_numfree--;
1691 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001692 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001693 }
1694 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001695 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001696 if (o == NULL) {
1697 return NULL;
1698 }
1699 }
1700
1701 Py_INCREF(gen);
1702 o->ags_gen = gen;
1703
1704 Py_XINCREF(sendval);
1705 o->ags_sendval = sendval;
1706
1707 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001708
1709 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001710 return (PyObject*)o;
1711}
1712
1713
1714/* ---------- Async Generator Value Wrapper ------------ */
1715
1716
1717static void
1718async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1719{
Yury Selivanov29310c42016-11-08 19:46:22 -05001720 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001721 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001722 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001723#ifdef Py_DEBUG
1724 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1725 assert(state->value_numfree != -1);
1726#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001727 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001728 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001729 state->value_freelist[state->value_numfree++] = o;
1730 }
1731 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001732 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001733 }
1734}
1735
1736
Yury Selivanov29310c42016-11-08 19:46:22 -05001737static int
1738async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1739 visitproc visit, void *arg)
1740{
1741 Py_VISIT(o->agw_val);
1742 return 0;
1743}
1744
1745
Yury Selivanoveb636452016-09-08 22:01:51 -07001746PyTypeObject _PyAsyncGenWrappedValue_Type = {
1747 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1748 "async_generator_wrapped_value", /* tp_name */
1749 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1750 0, /* tp_itemsize */
1751 /* methods */
1752 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001753 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001754 0, /* tp_getattr */
1755 0, /* tp_setattr */
1756 0, /* tp_as_async */
1757 0, /* tp_repr */
1758 0, /* tp_as_number */
1759 0, /* tp_as_sequence */
1760 0, /* tp_as_mapping */
1761 0, /* tp_hash */
1762 0, /* tp_call */
1763 0, /* tp_str */
1764 PyObject_GenericGetAttr, /* tp_getattro */
1765 0, /* tp_setattro */
1766 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001767 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001768 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001769 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001770 0, /* tp_clear */
1771 0, /* tp_richcompare */
1772 0, /* tp_weaklistoffset */
1773 0, /* tp_iter */
1774 0, /* tp_iternext */
1775 0, /* tp_methods */
1776 0, /* tp_members */
1777 0, /* tp_getset */
1778 0, /* tp_base */
1779 0, /* tp_dict */
1780 0, /* tp_descr_get */
1781 0, /* tp_descr_set */
1782 0, /* tp_dictoffset */
1783 0, /* tp_init */
1784 0, /* tp_alloc */
1785 0, /* tp_new */
1786};
1787
1788
1789PyObject *
1790_PyAsyncGenValueWrapperNew(PyObject *val)
1791{
1792 _PyAsyncGenWrappedValue *o;
1793 assert(val);
1794
Victor Stinner522691c2020-06-23 16:40:40 +02001795 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001796#ifdef Py_DEBUG
1797 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1798 assert(state->value_numfree != -1);
1799#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001800 if (state->value_numfree) {
1801 state->value_numfree--;
1802 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001803 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1804 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001805 }
1806 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001807 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1808 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001809 if (o == NULL) {
1810 return NULL;
1811 }
1812 }
1813 o->agw_val = val;
1814 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001815 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001816 return (PyObject*)o;
1817}
1818
1819
1820/* ---------- Async Generator AThrow awaitable ------------ */
1821
1822
1823static void
1824async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1825{
Yury Selivanov29310c42016-11-08 19:46:22 -05001826 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001827 Py_CLEAR(o->agt_gen);
1828 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001829 PyObject_GC_Del(o);
1830}
1831
1832
1833static int
1834async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1835{
1836 Py_VISIT(o->agt_gen);
1837 Py_VISIT(o->agt_args);
1838 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001839}
1840
1841
1842static PyObject *
1843async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1844{
1845 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1846 PyFrameObject *f = gen->gi_frame;
1847 PyObject *retval;
1848
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001849 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001850 PyErr_SetString(
1851 PyExc_RuntimeError,
1852 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001853 return NULL;
1854 }
1855
Mark Shannoncb9879b2020-07-17 11:44:23 +01001856 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001857 o->agt_state = AWAITABLE_STATE_CLOSED;
1858 PyErr_SetNone(PyExc_StopIteration);
1859 return NULL;
1860 }
1861
Yury Selivanoveb636452016-09-08 22:01:51 -07001862 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001863 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001864 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001865 if (o->agt_args == NULL) {
1866 PyErr_SetString(
1867 PyExc_RuntimeError,
1868 "aclose(): asynchronous generator is already running");
1869 }
1870 else {
1871 PyErr_SetString(
1872 PyExc_RuntimeError,
1873 "athrow(): asynchronous generator is already running");
1874 }
1875 return NULL;
1876 }
1877
Yury Selivanoveb636452016-09-08 22:01:51 -07001878 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001879 o->agt_state = AWAITABLE_STATE_CLOSED;
1880 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001881 return NULL;
1882 }
1883
1884 if (arg != Py_None) {
1885 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1886 return NULL;
1887 }
1888
1889 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001890 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001891
1892 if (o->agt_args == NULL) {
1893 /* aclose() mode */
1894 o->agt_gen->ag_closed = 1;
1895
1896 retval = _gen_throw((PyGenObject *)gen,
1897 0, /* Do not close generator when
1898 PyExc_GeneratorExit is passed */
1899 PyExc_GeneratorExit, NULL, NULL);
1900
1901 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1902 Py_DECREF(retval);
1903 goto yield_close;
1904 }
1905 } else {
1906 PyObject *typ;
1907 PyObject *tb = NULL;
1908 PyObject *val = NULL;
1909
1910 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1911 &typ, &val, &tb)) {
1912 return NULL;
1913 }
1914
1915 retval = _gen_throw((PyGenObject *)gen,
1916 0, /* Do not close generator when
1917 PyExc_GeneratorExit is passed */
1918 typ, val, tb);
1919 retval = async_gen_unwrap_value(o->agt_gen, retval);
1920 }
1921 if (retval == NULL) {
1922 goto check_error;
1923 }
1924 return retval;
1925 }
1926
1927 assert(o->agt_state == AWAITABLE_STATE_ITER);
1928
1929 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1930 if (o->agt_args) {
1931 return async_gen_unwrap_value(o->agt_gen, retval);
1932 } else {
1933 /* aclose() mode */
1934 if (retval) {
1935 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1936 Py_DECREF(retval);
1937 goto yield_close;
1938 }
1939 else {
1940 return retval;
1941 }
1942 }
1943 else {
1944 goto check_error;
1945 }
1946 }
1947
1948yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001949 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001950 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001951 PyErr_SetString(
1952 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1953 return NULL;
1954
1955check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001956 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001957 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001958 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1959 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1960 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001961 if (o->agt_args == NULL) {
1962 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001963 StopAsyncIteration or GeneratorExit; just raise
1964 StopIteration, signalling that this 'aclose()' await
1965 is done.
1966 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001967 PyErr_Clear();
1968 PyErr_SetNone(PyExc_StopIteration);
1969 }
1970 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001971 return NULL;
1972}
1973
1974
1975static PyObject *
1976async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1977{
1978 PyObject *retval;
1979
Yury Selivanoveb636452016-09-08 22:01:51 -07001980 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001981 PyErr_SetString(
1982 PyExc_RuntimeError,
1983 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001984 return NULL;
1985 }
1986
1987 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1988 if (o->agt_args) {
1989 return async_gen_unwrap_value(o->agt_gen, retval);
1990 } else {
1991 /* aclose() mode */
1992 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001993 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001994 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001995 Py_DECREF(retval);
1996 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1997 return NULL;
1998 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08001999 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2000 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2001 {
2002 /* when aclose() is called we don't want to propagate
2003 StopAsyncIteration or GeneratorExit; just raise
2004 StopIteration, signalling that this 'aclose()' await
2005 is done.
2006 */
2007 PyErr_Clear();
2008 PyErr_SetNone(PyExc_StopIteration);
2009 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002010 return retval;
2011 }
2012}
2013
2014
2015static PyObject *
2016async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2017{
2018 return async_gen_athrow_send(o, Py_None);
2019}
2020
2021
2022static PyObject *
2023async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2024{
2025 o->agt_state = AWAITABLE_STATE_CLOSED;
2026 Py_RETURN_NONE;
2027}
2028
2029
2030static PyMethodDef async_gen_athrow_methods[] = {
2031 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2032 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2033 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2034 {NULL, NULL} /* Sentinel */
2035};
2036
2037
2038static PyAsyncMethods async_gen_athrow_as_async = {
2039 PyObject_SelfIter, /* am_await */
2040 0, /* am_aiter */
2041 0 /* am_anext */
2042};
2043
2044
2045PyTypeObject _PyAsyncGenAThrow_Type = {
2046 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2047 "async_generator_athrow", /* tp_name */
2048 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2049 0, /* tp_itemsize */
2050 /* methods */
2051 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002052 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002053 0, /* tp_getattr */
2054 0, /* tp_setattr */
2055 &async_gen_athrow_as_async, /* tp_as_async */
2056 0, /* tp_repr */
2057 0, /* tp_as_number */
2058 0, /* tp_as_sequence */
2059 0, /* tp_as_mapping */
2060 0, /* tp_hash */
2061 0, /* tp_call */
2062 0, /* tp_str */
2063 PyObject_GenericGetAttr, /* tp_getattro */
2064 0, /* tp_setattro */
2065 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002066 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002067 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002068 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002069 0, /* tp_clear */
2070 0, /* tp_richcompare */
2071 0, /* tp_weaklistoffset */
2072 PyObject_SelfIter, /* tp_iter */
2073 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2074 async_gen_athrow_methods, /* tp_methods */
2075 0, /* tp_members */
2076 0, /* tp_getset */
2077 0, /* tp_base */
2078 0, /* tp_dict */
2079 0, /* tp_descr_get */
2080 0, /* tp_descr_set */
2081 0, /* tp_dictoffset */
2082 0, /* tp_init */
2083 0, /* tp_alloc */
2084 0, /* tp_new */
2085};
2086
2087
2088static PyObject *
2089async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2090{
2091 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002092 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002093 if (o == NULL) {
2094 return NULL;
2095 }
2096 o->agt_gen = gen;
2097 o->agt_args = args;
2098 o->agt_state = AWAITABLE_STATE_INIT;
2099 Py_INCREF(gen);
2100 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002101 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002102 return (PyObject*)o;
2103}