blob: f7dbfd74864193ca7caa9fef1cac98c2b02ced14 [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
Yury Selivanov2a2270d2018-01-29 14:31:47 -050050 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) {
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
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500146 if (gen->gi_running) {
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 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200157 if (f == NULL || f->f_stacktop == NULL) {
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
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);
Antoine Pitrou93963562013-05-14 20:37:52 +0200191 return NULL;
192 }
193 } else {
194 /* Push arg onto the frame's value stack */
195 result = arg ? arg : Py_None;
196 Py_INCREF(result);
197 *(f->f_stacktop++) = result;
198 }
199
200 /* Generators always return to their most recent caller, not
201 * necessarily their creator. */
202 Py_XINCREF(tstate->frame);
203 assert(f->f_back == NULL);
204 f->f_back = tstate->frame;
205
206 gen->gi_running = 1;
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 gen->gi_running = 0;
219
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. */
228 if (result && f->f_stacktop == NULL) {
229 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
267 if (!result || f->f_stacktop == NULL) {
268 /* 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
330 if (f && f->f_stacktop) {
331 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;
344 yf = f->f_stacktop[-1];
345 Py_INCREF(yf);
346 }
347
348 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500349}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000350
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000351static PyObject *
352gen_close(PyGenObject *gen, PyObject *args)
353{
Antoine Pitrou93963562013-05-14 20:37:52 +0200354 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500355 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200356 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000357
Antoine Pitrou93963562013-05-14 20:37:52 +0200358 if (yf) {
359 gen->gi_running = 1;
360 err = gen_close_iter(yf);
361 gen->gi_running = 0;
362 Py_DECREF(yf);
363 }
364 if (err == 0)
365 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500366 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200367 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200368 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700369 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400370 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700371 } else if (PyAsyncGen_CheckExact(gen)) {
372 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
373 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200374 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400375 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 return NULL;
377 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200378 if (PyErr_ExceptionMatches(PyExc_StopIteration)
379 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
380 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200381 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200382 }
383 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000384}
385
Antoine Pitrou93963562013-05-14 20:37:52 +0200386
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000387PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000388"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
389return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000390
391static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700392_gen_throw(PyGenObject *gen, int close_on_genexit,
393 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000394{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500395 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000396 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000397
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000398 if (yf) {
399 PyObject *ret;
400 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700401 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
402 close_on_genexit
403 ) {
404 /* Asynchronous generators *should not* be closed right away.
405 We have to allow some awaits to work it through, hence the
406 `close_on_genexit` parameter here.
407 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500408 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200409 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500410 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000411 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000412 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500413 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000414 goto throw_here;
415 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700416 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
417 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500418 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700419 /* Close the generator that we are currently iterating with
420 'yield from' or awaiting on with 'await'. */
421 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
422 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500423 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000424 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700425 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200426 PyObject *meth;
427 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
428 Py_DECREF(yf);
429 return NULL;
430 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000431 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000432 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000433 goto throw_here;
434 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500435 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700436 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500437 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 Py_DECREF(meth);
439 }
440 Py_DECREF(yf);
441 if (!ret) {
442 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500443 /* Pop subiterator from stack */
444 ret = *(--gen->gi_frame->f_stacktop);
445 assert(ret == yf);
446 Py_DECREF(ret);
447 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100448 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300449 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000450 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500451 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000452 Py_DECREF(val);
453 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500454 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000455 }
456 }
457 return ret;
458 }
459
460throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* First, check the traceback argument, replacing None with
462 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400463 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 else if (tb != NULL && !PyTraceBack_Check(tb)) {
467 PyErr_SetString(PyExc_TypeError,
468 "throw() third argument must be a traceback object");
469 return NULL;
470 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_INCREF(typ);
473 Py_XINCREF(val);
474 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000475
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400476 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 else if (PyExceptionInstance_Check(typ)) {
480 /* Raising an instance. The value should be a dummy. */
481 if (val && val != Py_None) {
482 PyErr_SetString(PyExc_TypeError,
483 "instance exception may not have a separate value");
484 goto failed_throw;
485 }
486 else {
487 /* Normalize to raise <class>, <instance> */
488 Py_XDECREF(val);
489 val = typ;
490 typ = PyExceptionInstance_Class(typ);
491 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200492
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400493 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200494 /* Returns NULL if there's no traceback */
495 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 }
497 }
498 else {
499 /* Not something you can raise. throw() fails. */
500 PyErr_Format(PyExc_TypeError,
501 "exceptions must be classes or instances "
502 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000503 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 goto failed_throw;
505 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500508 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000509
510failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 /* Didn't use our arguments, so restore their original refcounts */
512 Py_DECREF(typ);
513 Py_XDECREF(val);
514 Py_XDECREF(tb);
515 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000516}
517
518
519static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700520gen_throw(PyGenObject *gen, PyObject *args)
521{
522 PyObject *typ;
523 PyObject *tb = NULL;
524 PyObject *val = NULL;
525
526 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
527 return NULL;
528 }
529
530 return _gen_throw(gen, 1, typ, val, tb);
531}
532
533
534static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000535gen_iternext(PyGenObject *gen)
536{
Yury Selivanov77c96812016-02-13 17:59:05 -0500537 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000538}
539
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000540/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200541 * Set StopIteration with specified value. Value can be arbitrary object
542 * or NULL.
543 *
544 * Returns 0 if StopIteration is set and -1 if any other exception is set.
545 */
546int
547_PyGen_SetStopIterationValue(PyObject *value)
548{
549 PyObject *e;
550
551 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400552 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200553 {
554 /* Delay exception instantiation if we can */
555 PyErr_SetObject(PyExc_StopIteration, value);
556 return 0;
557 }
558 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100559 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200560 *
561 * We do this to handle a situation when "value" is a tuple, in which
562 * case PyErr_SetObject would set the value of StopIteration to
563 * the first element of the tuple.
564 *
565 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
566 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100567 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200568 if (e == NULL) {
569 return -1;
570 }
571 PyErr_SetObject(PyExc_StopIteration, e);
572 Py_DECREF(e);
573 return 0;
574}
575
576/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000577 * If StopIteration exception is set, fetches its 'value'
578 * attribute if any, otherwise sets pvalue to None.
579 *
580 * Returns 0 if no exception or StopIteration is set.
581 * If any other exception is set, returns -1 and leaves
582 * pvalue unchanged.
583 */
584
585int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200586_PyGen_FetchStopIterationValue(PyObject **pvalue)
587{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000588 PyObject *et, *ev, *tb;
589 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500590
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000591 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
592 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200593 if (ev) {
594 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300595 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200596 value = ((PyStopIterationObject *)ev)->value;
597 Py_INCREF(value);
598 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200599 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
600 /* Avoid normalisation and take ev as value.
601 *
602 * Normalization is required if the value is a tuple, in
603 * that case the value of StopIteration would be set to
604 * the first element of the tuple.
605 *
606 * (See _PyErr_CreateException code for details.)
607 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200608 value = ev;
609 } else {
610 /* normalisation required */
611 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300612 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200613 PyErr_Restore(et, ev, tb);
614 return -1;
615 }
616 value = ((PyStopIterationObject *)ev)->value;
617 Py_INCREF(value);
618 Py_DECREF(ev);
619 }
620 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000621 Py_XDECREF(et);
622 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000623 } else if (PyErr_Occurred()) {
624 return -1;
625 }
626 if (value == NULL) {
627 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100628 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000629 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000630 *pvalue = value;
631 return 0;
632}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000633
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000634static PyObject *
635gen_repr(PyGenObject *gen)
636{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400637 return PyUnicode_FromFormat("<generator object %S at %p>",
638 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000639}
640
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000641static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200642gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000643{
Victor Stinner40ee3012014-06-16 15:59:28 +0200644 Py_INCREF(op->gi_name);
645 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000646}
647
Victor Stinner40ee3012014-06-16 15:59:28 +0200648static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200649gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200650{
Victor Stinner40ee3012014-06-16 15:59:28 +0200651 /* Not legal to del gen.gi_name or to set it to anything
652 * other than a string object. */
653 if (value == NULL || !PyUnicode_Check(value)) {
654 PyErr_SetString(PyExc_TypeError,
655 "__name__ must be set to a string object");
656 return -1;
657 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200658 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300659 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200660 return 0;
661}
662
663static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200664gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200665{
666 Py_INCREF(op->gi_qualname);
667 return op->gi_qualname;
668}
669
670static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200671gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200672{
Victor Stinner40ee3012014-06-16 15:59:28 +0200673 /* Not legal to del gen.__qualname__ or to set it to anything
674 * other than a string object. */
675 if (value == NULL || !PyUnicode_Check(value)) {
676 PyErr_SetString(PyExc_TypeError,
677 "__qualname__ must be set to a string object");
678 return -1;
679 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200680 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300681 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200682 return 0;
683}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000684
Yury Selivanove13f8f32015-07-03 00:23:30 -0400685static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200686gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400687{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500688 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400689 if (yf == NULL)
690 Py_RETURN_NONE;
691 return yf;
692}
693
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000694static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200695 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
696 PyDoc_STR("name of the generator")},
697 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
698 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400699 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
700 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200701 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000702};
703
Martin v. Löwise440e472004-06-01 15:22:42 +0000704static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200705 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
706 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
707 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000709};
710
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000711static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500712 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
714 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
715 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000716};
717
Martin v. Löwise440e472004-06-01 15:22:42 +0000718PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyVarObject_HEAD_INIT(&PyType_Type, 0)
720 "generator", /* tp_name */
721 sizeof(PyGenObject), /* tp_basicsize */
722 0, /* tp_itemsize */
723 /* methods */
724 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200725 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 0, /* tp_getattr */
727 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400728 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 (reprfunc)gen_repr, /* tp_repr */
730 0, /* tp_as_number */
731 0, /* tp_as_sequence */
732 0, /* tp_as_mapping */
733 0, /* tp_hash */
734 0, /* tp_call */
735 0, /* tp_str */
736 PyObject_GenericGetAttr, /* tp_getattro */
737 0, /* tp_setattro */
738 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200739 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 0, /* tp_doc */
741 (traverseproc)gen_traverse, /* tp_traverse */
742 0, /* tp_clear */
743 0, /* tp_richcompare */
744 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400745 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 (iternextfunc)gen_iternext, /* tp_iternext */
747 gen_methods, /* tp_methods */
748 gen_memberlist, /* tp_members */
749 gen_getsetlist, /* tp_getset */
750 0, /* tp_base */
751 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 0, /* tp_descr_get */
754 0, /* tp_descr_set */
755 0, /* tp_dictoffset */
756 0, /* tp_init */
757 0, /* tp_alloc */
758 0, /* tp_new */
759 0, /* tp_free */
760 0, /* tp_is_gc */
761 0, /* tp_bases */
762 0, /* tp_mro */
763 0, /* tp_cache */
764 0, /* tp_subclasses */
765 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200766 0, /* tp_del */
767 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200768 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000769};
770
Yury Selivanov5376ba92015-06-22 12:19:30 -0400771static PyObject *
772gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
773 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000774{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400775 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (gen == NULL) {
777 Py_DECREF(f);
778 return NULL;
779 }
780 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200781 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_INCREF(f->f_code);
783 gen->gi_code = (PyObject *)(f->f_code);
784 gen->gi_running = 0;
785 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100786 gen->gi_exc_state.exc_type = NULL;
787 gen->gi_exc_state.exc_value = NULL;
788 gen->gi_exc_state.exc_traceback = NULL;
789 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200790 if (name != NULL)
791 gen->gi_name = name;
792 else
793 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
794 Py_INCREF(gen->gi_name);
795 if (qualname != NULL)
796 gen->gi_qualname = qualname;
797 else
798 gen->gi_qualname = gen->gi_name;
799 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 _PyObject_GC_TRACK(gen);
801 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000802}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000803
Victor Stinner40ee3012014-06-16 15:59:28 +0200804PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400805PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
806{
807 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
808}
809
810PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200811PyGen_New(PyFrameObject *f)
812{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400813 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200814}
815
Yury Selivanov5376ba92015-06-22 12:19:30 -0400816/* Coroutine Object */
817
818typedef struct {
819 PyObject_HEAD
820 PyCoroObject *cw_coroutine;
821} PyCoroWrapper;
822
823static int
824gen_is_coroutine(PyObject *o)
825{
826 if (PyGen_CheckExact(o)) {
827 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
828 if (code->co_flags & CO_ITERABLE_COROUTINE) {
829 return 1;
830 }
831 }
832 return 0;
833}
834
Yury Selivanov75445082015-05-11 22:57:16 -0400835/*
836 * This helper function returns an awaitable for `o`:
837 * - `o` if `o` is a coroutine-object;
838 * - `type(o)->tp_as_async->am_await(o)`
839 *
840 * Raises a TypeError if it's not possible to return
841 * an awaitable and returns NULL.
842 */
843PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400844_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400845{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400846 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400847 PyTypeObject *ot;
848
Yury Selivanov5376ba92015-06-22 12:19:30 -0400849 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
850 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400851 Py_INCREF(o);
852 return o;
853 }
854
855 ot = Py_TYPE(o);
856 if (ot->tp_as_async != NULL) {
857 getter = ot->tp_as_async->am_await;
858 }
859 if (getter != NULL) {
860 PyObject *res = (*getter)(o);
861 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400862 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
863 /* __await__ must return an *iterator*, not
864 a coroutine or another awaitable (see PEP 492) */
865 PyErr_SetString(PyExc_TypeError,
866 "__await__() returned a coroutine");
867 Py_CLEAR(res);
868 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400869 PyErr_Format(PyExc_TypeError,
870 "__await__() returned non-iterator "
871 "of type '%.100s'",
872 Py_TYPE(res)->tp_name);
873 Py_CLEAR(res);
874 }
Yury Selivanov75445082015-05-11 22:57:16 -0400875 }
876 return res;
877 }
878
879 PyErr_Format(PyExc_TypeError,
880 "object %.100s can't be used in 'await' expression",
881 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400882 return NULL;
883}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400884
885static PyObject *
886coro_repr(PyCoroObject *coro)
887{
888 return PyUnicode_FromFormat("<coroutine object %S at %p>",
889 coro->cr_qualname, coro);
890}
891
892static PyObject *
893coro_await(PyCoroObject *coro)
894{
895 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
896 if (cw == NULL) {
897 return NULL;
898 }
899 Py_INCREF(coro);
900 cw->cw_coroutine = coro;
901 _PyObject_GC_TRACK(cw);
902 return (PyObject *)cw;
903}
904
Yury Selivanove13f8f32015-07-03 00:23:30 -0400905static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200906coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400907{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500908 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400909 if (yf == NULL)
910 Py_RETURN_NONE;
911 return yf;
912}
913
Yury Selivanov5376ba92015-06-22 12:19:30 -0400914static PyGetSetDef coro_getsetlist[] = {
915 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
916 PyDoc_STR("name of the coroutine")},
917 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
918 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400919 {"cr_await", (getter)coro_get_cr_await, NULL,
920 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400921 {NULL} /* Sentinel */
922};
923
924static PyMemberDef coro_memberlist[] = {
925 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
926 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
927 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800928 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400929 {NULL} /* Sentinel */
930};
931
932PyDoc_STRVAR(coro_send_doc,
933"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400934return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400935
936PyDoc_STRVAR(coro_throw_doc,
937"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400938return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400939
940PyDoc_STRVAR(coro_close_doc,
941"close() -> raise GeneratorExit inside coroutine.");
942
943static PyMethodDef coro_methods[] = {
944 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
945 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
946 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
947 {NULL, NULL} /* Sentinel */
948};
949
950static PyAsyncMethods coro_as_async = {
951 (unaryfunc)coro_await, /* am_await */
952 0, /* am_aiter */
953 0 /* am_anext */
954};
955
956PyTypeObject PyCoro_Type = {
957 PyVarObject_HEAD_INIT(&PyType_Type, 0)
958 "coroutine", /* tp_name */
959 sizeof(PyCoroObject), /* tp_basicsize */
960 0, /* tp_itemsize */
961 /* methods */
962 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200963 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400964 0, /* tp_getattr */
965 0, /* tp_setattr */
966 &coro_as_async, /* tp_as_async */
967 (reprfunc)coro_repr, /* tp_repr */
968 0, /* tp_as_number */
969 0, /* tp_as_sequence */
970 0, /* tp_as_mapping */
971 0, /* tp_hash */
972 0, /* tp_call */
973 0, /* tp_str */
974 PyObject_GenericGetAttr, /* tp_getattro */
975 0, /* tp_setattro */
976 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200977 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400978 0, /* tp_doc */
979 (traverseproc)gen_traverse, /* tp_traverse */
980 0, /* tp_clear */
981 0, /* tp_richcompare */
982 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
983 0, /* tp_iter */
984 0, /* tp_iternext */
985 coro_methods, /* tp_methods */
986 coro_memberlist, /* tp_members */
987 coro_getsetlist, /* tp_getset */
988 0, /* tp_base */
989 0, /* tp_dict */
990 0, /* tp_descr_get */
991 0, /* tp_descr_set */
992 0, /* tp_dictoffset */
993 0, /* tp_init */
994 0, /* tp_alloc */
995 0, /* tp_new */
996 0, /* tp_free */
997 0, /* tp_is_gc */
998 0, /* tp_bases */
999 0, /* tp_mro */
1000 0, /* tp_cache */
1001 0, /* tp_subclasses */
1002 0, /* tp_weaklist */
1003 0, /* tp_del */
1004 0, /* tp_version_tag */
1005 _PyGen_Finalize, /* tp_finalize */
1006};
1007
1008static void
1009coro_wrapper_dealloc(PyCoroWrapper *cw)
1010{
1011 _PyObject_GC_UNTRACK((PyObject *)cw);
1012 Py_CLEAR(cw->cw_coroutine);
1013 PyObject_GC_Del(cw);
1014}
1015
1016static PyObject *
1017coro_wrapper_iternext(PyCoroWrapper *cw)
1018{
Yury Selivanov77c96812016-02-13 17:59:05 -05001019 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001020}
1021
1022static PyObject *
1023coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1024{
Yury Selivanov77c96812016-02-13 17:59:05 -05001025 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001026}
1027
1028static PyObject *
1029coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1030{
1031 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1032}
1033
1034static PyObject *
1035coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1036{
1037 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1038}
1039
1040static int
1041coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1042{
1043 Py_VISIT((PyObject *)cw->cw_coroutine);
1044 return 0;
1045}
1046
1047static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001048 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1049 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1050 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001051 {NULL, NULL} /* Sentinel */
1052};
1053
1054PyTypeObject _PyCoroWrapper_Type = {
1055 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1056 "coroutine_wrapper",
1057 sizeof(PyCoroWrapper), /* tp_basicsize */
1058 0, /* tp_itemsize */
1059 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001060 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001061 0, /* tp_getattr */
1062 0, /* tp_setattr */
1063 0, /* tp_as_async */
1064 0, /* tp_repr */
1065 0, /* tp_as_number */
1066 0, /* tp_as_sequence */
1067 0, /* tp_as_mapping */
1068 0, /* tp_hash */
1069 0, /* tp_call */
1070 0, /* tp_str */
1071 PyObject_GenericGetAttr, /* tp_getattro */
1072 0, /* tp_setattro */
1073 0, /* tp_as_buffer */
1074 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1075 "A wrapper object implementing __await__ for coroutines.",
1076 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1077 0, /* tp_clear */
1078 0, /* tp_richcompare */
1079 0, /* tp_weaklistoffset */
1080 PyObject_SelfIter, /* tp_iter */
1081 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1082 coro_wrapper_methods, /* tp_methods */
1083 0, /* tp_members */
1084 0, /* tp_getset */
1085 0, /* tp_base */
1086 0, /* tp_dict */
1087 0, /* tp_descr_get */
1088 0, /* tp_descr_set */
1089 0, /* tp_dictoffset */
1090 0, /* tp_init */
1091 0, /* tp_alloc */
1092 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001093 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001094};
1095
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001096static PyObject *
1097compute_cr_origin(int origin_depth)
1098{
1099 PyFrameObject *frame = PyEval_GetFrame();
1100 /* First count how many frames we have */
1101 int frame_count = 0;
1102 for (; frame && frame_count < origin_depth; ++frame_count) {
1103 frame = frame->f_back;
1104 }
1105
1106 /* Now collect them */
1107 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001108 if (cr_origin == NULL) {
1109 return NULL;
1110 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001111 frame = PyEval_GetFrame();
1112 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001113 PyCodeObject *code = frame->f_code;
1114 PyObject *frameinfo = Py_BuildValue("OiO",
1115 code->co_filename,
1116 PyFrame_GetLineNumber(frame),
1117 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001118 if (!frameinfo) {
1119 Py_DECREF(cr_origin);
1120 return NULL;
1121 }
1122 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1123 frame = frame->f_back;
1124 }
1125
1126 return cr_origin;
1127}
1128
Yury Selivanov5376ba92015-06-22 12:19:30 -04001129PyObject *
1130PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1131{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001132 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1133 if (!coro) {
1134 return NULL;
1135 }
1136
Victor Stinner50b48572018-11-01 01:51:40 +01001137 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001138 int origin_depth = tstate->coroutine_origin_tracking_depth;
1139
1140 if (origin_depth == 0) {
1141 ((PyCoroObject *)coro)->cr_origin = NULL;
1142 } else {
1143 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001144 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001145 if (!cr_origin) {
1146 Py_DECREF(coro);
1147 return NULL;
1148 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001149 }
1150
1151 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001152}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001153
1154
Yury Selivanoveb636452016-09-08 22:01:51 -07001155/* ========= Asynchronous Generators ========= */
1156
1157
1158typedef enum {
1159 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1160 AWAITABLE_STATE_ITER, /* being iterated */
1161 AWAITABLE_STATE_CLOSED, /* closed */
1162} AwaitableState;
1163
1164
Victor Stinner78a02c22020-06-05 02:34:14 +02001165typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001166 PyObject_HEAD
1167 PyAsyncGenObject *ags_gen;
1168
1169 /* Can be NULL, when in the __anext__() mode
1170 (equivalent of "asend(None)") */
1171 PyObject *ags_sendval;
1172
1173 AwaitableState ags_state;
1174} PyAsyncGenASend;
1175
1176
Victor Stinner78a02c22020-06-05 02:34:14 +02001177typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001178 PyObject_HEAD
1179 PyAsyncGenObject *agt_gen;
1180
1181 /* Can be NULL, when in the "aclose()" mode
1182 (equivalent of "athrow(GeneratorExit)") */
1183 PyObject *agt_args;
1184
1185 AwaitableState agt_state;
1186} PyAsyncGenAThrow;
1187
1188
Victor Stinner78a02c22020-06-05 02:34:14 +02001189typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001190 PyObject_HEAD
1191 PyObject *agw_val;
1192} _PyAsyncGenWrappedValue;
1193
1194
Yury Selivanoveb636452016-09-08 22:01:51 -07001195#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001196 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001197
1198#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001199 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001200
1201
1202static int
1203async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1204{
1205 Py_VISIT(gen->ag_finalizer);
1206 return gen_traverse((PyGenObject*)gen, visit, arg);
1207}
1208
1209
1210static PyObject *
1211async_gen_repr(PyAsyncGenObject *o)
1212{
1213 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1214 o->ag_qualname, o);
1215}
1216
1217
1218static int
1219async_gen_init_hooks(PyAsyncGenObject *o)
1220{
1221 PyThreadState *tstate;
1222 PyObject *finalizer;
1223 PyObject *firstiter;
1224
1225 if (o->ag_hooks_inited) {
1226 return 0;
1227 }
1228
1229 o->ag_hooks_inited = 1;
1230
Victor Stinner50b48572018-11-01 01:51:40 +01001231 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001232
1233 finalizer = tstate->async_gen_finalizer;
1234 if (finalizer) {
1235 Py_INCREF(finalizer);
1236 o->ag_finalizer = finalizer;
1237 }
1238
1239 firstiter = tstate->async_gen_firstiter;
1240 if (firstiter) {
1241 PyObject *res;
1242
1243 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001244 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001245 Py_DECREF(firstiter);
1246 if (res == NULL) {
1247 return 1;
1248 }
1249 Py_DECREF(res);
1250 }
1251
1252 return 0;
1253}
1254
1255
1256static PyObject *
1257async_gen_anext(PyAsyncGenObject *o)
1258{
1259 if (async_gen_init_hooks(o)) {
1260 return NULL;
1261 }
1262 return async_gen_asend_new(o, NULL);
1263}
1264
1265
1266static PyObject *
1267async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1268{
1269 if (async_gen_init_hooks(o)) {
1270 return NULL;
1271 }
1272 return async_gen_asend_new(o, arg);
1273}
1274
1275
1276static PyObject *
1277async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1278{
1279 if (async_gen_init_hooks(o)) {
1280 return NULL;
1281 }
1282 return async_gen_athrow_new(o, NULL);
1283}
1284
1285static PyObject *
1286async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1287{
1288 if (async_gen_init_hooks(o)) {
1289 return NULL;
1290 }
1291 return async_gen_athrow_new(o, args);
1292}
1293
1294
1295static PyGetSetDef async_gen_getsetlist[] = {
1296 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1297 PyDoc_STR("name of the async generator")},
1298 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1299 PyDoc_STR("qualified name of the async generator")},
1300 {"ag_await", (getter)coro_get_cr_await, NULL,
1301 PyDoc_STR("object being awaited on, or None")},
1302 {NULL} /* Sentinel */
1303};
1304
1305static PyMemberDef async_gen_memberlist[] = {
1306 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001307 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1308 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001309 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1310 {NULL} /* Sentinel */
1311};
1312
1313PyDoc_STRVAR(async_aclose_doc,
1314"aclose() -> raise GeneratorExit inside generator.");
1315
1316PyDoc_STRVAR(async_asend_doc,
1317"asend(v) -> send 'v' in generator.");
1318
1319PyDoc_STRVAR(async_athrow_doc,
1320"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1321
1322static PyMethodDef async_gen_methods[] = {
1323 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1324 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1325 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001326 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1327 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001328 {NULL, NULL} /* Sentinel */
1329};
1330
1331
1332static PyAsyncMethods async_gen_as_async = {
1333 0, /* am_await */
1334 PyObject_SelfIter, /* am_aiter */
1335 (unaryfunc)async_gen_anext /* am_anext */
1336};
1337
1338
1339PyTypeObject PyAsyncGen_Type = {
1340 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1341 "async_generator", /* tp_name */
1342 sizeof(PyAsyncGenObject), /* tp_basicsize */
1343 0, /* tp_itemsize */
1344 /* methods */
1345 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001346 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001347 0, /* tp_getattr */
1348 0, /* tp_setattr */
1349 &async_gen_as_async, /* tp_as_async */
1350 (reprfunc)async_gen_repr, /* tp_repr */
1351 0, /* tp_as_number */
1352 0, /* tp_as_sequence */
1353 0, /* tp_as_mapping */
1354 0, /* tp_hash */
1355 0, /* tp_call */
1356 0, /* tp_str */
1357 PyObject_GenericGetAttr, /* tp_getattro */
1358 0, /* tp_setattro */
1359 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001360 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001361 0, /* tp_doc */
1362 (traverseproc)async_gen_traverse, /* tp_traverse */
1363 0, /* tp_clear */
1364 0, /* tp_richcompare */
1365 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1366 0, /* tp_iter */
1367 0, /* tp_iternext */
1368 async_gen_methods, /* tp_methods */
1369 async_gen_memberlist, /* tp_members */
1370 async_gen_getsetlist, /* tp_getset */
1371 0, /* tp_base */
1372 0, /* tp_dict */
1373 0, /* tp_descr_get */
1374 0, /* tp_descr_set */
1375 0, /* tp_dictoffset */
1376 0, /* tp_init */
1377 0, /* tp_alloc */
1378 0, /* tp_new */
1379 0, /* tp_free */
1380 0, /* tp_is_gc */
1381 0, /* tp_bases */
1382 0, /* tp_mro */
1383 0, /* tp_cache */
1384 0, /* tp_subclasses */
1385 0, /* tp_weaklist */
1386 0, /* tp_del */
1387 0, /* tp_version_tag */
1388 _PyGen_Finalize, /* tp_finalize */
1389};
1390
1391
1392PyObject *
1393PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1394{
1395 PyAsyncGenObject *o;
1396 o = (PyAsyncGenObject *)gen_new_with_qualname(
1397 &PyAsyncGen_Type, f, name, qualname);
1398 if (o == NULL) {
1399 return NULL;
1400 }
1401 o->ag_finalizer = NULL;
1402 o->ag_closed = 0;
1403 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001404 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001405 return (PyObject*)o;
1406}
1407
1408
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001409void
Victor Stinner78a02c22020-06-05 02:34:14 +02001410_PyAsyncGen_ClearFreeLists(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001411{
Victor Stinner78a02c22020-06-05 02:34:14 +02001412 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1413
1414 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001415 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001416 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001417 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001418 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001419 }
1420
Victor Stinner78a02c22020-06-05 02:34:14 +02001421 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001422 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001423 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001424 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001425 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001426 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001427}
1428
1429void
Victor Stinner78a02c22020-06-05 02:34:14 +02001430_PyAsyncGen_Fini(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001431{
Victor Stinner78a02c22020-06-05 02:34:14 +02001432 _PyAsyncGen_ClearFreeLists(tstate);
Yury Selivanoveb636452016-09-08 22:01:51 -07001433}
1434
1435
1436static PyObject *
1437async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1438{
1439 if (result == NULL) {
1440 if (!PyErr_Occurred()) {
1441 PyErr_SetNone(PyExc_StopAsyncIteration);
1442 }
1443
1444 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1445 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1446 ) {
1447 gen->ag_closed = 1;
1448 }
1449
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001450 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001451 return NULL;
1452 }
1453
1454 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1455 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001456 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001457 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001458 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001459 return NULL;
1460 }
1461
1462 return result;
1463}
1464
1465
1466/* ---------- Async Generator ASend Awaitable ------------ */
1467
1468
1469static void
1470async_gen_asend_dealloc(PyAsyncGenASend *o)
1471{
Yury Selivanov29310c42016-11-08 19:46:22 -05001472 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001473 Py_CLEAR(o->ags_gen);
1474 Py_CLEAR(o->ags_sendval);
Victor Stinner78a02c22020-06-05 02:34:14 +02001475 PyInterpreterState *interp = _PyInterpreterState_GET();
1476 struct _Py_async_gen_state *state = &interp->async_gen;
1477 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001478 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001479 state->asend_freelist[state->asend_numfree++] = o;
1480 }
1481 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001482 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001483 }
1484}
1485
Yury Selivanov29310c42016-11-08 19:46:22 -05001486static int
1487async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1488{
1489 Py_VISIT(o->ags_gen);
1490 Py_VISIT(o->ags_sendval);
1491 return 0;
1492}
1493
Yury Selivanoveb636452016-09-08 22:01:51 -07001494
1495static PyObject *
1496async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1497{
1498 PyObject *result;
1499
1500 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001501 PyErr_SetString(
1502 PyExc_RuntimeError,
1503 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001504 return NULL;
1505 }
1506
1507 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001508 if (o->ags_gen->ag_running_async) {
1509 PyErr_SetString(
1510 PyExc_RuntimeError,
1511 "anext(): asynchronous generator is already running");
1512 return NULL;
1513 }
1514
Yury Selivanoveb636452016-09-08 22:01:51 -07001515 if (arg == NULL || arg == Py_None) {
1516 arg = o->ags_sendval;
1517 }
1518 o->ags_state = AWAITABLE_STATE_ITER;
1519 }
1520
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001521 o->ags_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001522 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1523 result = async_gen_unwrap_value(o->ags_gen, result);
1524
1525 if (result == NULL) {
1526 o->ags_state = AWAITABLE_STATE_CLOSED;
1527 }
1528
1529 return result;
1530}
1531
1532
1533static PyObject *
1534async_gen_asend_iternext(PyAsyncGenASend *o)
1535{
1536 return async_gen_asend_send(o, NULL);
1537}
1538
1539
1540static PyObject *
1541async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1542{
1543 PyObject *result;
1544
1545 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001546 PyErr_SetString(
1547 PyExc_RuntimeError,
1548 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001549 return NULL;
1550 }
1551
1552 result = gen_throw((PyGenObject*)o->ags_gen, args);
1553 result = async_gen_unwrap_value(o->ags_gen, result);
1554
1555 if (result == NULL) {
1556 o->ags_state = AWAITABLE_STATE_CLOSED;
1557 }
1558
1559 return result;
1560}
1561
1562
1563static PyObject *
1564async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1565{
1566 o->ags_state = AWAITABLE_STATE_CLOSED;
1567 Py_RETURN_NONE;
1568}
1569
1570
1571static PyMethodDef async_gen_asend_methods[] = {
1572 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1573 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1574 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1575 {NULL, NULL} /* Sentinel */
1576};
1577
1578
1579static PyAsyncMethods async_gen_asend_as_async = {
1580 PyObject_SelfIter, /* am_await */
1581 0, /* am_aiter */
1582 0 /* am_anext */
1583};
1584
1585
1586PyTypeObject _PyAsyncGenASend_Type = {
1587 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1588 "async_generator_asend", /* tp_name */
1589 sizeof(PyAsyncGenASend), /* tp_basicsize */
1590 0, /* tp_itemsize */
1591 /* methods */
1592 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001593 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001594 0, /* tp_getattr */
1595 0, /* tp_setattr */
1596 &async_gen_asend_as_async, /* tp_as_async */
1597 0, /* tp_repr */
1598 0, /* tp_as_number */
1599 0, /* tp_as_sequence */
1600 0, /* tp_as_mapping */
1601 0, /* tp_hash */
1602 0, /* tp_call */
1603 0, /* tp_str */
1604 PyObject_GenericGetAttr, /* tp_getattro */
1605 0, /* tp_setattro */
1606 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001607 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001608 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001609 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001610 0, /* tp_clear */
1611 0, /* tp_richcompare */
1612 0, /* tp_weaklistoffset */
1613 PyObject_SelfIter, /* tp_iter */
1614 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1615 async_gen_asend_methods, /* tp_methods */
1616 0, /* tp_members */
1617 0, /* tp_getset */
1618 0, /* tp_base */
1619 0, /* tp_dict */
1620 0, /* tp_descr_get */
1621 0, /* tp_descr_set */
1622 0, /* tp_dictoffset */
1623 0, /* tp_init */
1624 0, /* tp_alloc */
1625 0, /* tp_new */
1626};
1627
1628
1629static PyObject *
1630async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1631{
1632 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001633 PyInterpreterState *interp = _PyInterpreterState_GET();
1634 struct _Py_async_gen_state *state = &interp->async_gen;
1635 if (state->asend_numfree) {
1636 state->asend_numfree--;
1637 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001638 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001639 }
1640 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001641 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001642 if (o == NULL) {
1643 return NULL;
1644 }
1645 }
1646
1647 Py_INCREF(gen);
1648 o->ags_gen = gen;
1649
1650 Py_XINCREF(sendval);
1651 o->ags_sendval = sendval;
1652
1653 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001654
1655 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001656 return (PyObject*)o;
1657}
1658
1659
1660/* ---------- Async Generator Value Wrapper ------------ */
1661
1662
1663static void
1664async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1665{
Yury Selivanov29310c42016-11-08 19:46:22 -05001666 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001667 Py_CLEAR(o->agw_val);
Victor Stinner78a02c22020-06-05 02:34:14 +02001668 PyInterpreterState *interp = _PyInterpreterState_GET();
1669 struct _Py_async_gen_state *state = &interp->async_gen;
1670 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001671 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001672 state->value_freelist[state->value_numfree++] = o;
1673 }
1674 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001675 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001676 }
1677}
1678
1679
Yury Selivanov29310c42016-11-08 19:46:22 -05001680static int
1681async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1682 visitproc visit, void *arg)
1683{
1684 Py_VISIT(o->agw_val);
1685 return 0;
1686}
1687
1688
Yury Selivanoveb636452016-09-08 22:01:51 -07001689PyTypeObject _PyAsyncGenWrappedValue_Type = {
1690 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1691 "async_generator_wrapped_value", /* tp_name */
1692 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1693 0, /* tp_itemsize */
1694 /* methods */
1695 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001696 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001697 0, /* tp_getattr */
1698 0, /* tp_setattr */
1699 0, /* tp_as_async */
1700 0, /* tp_repr */
1701 0, /* tp_as_number */
1702 0, /* tp_as_sequence */
1703 0, /* tp_as_mapping */
1704 0, /* tp_hash */
1705 0, /* tp_call */
1706 0, /* tp_str */
1707 PyObject_GenericGetAttr, /* tp_getattro */
1708 0, /* tp_setattro */
1709 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001710 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001711 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001712 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001713 0, /* tp_clear */
1714 0, /* tp_richcompare */
1715 0, /* tp_weaklistoffset */
1716 0, /* tp_iter */
1717 0, /* tp_iternext */
1718 0, /* tp_methods */
1719 0, /* tp_members */
1720 0, /* tp_getset */
1721 0, /* tp_base */
1722 0, /* tp_dict */
1723 0, /* tp_descr_get */
1724 0, /* tp_descr_set */
1725 0, /* tp_dictoffset */
1726 0, /* tp_init */
1727 0, /* tp_alloc */
1728 0, /* tp_new */
1729};
1730
1731
1732PyObject *
1733_PyAsyncGenValueWrapperNew(PyObject *val)
1734{
1735 _PyAsyncGenWrappedValue *o;
1736 assert(val);
1737
Victor Stinner78a02c22020-06-05 02:34:14 +02001738 PyInterpreterState *interp = _PyInterpreterState_GET();
1739 struct _Py_async_gen_state *state = &interp->async_gen;
1740 if (state->value_numfree) {
1741 state->value_numfree--;
1742 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001743 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1744 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001745 }
1746 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001747 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1748 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001749 if (o == NULL) {
1750 return NULL;
1751 }
1752 }
1753 o->agw_val = val;
1754 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001755 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001756 return (PyObject*)o;
1757}
1758
1759
1760/* ---------- Async Generator AThrow awaitable ------------ */
1761
1762
1763static void
1764async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1765{
Yury Selivanov29310c42016-11-08 19:46:22 -05001766 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001767 Py_CLEAR(o->agt_gen);
1768 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001769 PyObject_GC_Del(o);
1770}
1771
1772
1773static int
1774async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1775{
1776 Py_VISIT(o->agt_gen);
1777 Py_VISIT(o->agt_args);
1778 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001779}
1780
1781
1782static PyObject *
1783async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1784{
1785 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1786 PyFrameObject *f = gen->gi_frame;
1787 PyObject *retval;
1788
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001789 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001790 PyErr_SetString(
1791 PyExc_RuntimeError,
1792 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001793 return NULL;
1794 }
1795
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001796 if (f == NULL || f->f_stacktop == NULL) {
1797 o->agt_state = AWAITABLE_STATE_CLOSED;
1798 PyErr_SetNone(PyExc_StopIteration);
1799 return NULL;
1800 }
1801
Yury Selivanoveb636452016-09-08 22:01:51 -07001802 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001803 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001804 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001805 if (o->agt_args == NULL) {
1806 PyErr_SetString(
1807 PyExc_RuntimeError,
1808 "aclose(): asynchronous generator is already running");
1809 }
1810 else {
1811 PyErr_SetString(
1812 PyExc_RuntimeError,
1813 "athrow(): asynchronous generator is already running");
1814 }
1815 return NULL;
1816 }
1817
Yury Selivanoveb636452016-09-08 22:01:51 -07001818 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001819 o->agt_state = AWAITABLE_STATE_CLOSED;
1820 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001821 return NULL;
1822 }
1823
1824 if (arg != Py_None) {
1825 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1826 return NULL;
1827 }
1828
1829 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001830 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001831
1832 if (o->agt_args == NULL) {
1833 /* aclose() mode */
1834 o->agt_gen->ag_closed = 1;
1835
1836 retval = _gen_throw((PyGenObject *)gen,
1837 0, /* Do not close generator when
1838 PyExc_GeneratorExit is passed */
1839 PyExc_GeneratorExit, NULL, NULL);
1840
1841 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1842 Py_DECREF(retval);
1843 goto yield_close;
1844 }
1845 } else {
1846 PyObject *typ;
1847 PyObject *tb = NULL;
1848 PyObject *val = NULL;
1849
1850 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1851 &typ, &val, &tb)) {
1852 return NULL;
1853 }
1854
1855 retval = _gen_throw((PyGenObject *)gen,
1856 0, /* Do not close generator when
1857 PyExc_GeneratorExit is passed */
1858 typ, val, tb);
1859 retval = async_gen_unwrap_value(o->agt_gen, retval);
1860 }
1861 if (retval == NULL) {
1862 goto check_error;
1863 }
1864 return retval;
1865 }
1866
1867 assert(o->agt_state == AWAITABLE_STATE_ITER);
1868
1869 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1870 if (o->agt_args) {
1871 return async_gen_unwrap_value(o->agt_gen, retval);
1872 } else {
1873 /* aclose() mode */
1874 if (retval) {
1875 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1876 Py_DECREF(retval);
1877 goto yield_close;
1878 }
1879 else {
1880 return retval;
1881 }
1882 }
1883 else {
1884 goto check_error;
1885 }
1886 }
1887
1888yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001889 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001890 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001891 PyErr_SetString(
1892 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1893 return NULL;
1894
1895check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001896 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001897 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001898 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1899 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1900 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001901 if (o->agt_args == NULL) {
1902 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001903 StopAsyncIteration or GeneratorExit; just raise
1904 StopIteration, signalling that this 'aclose()' await
1905 is done.
1906 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001907 PyErr_Clear();
1908 PyErr_SetNone(PyExc_StopIteration);
1909 }
1910 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001911 return NULL;
1912}
1913
1914
1915static PyObject *
1916async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1917{
1918 PyObject *retval;
1919
Yury Selivanoveb636452016-09-08 22:01:51 -07001920 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001921 PyErr_SetString(
1922 PyExc_RuntimeError,
1923 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001924 return NULL;
1925 }
1926
1927 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1928 if (o->agt_args) {
1929 return async_gen_unwrap_value(o->agt_gen, retval);
1930 } else {
1931 /* aclose() mode */
1932 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001933 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001934 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001935 Py_DECREF(retval);
1936 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1937 return NULL;
1938 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08001939 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1940 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1941 {
1942 /* when aclose() is called we don't want to propagate
1943 StopAsyncIteration or GeneratorExit; just raise
1944 StopIteration, signalling that this 'aclose()' await
1945 is done.
1946 */
1947 PyErr_Clear();
1948 PyErr_SetNone(PyExc_StopIteration);
1949 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001950 return retval;
1951 }
1952}
1953
1954
1955static PyObject *
1956async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1957{
1958 return async_gen_athrow_send(o, Py_None);
1959}
1960
1961
1962static PyObject *
1963async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1964{
1965 o->agt_state = AWAITABLE_STATE_CLOSED;
1966 Py_RETURN_NONE;
1967}
1968
1969
1970static PyMethodDef async_gen_athrow_methods[] = {
1971 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1972 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1973 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1974 {NULL, NULL} /* Sentinel */
1975};
1976
1977
1978static PyAsyncMethods async_gen_athrow_as_async = {
1979 PyObject_SelfIter, /* am_await */
1980 0, /* am_aiter */
1981 0 /* am_anext */
1982};
1983
1984
1985PyTypeObject _PyAsyncGenAThrow_Type = {
1986 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1987 "async_generator_athrow", /* tp_name */
1988 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1989 0, /* tp_itemsize */
1990 /* methods */
1991 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001992 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001993 0, /* tp_getattr */
1994 0, /* tp_setattr */
1995 &async_gen_athrow_as_async, /* tp_as_async */
1996 0, /* tp_repr */
1997 0, /* tp_as_number */
1998 0, /* tp_as_sequence */
1999 0, /* tp_as_mapping */
2000 0, /* tp_hash */
2001 0, /* tp_call */
2002 0, /* tp_str */
2003 PyObject_GenericGetAttr, /* tp_getattro */
2004 0, /* tp_setattro */
2005 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002006 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002007 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002008 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002009 0, /* tp_clear */
2010 0, /* tp_richcompare */
2011 0, /* tp_weaklistoffset */
2012 PyObject_SelfIter, /* tp_iter */
2013 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2014 async_gen_athrow_methods, /* tp_methods */
2015 0, /* tp_members */
2016 0, /* tp_getset */
2017 0, /* tp_base */
2018 0, /* tp_dict */
2019 0, /* tp_descr_get */
2020 0, /* tp_descr_set */
2021 0, /* tp_dictoffset */
2022 0, /* tp_init */
2023 0, /* tp_alloc */
2024 0, /* tp_new */
2025};
2026
2027
2028static PyObject *
2029async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2030{
2031 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002032 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002033 if (o == NULL) {
2034 return NULL;
2035 }
2036 o->agt_gen = gen;
2037 o->agt_args = args;
2038 o->agt_state = AWAITABLE_STATE_INIT;
2039 Py_INCREF(gen);
2040 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002041 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002042 return (PyObject*)o;
2043}