blob: 3ac38de0c311bca0dc250e096a0b2f8a76dc4f7a [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02004#include "pycore_ceval.h" // _PyEval_EvalFrame()
Victor Stinnerbcda8f12018-11-21 22:27:47 +01005#include "pycore_object.h"
Chris Jerdonekda742ba2020-05-17 22:47:31 -07006#include "pycore_pyerrors.h" // _PyErr_ClearExcState()
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include "pycore_pystate.h" // _PyThreadState_GET()
Martin v. Löwise440e472004-06-01 15:22:42 +00008#include "frameobject.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02009#include "structmember.h" // PyMemberDef
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +000011
Yury Selivanoveb636452016-09-08 22:01:51 -070012static PyObject *gen_close(PyGenObject *, PyObject *);
13static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
14static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
15
Andy Lester7386a702020-02-13 22:42:56 -060016static const char *NON_INIT_CORO_MSG = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -070017 "just-started coroutine";
18
Andy Lester7386a702020-02-13 22:42:56 -060019static const char *ASYNC_GEN_IGNORED_EXIT_MSG =
Yury Selivanoveb636452016-09-08 22:01:51 -070020 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100021
Mark Shannonae3087c2017-10-22 22:41:51 +010022static inline int
23exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
24{
25 Py_VISIT(exc_state->exc_type);
26 Py_VISIT(exc_state->exc_value);
27 Py_VISIT(exc_state->exc_traceback);
28 return 0;
29}
30
Martin v. Löwise440e472004-06-01 15:22:42 +000031static int
32gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
33{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_VISIT((PyObject *)gen->gi_frame);
35 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020036 Py_VISIT(gen->gi_name);
37 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080038 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
39 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010040 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000041}
42
Antoine Pitrou58720d62013-08-05 23:26:40 +020043void
44_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020045{
46 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070047 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020048 PyObject *error_type, *error_value, *error_traceback;
49
Mark Shannoncb9879b2020-07-17 11:44:23 +010050 if (gen->gi_frame == NULL || _PyFrameHasCompleted(gen->gi_frame)) {
Antoine Pitrou796564c2013-07-30 19:59:21 +020051 /* Generator isn't paused, so no need to close */
52 return;
Yury Selivanov2a2270d2018-01-29 14:31:47 -050053 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020054
Yury Selivanoveb636452016-09-08 22:01:51 -070055 if (PyAsyncGen_CheckExact(self)) {
56 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
57 PyObject *finalizer = agen->ag_finalizer;
58 if (finalizer && !agen->ag_closed) {
59 /* Save the current exception, if any. */
60 PyErr_Fetch(&error_type, &error_value, &error_traceback);
61
Petr Viktorinffd97532020-02-11 17:46:57 +010062 res = PyObject_CallOneArg(finalizer, self);
Yury Selivanoveb636452016-09-08 22:01:51 -070063
64 if (res == NULL) {
65 PyErr_WriteUnraisable(self);
66 } else {
67 Py_DECREF(res);
68 }
69 /* Restore the saved exception. */
70 PyErr_Restore(error_type, error_value, error_traceback);
71 return;
72 }
73 }
74
Antoine Pitrou796564c2013-07-30 19:59:21 +020075 /* Save the current exception, if any. */
76 PyErr_Fetch(&error_type, &error_value, &error_traceback);
77
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070078 /* If `gen` is a coroutine, and if it was never awaited on,
79 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070080 if (gen->gi_code != NULL &&
81 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
Yury Selivanov2a2270d2018-01-29 14:31:47 -050082 gen->gi_frame->f_lasti == -1)
83 {
84 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070085 }
86 else {
87 res = gen_close(gen, NULL);
88 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020089
Benjamin Petersonb88db872016-09-07 08:46:59 -070090 if (res == NULL) {
Yury Selivanov2a2270d2018-01-29 14:31:47 -050091 if (PyErr_Occurred()) {
Benjamin Petersonb88db872016-09-07 08:46:59 -070092 PyErr_WriteUnraisable(self);
Yury Selivanov2a2270d2018-01-29 14:31:47 -050093 }
Benjamin Petersonb88db872016-09-07 08:46:59 -070094 }
95 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020096 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070097 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020098
99 /* Restore the saved exception. */
100 PyErr_Restore(error_type, error_value, error_traceback);
101}
102
103static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000104gen_dealloc(PyGenObject *gen)
105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (gen->gi_weakreflist != NULL)
111 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000112
Antoine Pitrou93963562013-05-14 20:37:52 +0200113 _PyObject_GC_TRACK(self);
114
Antoine Pitrou796564c2013-07-30 19:59:21 +0200115 if (PyObject_CallFinalizerFromDealloc(self))
116 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200117
118 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700119 if (PyAsyncGen_CheckExact(gen)) {
120 /* We have to handle this case for asynchronous generators
121 right here, because this code has to be between UNTRACK
122 and GC_Del. */
123 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
124 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700125 if (gen->gi_frame != NULL) {
126 gen->gi_frame->f_gen = NULL;
127 Py_CLEAR(gen->gi_frame);
128 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800129 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
130 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200133 Py_CLEAR(gen->gi_name);
134 Py_CLEAR(gen->gi_qualname);
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700135 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000137}
138
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300139static PySendResult
140gen_send_ex2(PyGenObject *gen, PyObject *arg, PyObject **presult,
141 int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000142{
Victor Stinner50b48572018-11-01 01:51:40 +0100143 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200145 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000146
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300147 *presult = NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100148 if (f != NULL && _PyFrame_IsExecuting(f)) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200149 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700150 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400151 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700152 }
153 else if (PyAsyncGen_CheckExact(gen)) {
154 msg = "async generator already executing";
155 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400156 PyErr_SetString(PyExc_ValueError, msg);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300157 return PYGEN_ERROR;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500158 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100159 if (f == NULL || _PyFrameHasCompleted(f)) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500160 if (PyCoro_CheckExact(gen) && !closing) {
161 /* `gen` is an exhausted coroutine: raise an error,
162 except when called from gen_close(), which should
163 always be a silent method. */
164 PyErr_SetString(
165 PyExc_RuntimeError,
166 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700167 }
168 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500169 /* `gen` is an exhausted generator:
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300170 only return value if called from send(). */
171 *presult = Py_None;
172 Py_INCREF(*presult);
173 return PYGEN_RETURN;
Yury Selivanov77c96812016-02-13 17:59:05 -0500174 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300175 return PYGEN_ERROR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000177
Mark Shannoncb9879b2020-07-17 11:44:23 +0100178 assert(_PyFrame_IsRunnable(f));
Mark Shannonb37181e2021-04-06 11:48:59 +0100179 assert(f->f_lasti >= 0 || ((unsigned char *)PyBytes_AS_STRING(f->f_code->co_code))[0] == GEN_START);
180 /* Push arg onto the frame's value stack */
181 result = arg ? arg : Py_None;
182 Py_INCREF(result);
183 gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth] = result;
184 gen->gi_frame->f_stackdepth++;
Antoine Pitrou93963562013-05-14 20:37:52 +0200185
186 /* Generators always return to their most recent caller, not
187 * necessarily their creator. */
188 Py_XINCREF(tstate->frame);
189 assert(f->f_back == NULL);
190 f->f_back = tstate->frame;
191
Mark Shannonae3087c2017-10-22 22:41:51 +0100192 gen->gi_exc_state.previous_item = tstate->exc_info;
193 tstate->exc_info = &gen->gi_exc_state;
Chris Jerdonek7c30d122020-05-22 13:33:27 -0700194
195 if (exc) {
196 assert(_PyErr_Occurred(tstate));
197 _PyErr_ChainStackItem(NULL);
198 }
199
Victor Stinnerb9e68122019-11-14 12:20:46 +0100200 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100201 tstate->exc_info = gen->gi_exc_state.previous_item;
202 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200203
204 /* Don't keep the reference to f_back any longer than necessary. It
205 * may keep a chain of frames alive or it could create a reference
206 * cycle. */
207 assert(f->f_back == tstate->frame);
208 Py_CLEAR(f->f_back);
209
210 /* If the generator just returned (as opposed to yielding), signal
211 * that the generator is exhausted. */
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300212 if (result) {
213 if (!_PyFrameHasCompleted(f)) {
214 *presult = result;
215 return PYGEN_NEXT;
216 }
217 assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
218 if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
219 /* Return NULL if called by gen_iternext() */
220 Py_CLEAR(result);
221 }
222 }
223 else {
224 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
225 const char *msg = "generator raised StopIteration";
226 if (PyCoro_CheckExact(gen)) {
227 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700228 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300229 else if (PyAsyncGen_CheckExact(gen)) {
230 msg = "async generator raised StopIteration";
Vladimir Matveev2b053612020-09-18 18:38:38 -0700231 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300232 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
233 }
234 else if (PyAsyncGen_CheckExact(gen) &&
235 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
236 {
237 /* code in `gen` raised a StopAsyncIteration error:
238 raise a RuntimeError.
239 */
240 const char *msg = "async generator raised StopAsyncIteration";
241 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
242 }
243 }
244
245 /* generator can't be rerun, so release the frame */
246 /* first clean reference cycle through stored exception traceback */
247 _PyErr_ClearExcState(&gen->gi_exc_state);
248 gen->gi_frame->f_gen = NULL;
249 gen->gi_frame = NULL;
250 Py_DECREF(f);
251
252 *presult = result;
253 return result ? PYGEN_RETURN : PYGEN_ERROR;
254}
255
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800256static PySendResult
257PyGen_am_send(PyGenObject *gen, PyObject *arg, PyObject **result)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300258{
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800259 return gen_send_ex2(gen, arg, result, 0, 0);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300260}
261
262static PyObject *
263gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
264{
265 PyObject *result;
266 if (gen_send_ex2(gen, arg, &result, exc, closing) == PYGEN_RETURN) {
267 if (PyAsyncGen_CheckExact(gen)) {
268 assert(result == Py_None);
269 PyErr_SetNone(PyExc_StopAsyncIteration);
270 }
271 else if (result == Py_None) {
272 PyErr_SetNone(PyExc_StopIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -0700273 }
274 else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300275 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200276 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300277 Py_CLEAR(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200278 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200279 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000280}
281
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000282PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283"send(arg) -> send 'arg' into generator,\n\
284return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000285
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300286static PyObject *
287gen_send(PyGenObject *gen, PyObject *arg)
288{
289 return gen_send_ex(gen, arg, 0, 0);
290}
291
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000292PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400293"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000294
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000295/*
296 * This helper function is used by gen_close and gen_throw to
297 * close a subiterator being delegated to by yield-from.
298 */
299
Antoine Pitrou93963562013-05-14 20:37:52 +0200300static int
301gen_close_iter(PyObject *yf)
302{
303 PyObject *retval = NULL;
304 _Py_IDENTIFIER(close);
305
Yury Selivanoveb636452016-09-08 22:01:51 -0700306 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200307 retval = gen_close((PyGenObject *)yf, NULL);
308 if (retval == NULL)
309 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700310 }
311 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200312 PyObject *meth;
313 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
314 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700315 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200316 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700317 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200318 Py_DECREF(meth);
319 if (retval == NULL)
320 return -1;
321 }
322 }
323 Py_XDECREF(retval);
324 return 0;
325}
326
Yury Selivanovc724bae2016-03-02 11:30:46 -0500327PyObject *
328_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500329{
Antoine Pitrou93963562013-05-14 20:37:52 +0200330 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500331 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200332
Mark Shannoncb9879b2020-07-17 11:44:23 +0100333 if (f) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200334 PyObject *bytecode = f->f_code->co_code;
335 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
336
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100337 if (f->f_lasti < 0) {
338 /* Return immediately if the frame didn't start yet. YIELD_FROM
339 always come after LOAD_CONST: a code object should not start
340 with YIELD_FROM */
341 assert(code[0] != YIELD_FROM);
342 return NULL;
343 }
344
Mark Shannonfcb55c02021-04-01 16:00:31 +0100345 if (code[(f->f_lasti+1)*sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200346 return NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100347 assert(f->f_stackdepth > 0);
348 yf = f->f_valuestack[f->f_stackdepth-1];
Antoine Pitrou93963562013-05-14 20:37:52 +0200349 Py_INCREF(yf);
350 }
351
352 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500353}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000354
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000355static PyObject *
356gen_close(PyGenObject *gen, PyObject *args)
357{
Antoine Pitrou93963562013-05-14 20:37:52 +0200358 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500359 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200360 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000361
Antoine Pitrou93963562013-05-14 20:37:52 +0200362 if (yf) {
Mark Shannoncb9879b2020-07-17 11:44:23 +0100363 PyFrameState state = gen->gi_frame->f_state;
364 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200365 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100366 gen->gi_frame->f_state = state;
Antoine Pitrou93963562013-05-14 20:37:52 +0200367 Py_DECREF(yf);
368 }
369 if (err == 0)
370 PyErr_SetNone(PyExc_GeneratorExit);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300371 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200372 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200373 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700374 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400375 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700376 } else if (PyAsyncGen_CheckExact(gen)) {
377 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
378 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200379 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400380 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 return NULL;
382 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200383 if (PyErr_ExceptionMatches(PyExc_StopIteration)
384 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
385 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200386 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200387 }
388 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000389}
390
Antoine Pitrou93963562013-05-14 20:37:52 +0200391
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000392PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
394return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000395
396static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700397_gen_throw(PyGenObject *gen, int close_on_genexit,
398 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000399{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500400 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000401 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000402
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000403 if (yf) {
404 PyObject *ret;
405 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700406 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
407 close_on_genexit
408 ) {
409 /* Asynchronous generators *should not* be closed right away.
410 We have to allow some awaits to work it through, hence the
411 `close_on_genexit` parameter here.
412 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100413 PyFrameState state = gen->gi_frame->f_state;
414 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200415 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100416 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000417 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000418 if (err < 0)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300419 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000420 goto throw_here;
421 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700422 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
423 /* `yf` is a generator or a coroutine. */
Chris Jerdonek8b339612020-07-09 06:27:23 -0700424 PyThreadState *tstate = _PyThreadState_GET();
425 PyFrameObject *f = tstate->frame;
426
Chris Jerdonek8b339612020-07-09 06:27:23 -0700427 /* Since we are fast-tracking things by skipping the eval loop,
428 we need to update the current frame so the stack trace
429 will be reported correctly to the user. */
430 /* XXX We should probably be updating the current frame
431 somewhere in ceval.c. */
432 tstate->frame = gen->gi_frame;
Yury Selivanoveb636452016-09-08 22:01:51 -0700433 /* Close the generator that we are currently iterating with
434 'yield from' or awaiting on with 'await'. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100435 PyFrameState state = gen->gi_frame->f_state;
436 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700437 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
438 typ, val, tb);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100439 gen->gi_frame->f_state = state;
Chris Jerdonek8b339612020-07-09 06:27:23 -0700440 tstate->frame = f;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000441 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700442 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200443 PyObject *meth;
444 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
445 Py_DECREF(yf);
446 return NULL;
447 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000448 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000449 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000450 goto throw_here;
451 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100452 PyFrameState state = gen->gi_frame->f_state;
453 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700454 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100455 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000456 Py_DECREF(meth);
457 }
458 Py_DECREF(yf);
459 if (!ret) {
460 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500461 /* Pop subiterator from stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100462 assert(gen->gi_frame->f_stackdepth > 0);
463 gen->gi_frame->f_stackdepth--;
464 ret = gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth];
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500465 assert(ret == yf);
466 Py_DECREF(ret);
467 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100468 assert(gen->gi_frame->f_lasti >= 0);
Mark Shannonfcb55c02021-04-01 16:00:31 +0100469 gen->gi_frame->f_lasti += 1;
Nick Coghlanc40bc092012-06-17 15:15:49 +1000470 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300471 ret = gen_send(gen, val);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000472 Py_DECREF(val);
473 } else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300474 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000475 }
476 }
477 return ret;
478 }
479
480throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 /* First, check the traceback argument, replacing None with
482 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400483 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 else if (tb != NULL && !PyTraceBack_Check(tb)) {
487 PyErr_SetString(PyExc_TypeError,
488 "throw() third argument must be a traceback object");
489 return NULL;
490 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_INCREF(typ);
493 Py_XINCREF(val);
494 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000495
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400496 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 else if (PyExceptionInstance_Check(typ)) {
500 /* Raising an instance. The value should be a dummy. */
501 if (val && val != Py_None) {
502 PyErr_SetString(PyExc_TypeError,
503 "instance exception may not have a separate value");
504 goto failed_throw;
505 }
506 else {
507 /* Normalize to raise <class>, <instance> */
508 Py_XDECREF(val);
509 val = typ;
510 typ = PyExceptionInstance_Class(typ);
511 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200512
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400513 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200514 /* Returns NULL if there's no traceback */
515 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 }
517 }
518 else {
519 /* Not something you can raise. throw() fails. */
520 PyErr_Format(PyExc_TypeError,
521 "exceptions must be classes or instances "
522 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000523 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 goto failed_throw;
525 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 PyErr_Restore(typ, val, tb);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300528 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000529
530failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* Didn't use our arguments, so restore their original refcounts */
532 Py_DECREF(typ);
533 Py_XDECREF(val);
534 Py_XDECREF(tb);
535 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000536}
537
538
539static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700540gen_throw(PyGenObject *gen, PyObject *args)
541{
542 PyObject *typ;
543 PyObject *tb = NULL;
544 PyObject *val = NULL;
545
546 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
547 return NULL;
548 }
549
550 return _gen_throw(gen, 1, typ, val, tb);
551}
552
553
554static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000555gen_iternext(PyGenObject *gen)
556{
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300557 PyObject *result;
558 assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
559 if (gen_send_ex2(gen, NULL, &result, 0, 0) == PYGEN_RETURN) {
560 if (result != Py_None) {
561 _PyGen_SetStopIterationValue(result);
562 }
563 Py_CLEAR(result);
564 }
565 return result;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000566}
567
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000568/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200569 * Set StopIteration with specified value. Value can be arbitrary object
570 * or NULL.
571 *
572 * Returns 0 if StopIteration is set and -1 if any other exception is set.
573 */
574int
575_PyGen_SetStopIterationValue(PyObject *value)
576{
577 PyObject *e;
578
579 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400580 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200581 {
582 /* Delay exception instantiation if we can */
583 PyErr_SetObject(PyExc_StopIteration, value);
584 return 0;
585 }
586 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100587 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200588 *
589 * We do this to handle a situation when "value" is a tuple, in which
590 * case PyErr_SetObject would set the value of StopIteration to
591 * the first element of the tuple.
592 *
593 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
594 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100595 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200596 if (e == NULL) {
597 return -1;
598 }
599 PyErr_SetObject(PyExc_StopIteration, e);
600 Py_DECREF(e);
601 return 0;
602}
603
604/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000605 * If StopIteration exception is set, fetches its 'value'
606 * attribute if any, otherwise sets pvalue to None.
607 *
608 * Returns 0 if no exception or StopIteration is set.
609 * If any other exception is set, returns -1 and leaves
610 * pvalue unchanged.
611 */
612
613int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200614_PyGen_FetchStopIterationValue(PyObject **pvalue)
615{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000616 PyObject *et, *ev, *tb;
617 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500618
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000619 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
620 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200621 if (ev) {
622 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300623 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200624 value = ((PyStopIterationObject *)ev)->value;
625 Py_INCREF(value);
626 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200627 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
628 /* Avoid normalisation and take ev as value.
629 *
630 * Normalization is required if the value is a tuple, in
631 * that case the value of StopIteration would be set to
632 * the first element of the tuple.
633 *
634 * (See _PyErr_CreateException code for details.)
635 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200636 value = ev;
637 } else {
638 /* normalisation required */
639 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300640 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200641 PyErr_Restore(et, ev, tb);
642 return -1;
643 }
644 value = ((PyStopIterationObject *)ev)->value;
645 Py_INCREF(value);
646 Py_DECREF(ev);
647 }
648 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000649 Py_XDECREF(et);
650 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000651 } else if (PyErr_Occurred()) {
652 return -1;
653 }
654 if (value == NULL) {
655 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100656 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000657 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000658 *pvalue = value;
659 return 0;
660}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000661
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000662static PyObject *
663gen_repr(PyGenObject *gen)
664{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400665 return PyUnicode_FromFormat("<generator object %S at %p>",
666 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000667}
668
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000669static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200670gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000671{
Victor Stinner40ee3012014-06-16 15:59:28 +0200672 Py_INCREF(op->gi_name);
673 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000674}
675
Victor Stinner40ee3012014-06-16 15:59:28 +0200676static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200677gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200678{
Victor Stinner40ee3012014-06-16 15:59:28 +0200679 /* Not legal to del gen.gi_name or to set it to anything
680 * other than a string object. */
681 if (value == NULL || !PyUnicode_Check(value)) {
682 PyErr_SetString(PyExc_TypeError,
683 "__name__ must be set to a string object");
684 return -1;
685 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200686 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300687 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200688 return 0;
689}
690
691static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200692gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200693{
694 Py_INCREF(op->gi_qualname);
695 return op->gi_qualname;
696}
697
698static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200699gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200700{
Victor Stinner40ee3012014-06-16 15:59:28 +0200701 /* Not legal to del gen.__qualname__ or to set it to anything
702 * other than a string object. */
703 if (value == NULL || !PyUnicode_Check(value)) {
704 PyErr_SetString(PyExc_TypeError,
705 "__qualname__ must be set to a string object");
706 return -1;
707 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200708 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300709 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200710 return 0;
711}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000712
Yury Selivanove13f8f32015-07-03 00:23:30 -0400713static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200714gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400715{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500716 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400717 if (yf == NULL)
718 Py_RETURN_NONE;
719 return yf;
720}
721
Mark Shannoncb9879b2020-07-17 11:44:23 +0100722
723static PyObject *
724gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
725{
726 if (gen->gi_frame == NULL) {
727 Py_RETURN_FALSE;
728 }
729 return PyBool_FromLong(_PyFrame_IsExecuting(gen->gi_frame));
730}
731
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000732static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200733 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
734 PyDoc_STR("name of the generator")},
735 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
736 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400737 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
738 PyDoc_STR("object being iterated by yield from, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100739 {"gi_running", (getter)gen_getrunning, NULL, NULL},
Victor Stinner40ee3012014-06-16 15:59:28 +0200740 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000741};
742
Martin v. Löwise440e472004-06-01 15:22:42 +0000743static PyMemberDef gen_memberlist[] = {
Steve Dower87655e22021-04-30 01:08:55 +0100744 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY|PY_AUDIT_READ},
745 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY|PY_AUDIT_READ},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000747};
748
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000749static PyMethodDef gen_methods[] = {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300750 {"send",(PyCFunction)gen_send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
752 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
753 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000754};
755
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800756static PyAsyncMethods gen_as_async = {
757 0, /* am_await */
758 0, /* am_aiter */
759 0, /* am_anext */
760 (sendfunc)PyGen_am_send, /* am_send */
761};
762
763
Martin v. Löwise440e472004-06-01 15:22:42 +0000764PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyVarObject_HEAD_INIT(&PyType_Type, 0)
766 "generator", /* tp_name */
767 sizeof(PyGenObject), /* tp_basicsize */
768 0, /* tp_itemsize */
769 /* methods */
770 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200771 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 0, /* tp_getattr */
773 0, /* tp_setattr */
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800774 &gen_as_async, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 (reprfunc)gen_repr, /* tp_repr */
776 0, /* tp_as_number */
777 0, /* tp_as_sequence */
778 0, /* tp_as_mapping */
779 0, /* tp_hash */
780 0, /* tp_call */
781 0, /* tp_str */
782 PyObject_GenericGetAttr, /* tp_getattro */
783 0, /* tp_setattro */
784 0, /* tp_as_buffer */
Miss Islington (bot)632e8a62021-07-23 07:56:53 -0700785 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 0, /* tp_doc */
787 (traverseproc)gen_traverse, /* tp_traverse */
788 0, /* tp_clear */
789 0, /* tp_richcompare */
790 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400791 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 (iternextfunc)gen_iternext, /* tp_iternext */
793 gen_methods, /* tp_methods */
794 gen_memberlist, /* tp_members */
795 gen_getsetlist, /* tp_getset */
796 0, /* tp_base */
797 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 0, /* tp_descr_get */
800 0, /* tp_descr_set */
801 0, /* tp_dictoffset */
802 0, /* tp_init */
803 0, /* tp_alloc */
804 0, /* tp_new */
805 0, /* tp_free */
806 0, /* tp_is_gc */
807 0, /* tp_bases */
808 0, /* tp_mro */
809 0, /* tp_cache */
810 0, /* tp_subclasses */
811 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200812 0, /* tp_del */
813 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200814 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000815};
816
Yury Selivanov5376ba92015-06-22 12:19:30 -0400817static PyObject *
818gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
819 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000820{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400821 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (gen == NULL) {
823 Py_DECREF(f);
824 return NULL;
825 }
826 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200827 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 Py_INCREF(f->f_code);
829 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100831 gen->gi_exc_state.exc_type = NULL;
832 gen->gi_exc_state.exc_value = NULL;
833 gen->gi_exc_state.exc_traceback = NULL;
834 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200835 if (name != NULL)
836 gen->gi_name = name;
837 else
838 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
839 Py_INCREF(gen->gi_name);
840 if (qualname != NULL)
841 gen->gi_qualname = qualname;
842 else
843 gen->gi_qualname = gen->gi_name;
844 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 _PyObject_GC_TRACK(gen);
846 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000847}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848
Victor Stinner40ee3012014-06-16 15:59:28 +0200849PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400850PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
851{
852 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
853}
854
855PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200856PyGen_New(PyFrameObject *f)
857{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400858 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200859}
860
Yury Selivanov5376ba92015-06-22 12:19:30 -0400861/* Coroutine Object */
862
863typedef struct {
864 PyObject_HEAD
865 PyCoroObject *cw_coroutine;
866} PyCoroWrapper;
867
868static int
869gen_is_coroutine(PyObject *o)
870{
871 if (PyGen_CheckExact(o)) {
872 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
873 if (code->co_flags & CO_ITERABLE_COROUTINE) {
874 return 1;
875 }
876 }
877 return 0;
878}
879
Yury Selivanov75445082015-05-11 22:57:16 -0400880/*
881 * This helper function returns an awaitable for `o`:
882 * - `o` if `o` is a coroutine-object;
883 * - `type(o)->tp_as_async->am_await(o)`
884 *
885 * Raises a TypeError if it's not possible to return
886 * an awaitable and returns NULL.
887 */
888PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400889_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400890{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400891 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400892 PyTypeObject *ot;
893
Yury Selivanov5376ba92015-06-22 12:19:30 -0400894 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
895 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400896 Py_INCREF(o);
897 return o;
898 }
899
900 ot = Py_TYPE(o);
901 if (ot->tp_as_async != NULL) {
902 getter = ot->tp_as_async->am_await;
903 }
904 if (getter != NULL) {
905 PyObject *res = (*getter)(o);
906 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400907 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
908 /* __await__ must return an *iterator*, not
909 a coroutine or another awaitable (see PEP 492) */
910 PyErr_SetString(PyExc_TypeError,
911 "__await__() returned a coroutine");
912 Py_CLEAR(res);
913 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400914 PyErr_Format(PyExc_TypeError,
915 "__await__() returned non-iterator "
916 "of type '%.100s'",
917 Py_TYPE(res)->tp_name);
918 Py_CLEAR(res);
919 }
Yury Selivanov75445082015-05-11 22:57:16 -0400920 }
921 return res;
922 }
923
924 PyErr_Format(PyExc_TypeError,
925 "object %.100s can't be used in 'await' expression",
926 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400927 return NULL;
928}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400929
930static PyObject *
931coro_repr(PyCoroObject *coro)
932{
933 return PyUnicode_FromFormat("<coroutine object %S at %p>",
934 coro->cr_qualname, coro);
935}
936
937static PyObject *
938coro_await(PyCoroObject *coro)
939{
940 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
941 if (cw == NULL) {
942 return NULL;
943 }
944 Py_INCREF(coro);
945 cw->cw_coroutine = coro;
946 _PyObject_GC_TRACK(cw);
947 return (PyObject *)cw;
948}
949
Yury Selivanove13f8f32015-07-03 00:23:30 -0400950static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200951coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400952{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500953 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400954 if (yf == NULL)
955 Py_RETURN_NONE;
956 return yf;
957}
958
Mark Shannoncb9879b2020-07-17 11:44:23 +0100959static PyObject *
960cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
961{
962 if (coro->cr_frame == NULL) {
963 Py_RETURN_FALSE;
964 }
965 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
966}
967
Yury Selivanov5376ba92015-06-22 12:19:30 -0400968static PyGetSetDef coro_getsetlist[] = {
969 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
970 PyDoc_STR("name of the coroutine")},
971 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
972 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400973 {"cr_await", (getter)coro_get_cr_await, NULL,
974 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100975 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400976 {NULL} /* Sentinel */
977};
978
979static PyMemberDef coro_memberlist[] = {
Steve Dower87655e22021-04-30 01:08:55 +0100980 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY|PY_AUDIT_READ},
981 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY|PY_AUDIT_READ},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800982 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400983 {NULL} /* Sentinel */
984};
985
986PyDoc_STRVAR(coro_send_doc,
987"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400988return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400989
990PyDoc_STRVAR(coro_throw_doc,
991"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400992return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400993
994PyDoc_STRVAR(coro_close_doc,
995"close() -> raise GeneratorExit inside coroutine.");
996
997static PyMethodDef coro_methods[] = {
Vladimir Matveev037245c2020-10-09 17:15:15 -0700998 {"send",(PyCFunction)gen_send, METH_O, coro_send_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400999 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1000 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1001 {NULL, NULL} /* Sentinel */
1002};
1003
1004static PyAsyncMethods coro_as_async = {
1005 (unaryfunc)coro_await, /* am_await */
1006 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001007 0, /* am_anext */
1008 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001009};
1010
1011PyTypeObject PyCoro_Type = {
1012 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1013 "coroutine", /* tp_name */
1014 sizeof(PyCoroObject), /* tp_basicsize */
1015 0, /* tp_itemsize */
1016 /* methods */
1017 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001018 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001019 0, /* tp_getattr */
1020 0, /* tp_setattr */
1021 &coro_as_async, /* tp_as_async */
1022 (reprfunc)coro_repr, /* tp_repr */
1023 0, /* tp_as_number */
1024 0, /* tp_as_sequence */
1025 0, /* tp_as_mapping */
1026 0, /* tp_hash */
1027 0, /* tp_call */
1028 0, /* tp_str */
1029 PyObject_GenericGetAttr, /* tp_getattro */
1030 0, /* tp_setattro */
1031 0, /* tp_as_buffer */
Miss Islington (bot)632e8a62021-07-23 07:56:53 -07001032 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001033 0, /* tp_doc */
1034 (traverseproc)gen_traverse, /* tp_traverse */
1035 0, /* tp_clear */
1036 0, /* tp_richcompare */
1037 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1038 0, /* tp_iter */
1039 0, /* tp_iternext */
1040 coro_methods, /* tp_methods */
1041 coro_memberlist, /* tp_members */
1042 coro_getsetlist, /* tp_getset */
1043 0, /* tp_base */
1044 0, /* tp_dict */
1045 0, /* tp_descr_get */
1046 0, /* tp_descr_set */
1047 0, /* tp_dictoffset */
1048 0, /* tp_init */
1049 0, /* tp_alloc */
1050 0, /* tp_new */
1051 0, /* tp_free */
1052 0, /* tp_is_gc */
1053 0, /* tp_bases */
1054 0, /* tp_mro */
1055 0, /* tp_cache */
1056 0, /* tp_subclasses */
1057 0, /* tp_weaklist */
1058 0, /* tp_del */
1059 0, /* tp_version_tag */
1060 _PyGen_Finalize, /* tp_finalize */
1061};
1062
1063static void
1064coro_wrapper_dealloc(PyCoroWrapper *cw)
1065{
1066 _PyObject_GC_UNTRACK((PyObject *)cw);
1067 Py_CLEAR(cw->cw_coroutine);
1068 PyObject_GC_Del(cw);
1069}
1070
1071static PyObject *
1072coro_wrapper_iternext(PyCoroWrapper *cw)
1073{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001074 return gen_iternext((PyGenObject *)cw->cw_coroutine);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001075}
1076
1077static PyObject *
1078coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1079{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001080 return gen_send((PyGenObject *)cw->cw_coroutine, arg);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001081}
1082
1083static PyObject *
1084coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1085{
1086 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1087}
1088
1089static PyObject *
1090coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1091{
1092 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1093}
1094
1095static int
1096coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1097{
1098 Py_VISIT((PyObject *)cw->cw_coroutine);
1099 return 0;
1100}
1101
1102static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001103 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1104 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1105 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001106 {NULL, NULL} /* Sentinel */
1107};
1108
1109PyTypeObject _PyCoroWrapper_Type = {
1110 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1111 "coroutine_wrapper",
1112 sizeof(PyCoroWrapper), /* tp_basicsize */
1113 0, /* tp_itemsize */
1114 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001115 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001116 0, /* tp_getattr */
1117 0, /* tp_setattr */
1118 0, /* tp_as_async */
1119 0, /* tp_repr */
1120 0, /* tp_as_number */
1121 0, /* tp_as_sequence */
1122 0, /* tp_as_mapping */
1123 0, /* tp_hash */
1124 0, /* tp_call */
1125 0, /* tp_str */
1126 PyObject_GenericGetAttr, /* tp_getattro */
1127 0, /* tp_setattro */
1128 0, /* tp_as_buffer */
1129 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1130 "A wrapper object implementing __await__ for coroutines.",
1131 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1132 0, /* tp_clear */
1133 0, /* tp_richcompare */
1134 0, /* tp_weaklistoffset */
1135 PyObject_SelfIter, /* tp_iter */
1136 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1137 coro_wrapper_methods, /* tp_methods */
1138 0, /* tp_members */
1139 0, /* tp_getset */
1140 0, /* tp_base */
1141 0, /* tp_dict */
1142 0, /* tp_descr_get */
1143 0, /* tp_descr_set */
1144 0, /* tp_dictoffset */
1145 0, /* tp_init */
1146 0, /* tp_alloc */
1147 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001148 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001149};
1150
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001151static PyObject *
1152compute_cr_origin(int origin_depth)
1153{
1154 PyFrameObject *frame = PyEval_GetFrame();
1155 /* First count how many frames we have */
1156 int frame_count = 0;
1157 for (; frame && frame_count < origin_depth; ++frame_count) {
1158 frame = frame->f_back;
1159 }
1160
1161 /* Now collect them */
1162 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001163 if (cr_origin == NULL) {
1164 return NULL;
1165 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001166 frame = PyEval_GetFrame();
1167 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001168 PyCodeObject *code = frame->f_code;
1169 PyObject *frameinfo = Py_BuildValue("OiO",
1170 code->co_filename,
1171 PyFrame_GetLineNumber(frame),
1172 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001173 if (!frameinfo) {
1174 Py_DECREF(cr_origin);
1175 return NULL;
1176 }
1177 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1178 frame = frame->f_back;
1179 }
1180
1181 return cr_origin;
1182}
1183
Yury Selivanov5376ba92015-06-22 12:19:30 -04001184PyObject *
1185PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1186{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001187 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1188 if (!coro) {
1189 return NULL;
1190 }
1191
Victor Stinner50b48572018-11-01 01:51:40 +01001192 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001193 int origin_depth = tstate->coroutine_origin_tracking_depth;
1194
1195 if (origin_depth == 0) {
1196 ((PyCoroObject *)coro)->cr_origin = NULL;
1197 } else {
1198 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001199 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001200 if (!cr_origin) {
1201 Py_DECREF(coro);
1202 return NULL;
1203 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001204 }
1205
1206 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001207}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001208
1209
Yury Selivanoveb636452016-09-08 22:01:51 -07001210/* ========= Asynchronous Generators ========= */
1211
1212
1213typedef enum {
1214 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1215 AWAITABLE_STATE_ITER, /* being iterated */
1216 AWAITABLE_STATE_CLOSED, /* closed */
1217} AwaitableState;
1218
1219
Victor Stinner78a02c22020-06-05 02:34:14 +02001220typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001221 PyObject_HEAD
1222 PyAsyncGenObject *ags_gen;
1223
1224 /* Can be NULL, when in the __anext__() mode
1225 (equivalent of "asend(None)") */
1226 PyObject *ags_sendval;
1227
1228 AwaitableState ags_state;
1229} PyAsyncGenASend;
1230
1231
Victor Stinner78a02c22020-06-05 02:34:14 +02001232typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001233 PyObject_HEAD
1234 PyAsyncGenObject *agt_gen;
1235
1236 /* Can be NULL, when in the "aclose()" mode
1237 (equivalent of "athrow(GeneratorExit)") */
1238 PyObject *agt_args;
1239
1240 AwaitableState agt_state;
1241} PyAsyncGenAThrow;
1242
1243
Victor Stinner78a02c22020-06-05 02:34:14 +02001244typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001245 PyObject_HEAD
1246 PyObject *agw_val;
1247} _PyAsyncGenWrappedValue;
1248
1249
Yury Selivanoveb636452016-09-08 22:01:51 -07001250#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001251 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001252
1253#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001254 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001255
1256
1257static int
1258async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1259{
1260 Py_VISIT(gen->ag_finalizer);
1261 return gen_traverse((PyGenObject*)gen, visit, arg);
1262}
1263
1264
1265static PyObject *
1266async_gen_repr(PyAsyncGenObject *o)
1267{
1268 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1269 o->ag_qualname, o);
1270}
1271
1272
1273static int
1274async_gen_init_hooks(PyAsyncGenObject *o)
1275{
1276 PyThreadState *tstate;
1277 PyObject *finalizer;
1278 PyObject *firstiter;
1279
1280 if (o->ag_hooks_inited) {
1281 return 0;
1282 }
1283
1284 o->ag_hooks_inited = 1;
1285
Victor Stinner50b48572018-11-01 01:51:40 +01001286 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001287
1288 finalizer = tstate->async_gen_finalizer;
1289 if (finalizer) {
1290 Py_INCREF(finalizer);
1291 o->ag_finalizer = finalizer;
1292 }
1293
1294 firstiter = tstate->async_gen_firstiter;
1295 if (firstiter) {
1296 PyObject *res;
1297
1298 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001299 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001300 Py_DECREF(firstiter);
1301 if (res == NULL) {
1302 return 1;
1303 }
1304 Py_DECREF(res);
1305 }
1306
1307 return 0;
1308}
1309
1310
1311static PyObject *
1312async_gen_anext(PyAsyncGenObject *o)
1313{
1314 if (async_gen_init_hooks(o)) {
1315 return NULL;
1316 }
1317 return async_gen_asend_new(o, NULL);
1318}
1319
1320
1321static PyObject *
1322async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1323{
1324 if (async_gen_init_hooks(o)) {
1325 return NULL;
1326 }
1327 return async_gen_asend_new(o, arg);
1328}
1329
1330
1331static PyObject *
1332async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1333{
1334 if (async_gen_init_hooks(o)) {
1335 return NULL;
1336 }
1337 return async_gen_athrow_new(o, NULL);
1338}
1339
1340static PyObject *
1341async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1342{
1343 if (async_gen_init_hooks(o)) {
1344 return NULL;
1345 }
1346 return async_gen_athrow_new(o, args);
1347}
1348
1349
1350static PyGetSetDef async_gen_getsetlist[] = {
1351 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1352 PyDoc_STR("name of the async generator")},
1353 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1354 PyDoc_STR("qualified name of the async generator")},
1355 {"ag_await", (getter)coro_get_cr_await, NULL,
1356 PyDoc_STR("object being awaited on, or None")},
1357 {NULL} /* Sentinel */
1358};
1359
1360static PyMemberDef async_gen_memberlist[] = {
Steve Dower87655e22021-04-30 01:08:55 +01001361 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY|PY_AUDIT_READ},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001362 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1363 READONLY},
Steve Dower87655e22021-04-30 01:08:55 +01001364 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY|PY_AUDIT_READ},
Yury Selivanoveb636452016-09-08 22:01:51 -07001365 {NULL} /* Sentinel */
1366};
1367
1368PyDoc_STRVAR(async_aclose_doc,
1369"aclose() -> raise GeneratorExit inside generator.");
1370
1371PyDoc_STRVAR(async_asend_doc,
1372"asend(v) -> send 'v' in generator.");
1373
1374PyDoc_STRVAR(async_athrow_doc,
1375"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1376
1377static PyMethodDef async_gen_methods[] = {
1378 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1379 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1380 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001381 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1382 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001383 {NULL, NULL} /* Sentinel */
1384};
1385
1386
1387static PyAsyncMethods async_gen_as_async = {
1388 0, /* am_await */
1389 PyObject_SelfIter, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001390 (unaryfunc)async_gen_anext, /* am_anext */
1391 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001392};
1393
1394
1395PyTypeObject PyAsyncGen_Type = {
1396 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1397 "async_generator", /* tp_name */
1398 sizeof(PyAsyncGenObject), /* tp_basicsize */
1399 0, /* tp_itemsize */
1400 /* methods */
1401 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001402 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001403 0, /* tp_getattr */
1404 0, /* tp_setattr */
1405 &async_gen_as_async, /* tp_as_async */
1406 (reprfunc)async_gen_repr, /* tp_repr */
1407 0, /* tp_as_number */
1408 0, /* tp_as_sequence */
1409 0, /* tp_as_mapping */
1410 0, /* tp_hash */
1411 0, /* tp_call */
1412 0, /* tp_str */
1413 PyObject_GenericGetAttr, /* tp_getattro */
1414 0, /* tp_setattro */
1415 0, /* tp_as_buffer */
Miss Islington (bot)632e8a62021-07-23 07:56:53 -07001416 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001417 0, /* tp_doc */
1418 (traverseproc)async_gen_traverse, /* tp_traverse */
1419 0, /* tp_clear */
1420 0, /* tp_richcompare */
1421 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1422 0, /* tp_iter */
1423 0, /* tp_iternext */
1424 async_gen_methods, /* tp_methods */
1425 async_gen_memberlist, /* tp_members */
1426 async_gen_getsetlist, /* tp_getset */
1427 0, /* tp_base */
1428 0, /* tp_dict */
1429 0, /* tp_descr_get */
1430 0, /* tp_descr_set */
1431 0, /* tp_dictoffset */
1432 0, /* tp_init */
1433 0, /* tp_alloc */
1434 0, /* tp_new */
1435 0, /* tp_free */
1436 0, /* tp_is_gc */
1437 0, /* tp_bases */
1438 0, /* tp_mro */
1439 0, /* tp_cache */
1440 0, /* tp_subclasses */
1441 0, /* tp_weaklist */
1442 0, /* tp_del */
1443 0, /* tp_version_tag */
1444 _PyGen_Finalize, /* tp_finalize */
1445};
1446
1447
Victor Stinner522691c2020-06-23 16:40:40 +02001448static struct _Py_async_gen_state *
1449get_async_gen_state(void)
1450{
1451 PyInterpreterState *interp = _PyInterpreterState_GET();
1452 return &interp->async_gen;
1453}
1454
1455
Yury Selivanoveb636452016-09-08 22:01:51 -07001456PyObject *
1457PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1458{
1459 PyAsyncGenObject *o;
1460 o = (PyAsyncGenObject *)gen_new_with_qualname(
1461 &PyAsyncGen_Type, f, name, qualname);
1462 if (o == NULL) {
1463 return NULL;
1464 }
1465 o->ag_finalizer = NULL;
1466 o->ag_closed = 0;
1467 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001468 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001469 return (PyObject*)o;
1470}
1471
1472
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001473void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001474_PyAsyncGen_ClearFreeLists(PyInterpreterState *interp)
Yury Selivanoveb636452016-09-08 22:01:51 -07001475{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001476 struct _Py_async_gen_state *state = &interp->async_gen;
Victor Stinner78a02c22020-06-05 02:34:14 +02001477
1478 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001479 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001480 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001481 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001482 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001483 }
1484
Victor Stinner78a02c22020-06-05 02:34:14 +02001485 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001486 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001487 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001488 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001489 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001490 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001491}
1492
1493void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001494_PyAsyncGen_Fini(PyInterpreterState *interp)
Yury Selivanoveb636452016-09-08 22:01:51 -07001495{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001496 _PyAsyncGen_ClearFreeLists(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001497#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001498 struct _Py_async_gen_state *state = &interp->async_gen;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001499 state->value_numfree = -1;
1500 state->asend_numfree = -1;
1501#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001502}
1503
1504
1505static PyObject *
1506async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1507{
1508 if (result == NULL) {
1509 if (!PyErr_Occurred()) {
1510 PyErr_SetNone(PyExc_StopAsyncIteration);
1511 }
1512
1513 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1514 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1515 ) {
1516 gen->ag_closed = 1;
1517 }
1518
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001519 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001520 return NULL;
1521 }
1522
1523 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1524 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001525 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001526 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001527 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001528 return NULL;
1529 }
1530
1531 return result;
1532}
1533
1534
1535/* ---------- Async Generator ASend Awaitable ------------ */
1536
1537
1538static void
1539async_gen_asend_dealloc(PyAsyncGenASend *o)
1540{
Yury Selivanov29310c42016-11-08 19:46:22 -05001541 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001542 Py_CLEAR(o->ags_gen);
1543 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001544 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001545#ifdef Py_DEBUG
1546 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1547 assert(state->asend_numfree != -1);
1548#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001549 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001550 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001551 state->asend_freelist[state->asend_numfree++] = o;
1552 }
1553 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001554 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001555 }
1556}
1557
Yury Selivanov29310c42016-11-08 19:46:22 -05001558static int
1559async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1560{
1561 Py_VISIT(o->ags_gen);
1562 Py_VISIT(o->ags_sendval);
1563 return 0;
1564}
1565
Yury Selivanoveb636452016-09-08 22:01:51 -07001566
1567static PyObject *
1568async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1569{
1570 PyObject *result;
1571
1572 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001573 PyErr_SetString(
1574 PyExc_RuntimeError,
1575 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001576 return NULL;
1577 }
1578
1579 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001580 if (o->ags_gen->ag_running_async) {
1581 PyErr_SetString(
1582 PyExc_RuntimeError,
1583 "anext(): asynchronous generator is already running");
1584 return NULL;
1585 }
1586
Yury Selivanoveb636452016-09-08 22:01:51 -07001587 if (arg == NULL || arg == Py_None) {
1588 arg = o->ags_sendval;
1589 }
1590 o->ags_state = AWAITABLE_STATE_ITER;
1591 }
1592
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001593 o->ags_gen->ag_running_async = 1;
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001594 result = gen_send((PyGenObject*)o->ags_gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001595 result = async_gen_unwrap_value(o->ags_gen, result);
1596
1597 if (result == NULL) {
1598 o->ags_state = AWAITABLE_STATE_CLOSED;
1599 }
1600
1601 return result;
1602}
1603
1604
1605static PyObject *
1606async_gen_asend_iternext(PyAsyncGenASend *o)
1607{
1608 return async_gen_asend_send(o, NULL);
1609}
1610
1611
1612static PyObject *
1613async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1614{
1615 PyObject *result;
1616
1617 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001618 PyErr_SetString(
1619 PyExc_RuntimeError,
1620 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001621 return NULL;
1622 }
1623
1624 result = gen_throw((PyGenObject*)o->ags_gen, args);
1625 result = async_gen_unwrap_value(o->ags_gen, result);
1626
1627 if (result == NULL) {
1628 o->ags_state = AWAITABLE_STATE_CLOSED;
1629 }
1630
1631 return result;
1632}
1633
1634
1635static PyObject *
1636async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1637{
1638 o->ags_state = AWAITABLE_STATE_CLOSED;
1639 Py_RETURN_NONE;
1640}
1641
1642
1643static PyMethodDef async_gen_asend_methods[] = {
1644 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1645 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1646 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1647 {NULL, NULL} /* Sentinel */
1648};
1649
1650
1651static PyAsyncMethods async_gen_asend_as_async = {
1652 PyObject_SelfIter, /* am_await */
1653 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001654 0, /* am_anext */
1655 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001656};
1657
1658
1659PyTypeObject _PyAsyncGenASend_Type = {
1660 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1661 "async_generator_asend", /* tp_name */
1662 sizeof(PyAsyncGenASend), /* tp_basicsize */
1663 0, /* tp_itemsize */
1664 /* methods */
1665 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001666 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001667 0, /* tp_getattr */
1668 0, /* tp_setattr */
1669 &async_gen_asend_as_async, /* tp_as_async */
1670 0, /* tp_repr */
1671 0, /* tp_as_number */
1672 0, /* tp_as_sequence */
1673 0, /* tp_as_mapping */
1674 0, /* tp_hash */
1675 0, /* tp_call */
1676 0, /* tp_str */
1677 PyObject_GenericGetAttr, /* tp_getattro */
1678 0, /* tp_setattro */
1679 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001680 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001681 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001682 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001683 0, /* tp_clear */
1684 0, /* tp_richcompare */
1685 0, /* tp_weaklistoffset */
1686 PyObject_SelfIter, /* tp_iter */
1687 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1688 async_gen_asend_methods, /* tp_methods */
1689 0, /* tp_members */
1690 0, /* tp_getset */
1691 0, /* tp_base */
1692 0, /* tp_dict */
1693 0, /* tp_descr_get */
1694 0, /* tp_descr_set */
1695 0, /* tp_dictoffset */
1696 0, /* tp_init */
1697 0, /* tp_alloc */
1698 0, /* tp_new */
1699};
1700
1701
1702static PyObject *
1703async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1704{
1705 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001706 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001707#ifdef Py_DEBUG
1708 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1709 assert(state->asend_numfree != -1);
1710#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001711 if (state->asend_numfree) {
1712 state->asend_numfree--;
1713 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001714 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001715 }
1716 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001717 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001718 if (o == NULL) {
1719 return NULL;
1720 }
1721 }
1722
1723 Py_INCREF(gen);
1724 o->ags_gen = gen;
1725
1726 Py_XINCREF(sendval);
1727 o->ags_sendval = sendval;
1728
1729 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001730
1731 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001732 return (PyObject*)o;
1733}
1734
1735
1736/* ---------- Async Generator Value Wrapper ------------ */
1737
1738
1739static void
1740async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1741{
Yury Selivanov29310c42016-11-08 19:46:22 -05001742 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001743 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001744 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001745#ifdef Py_DEBUG
1746 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1747 assert(state->value_numfree != -1);
1748#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001749 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001750 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001751 state->value_freelist[state->value_numfree++] = o;
1752 }
1753 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001754 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001755 }
1756}
1757
1758
Yury Selivanov29310c42016-11-08 19:46:22 -05001759static int
1760async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1761 visitproc visit, void *arg)
1762{
1763 Py_VISIT(o->agw_val);
1764 return 0;
1765}
1766
1767
Yury Selivanoveb636452016-09-08 22:01:51 -07001768PyTypeObject _PyAsyncGenWrappedValue_Type = {
1769 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1770 "async_generator_wrapped_value", /* tp_name */
1771 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1772 0, /* tp_itemsize */
1773 /* methods */
1774 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001775 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001776 0, /* tp_getattr */
1777 0, /* tp_setattr */
1778 0, /* tp_as_async */
1779 0, /* tp_repr */
1780 0, /* tp_as_number */
1781 0, /* tp_as_sequence */
1782 0, /* tp_as_mapping */
1783 0, /* tp_hash */
1784 0, /* tp_call */
1785 0, /* tp_str */
1786 PyObject_GenericGetAttr, /* tp_getattro */
1787 0, /* tp_setattro */
1788 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001789 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001790 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001791 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001792 0, /* tp_clear */
1793 0, /* tp_richcompare */
1794 0, /* tp_weaklistoffset */
1795 0, /* tp_iter */
1796 0, /* tp_iternext */
1797 0, /* tp_methods */
1798 0, /* tp_members */
1799 0, /* tp_getset */
1800 0, /* tp_base */
1801 0, /* tp_dict */
1802 0, /* tp_descr_get */
1803 0, /* tp_descr_set */
1804 0, /* tp_dictoffset */
1805 0, /* tp_init */
1806 0, /* tp_alloc */
1807 0, /* tp_new */
1808};
1809
1810
1811PyObject *
1812_PyAsyncGenValueWrapperNew(PyObject *val)
1813{
1814 _PyAsyncGenWrappedValue *o;
1815 assert(val);
1816
Victor Stinner522691c2020-06-23 16:40:40 +02001817 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001818#ifdef Py_DEBUG
1819 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1820 assert(state->value_numfree != -1);
1821#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001822 if (state->value_numfree) {
1823 state->value_numfree--;
1824 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001825 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1826 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001827 }
1828 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001829 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1830 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001831 if (o == NULL) {
1832 return NULL;
1833 }
1834 }
1835 o->agw_val = val;
1836 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001837 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001838 return (PyObject*)o;
1839}
1840
1841
1842/* ---------- Async Generator AThrow awaitable ------------ */
1843
1844
1845static void
1846async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1847{
Yury Selivanov29310c42016-11-08 19:46:22 -05001848 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001849 Py_CLEAR(o->agt_gen);
1850 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001851 PyObject_GC_Del(o);
1852}
1853
1854
1855static int
1856async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1857{
1858 Py_VISIT(o->agt_gen);
1859 Py_VISIT(o->agt_args);
1860 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001861}
1862
1863
1864static PyObject *
1865async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1866{
1867 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1868 PyFrameObject *f = gen->gi_frame;
1869 PyObject *retval;
1870
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001871 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001872 PyErr_SetString(
1873 PyExc_RuntimeError,
1874 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001875 return NULL;
1876 }
1877
Mark Shannoncb9879b2020-07-17 11:44:23 +01001878 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001879 o->agt_state = AWAITABLE_STATE_CLOSED;
1880 PyErr_SetNone(PyExc_StopIteration);
1881 return NULL;
1882 }
1883
Yury Selivanoveb636452016-09-08 22:01:51 -07001884 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001885 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001886 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001887 if (o->agt_args == NULL) {
1888 PyErr_SetString(
1889 PyExc_RuntimeError,
1890 "aclose(): asynchronous generator is already running");
1891 }
1892 else {
1893 PyErr_SetString(
1894 PyExc_RuntimeError,
1895 "athrow(): asynchronous generator is already running");
1896 }
1897 return NULL;
1898 }
1899
Yury Selivanoveb636452016-09-08 22:01:51 -07001900 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001901 o->agt_state = AWAITABLE_STATE_CLOSED;
1902 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001903 return NULL;
1904 }
1905
1906 if (arg != Py_None) {
1907 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1908 return NULL;
1909 }
1910
1911 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001912 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001913
1914 if (o->agt_args == NULL) {
1915 /* aclose() mode */
1916 o->agt_gen->ag_closed = 1;
1917
1918 retval = _gen_throw((PyGenObject *)gen,
1919 0, /* Do not close generator when
1920 PyExc_GeneratorExit is passed */
1921 PyExc_GeneratorExit, NULL, NULL);
1922
1923 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1924 Py_DECREF(retval);
1925 goto yield_close;
1926 }
1927 } else {
1928 PyObject *typ;
1929 PyObject *tb = NULL;
1930 PyObject *val = NULL;
1931
1932 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1933 &typ, &val, &tb)) {
1934 return NULL;
1935 }
1936
1937 retval = _gen_throw((PyGenObject *)gen,
1938 0, /* Do not close generator when
1939 PyExc_GeneratorExit is passed */
1940 typ, val, tb);
1941 retval = async_gen_unwrap_value(o->agt_gen, retval);
1942 }
1943 if (retval == NULL) {
1944 goto check_error;
1945 }
1946 return retval;
1947 }
1948
1949 assert(o->agt_state == AWAITABLE_STATE_ITER);
1950
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001951 retval = gen_send((PyGenObject *)gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001952 if (o->agt_args) {
1953 return async_gen_unwrap_value(o->agt_gen, retval);
1954 } else {
1955 /* aclose() mode */
1956 if (retval) {
1957 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1958 Py_DECREF(retval);
1959 goto yield_close;
1960 }
1961 else {
1962 return retval;
1963 }
1964 }
1965 else {
1966 goto check_error;
1967 }
1968 }
1969
1970yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001971 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001972 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001973 PyErr_SetString(
1974 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1975 return NULL;
1976
1977check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001978 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001979 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001980 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1981 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1982 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001983 if (o->agt_args == NULL) {
1984 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001985 StopAsyncIteration or GeneratorExit; just raise
1986 StopIteration, signalling that this 'aclose()' await
1987 is done.
1988 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001989 PyErr_Clear();
1990 PyErr_SetNone(PyExc_StopIteration);
1991 }
1992 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001993 return NULL;
1994}
1995
1996
1997static PyObject *
1998async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1999{
2000 PyObject *retval;
2001
Yury Selivanoveb636452016-09-08 22:01:51 -07002002 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02002003 PyErr_SetString(
2004 PyExc_RuntimeError,
2005 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07002006 return NULL;
2007 }
2008
2009 retval = gen_throw((PyGenObject*)o->agt_gen, args);
2010 if (o->agt_args) {
2011 return async_gen_unwrap_value(o->agt_gen, retval);
2012 } else {
2013 /* aclose() mode */
2014 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002015 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002016 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07002017 Py_DECREF(retval);
2018 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2019 return NULL;
2020 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08002021 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2022 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2023 {
2024 /* when aclose() is called we don't want to propagate
2025 StopAsyncIteration or GeneratorExit; just raise
2026 StopIteration, signalling that this 'aclose()' await
2027 is done.
2028 */
2029 PyErr_Clear();
2030 PyErr_SetNone(PyExc_StopIteration);
2031 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002032 return retval;
2033 }
2034}
2035
2036
2037static PyObject *
2038async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2039{
2040 return async_gen_athrow_send(o, Py_None);
2041}
2042
2043
2044static PyObject *
2045async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2046{
2047 o->agt_state = AWAITABLE_STATE_CLOSED;
2048 Py_RETURN_NONE;
2049}
2050
2051
2052static PyMethodDef async_gen_athrow_methods[] = {
2053 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2054 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2055 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2056 {NULL, NULL} /* Sentinel */
2057};
2058
2059
2060static PyAsyncMethods async_gen_athrow_as_async = {
2061 PyObject_SelfIter, /* am_await */
2062 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08002063 0, /* am_anext */
2064 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07002065};
2066
2067
2068PyTypeObject _PyAsyncGenAThrow_Type = {
2069 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2070 "async_generator_athrow", /* tp_name */
2071 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2072 0, /* tp_itemsize */
2073 /* methods */
2074 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002075 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002076 0, /* tp_getattr */
2077 0, /* tp_setattr */
2078 &async_gen_athrow_as_async, /* tp_as_async */
2079 0, /* tp_repr */
2080 0, /* tp_as_number */
2081 0, /* tp_as_sequence */
2082 0, /* tp_as_mapping */
2083 0, /* tp_hash */
2084 0, /* tp_call */
2085 0, /* tp_str */
2086 PyObject_GenericGetAttr, /* tp_getattro */
2087 0, /* tp_setattro */
2088 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002089 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002090 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002091 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002092 0, /* tp_clear */
2093 0, /* tp_richcompare */
2094 0, /* tp_weaklistoffset */
2095 PyObject_SelfIter, /* tp_iter */
2096 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2097 async_gen_athrow_methods, /* tp_methods */
2098 0, /* tp_members */
2099 0, /* tp_getset */
2100 0, /* tp_base */
2101 0, /* tp_dict */
2102 0, /* tp_descr_get */
2103 0, /* tp_descr_set */
2104 0, /* tp_dictoffset */
2105 0, /* tp_init */
2106 0, /* tp_alloc */
2107 0, /* tp_new */
2108};
2109
2110
2111static PyObject *
2112async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2113{
2114 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002115 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002116 if (o == NULL) {
2117 return NULL;
2118 }
2119 o->agt_gen = gen;
2120 o->agt_args = args;
2121 o->agt_state = AWAITABLE_STATE_INIT;
2122 Py_INCREF(gen);
2123 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002124 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002125 return (PyObject*)o;
2126}