blob: a922d45de10a090158acda715f2ff4e3aed162bc [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[] = {
Ryan Hileman9a2c2a92021-04-29 16:15:55 -0700744 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY|AUDIT_READ},
745 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY|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 */
Vladimir Matveev1e996c32020-11-10 12:09:55 -0800785 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
786 Py_TPFLAGS_HAVE_AM_SEND, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 0, /* tp_doc */
788 (traverseproc)gen_traverse, /* tp_traverse */
789 0, /* tp_clear */
790 0, /* tp_richcompare */
791 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400792 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 (iternextfunc)gen_iternext, /* tp_iternext */
794 gen_methods, /* tp_methods */
795 gen_memberlist, /* tp_members */
796 gen_getsetlist, /* tp_getset */
797 0, /* tp_base */
798 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 0, /* tp_descr_get */
801 0, /* tp_descr_set */
802 0, /* tp_dictoffset */
803 0, /* tp_init */
804 0, /* tp_alloc */
805 0, /* tp_new */
806 0, /* tp_free */
807 0, /* tp_is_gc */
808 0, /* tp_bases */
809 0, /* tp_mro */
810 0, /* tp_cache */
811 0, /* tp_subclasses */
812 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200813 0, /* tp_del */
814 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200815 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000816};
817
Yury Selivanov5376ba92015-06-22 12:19:30 -0400818static PyObject *
819gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
820 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000821{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400822 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (gen == NULL) {
824 Py_DECREF(f);
825 return NULL;
826 }
827 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200828 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_INCREF(f->f_code);
830 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100832 gen->gi_exc_state.exc_type = NULL;
833 gen->gi_exc_state.exc_value = NULL;
834 gen->gi_exc_state.exc_traceback = NULL;
835 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200836 if (name != NULL)
837 gen->gi_name = name;
838 else
839 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
840 Py_INCREF(gen->gi_name);
841 if (qualname != NULL)
842 gen->gi_qualname = qualname;
843 else
844 gen->gi_qualname = gen->gi_name;
845 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 _PyObject_GC_TRACK(gen);
847 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000848}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000849
Victor Stinner40ee3012014-06-16 15:59:28 +0200850PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400851PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
852{
853 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
854}
855
856PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200857PyGen_New(PyFrameObject *f)
858{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400859 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200860}
861
Yury Selivanov5376ba92015-06-22 12:19:30 -0400862/* Coroutine Object */
863
864typedef struct {
865 PyObject_HEAD
866 PyCoroObject *cw_coroutine;
867} PyCoroWrapper;
868
869static int
870gen_is_coroutine(PyObject *o)
871{
872 if (PyGen_CheckExact(o)) {
873 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
874 if (code->co_flags & CO_ITERABLE_COROUTINE) {
875 return 1;
876 }
877 }
878 return 0;
879}
880
Yury Selivanov75445082015-05-11 22:57:16 -0400881/*
882 * This helper function returns an awaitable for `o`:
883 * - `o` if `o` is a coroutine-object;
884 * - `type(o)->tp_as_async->am_await(o)`
885 *
886 * Raises a TypeError if it's not possible to return
887 * an awaitable and returns NULL.
888 */
889PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400890_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400891{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400892 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400893 PyTypeObject *ot;
894
Yury Selivanov5376ba92015-06-22 12:19:30 -0400895 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
896 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400897 Py_INCREF(o);
898 return o;
899 }
900
901 ot = Py_TYPE(o);
902 if (ot->tp_as_async != NULL) {
903 getter = ot->tp_as_async->am_await;
904 }
905 if (getter != NULL) {
906 PyObject *res = (*getter)(o);
907 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400908 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
909 /* __await__ must return an *iterator*, not
910 a coroutine or another awaitable (see PEP 492) */
911 PyErr_SetString(PyExc_TypeError,
912 "__await__() returned a coroutine");
913 Py_CLEAR(res);
914 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400915 PyErr_Format(PyExc_TypeError,
916 "__await__() returned non-iterator "
917 "of type '%.100s'",
918 Py_TYPE(res)->tp_name);
919 Py_CLEAR(res);
920 }
Yury Selivanov75445082015-05-11 22:57:16 -0400921 }
922 return res;
923 }
924
925 PyErr_Format(PyExc_TypeError,
926 "object %.100s can't be used in 'await' expression",
927 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400928 return NULL;
929}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400930
931static PyObject *
932coro_repr(PyCoroObject *coro)
933{
934 return PyUnicode_FromFormat("<coroutine object %S at %p>",
935 coro->cr_qualname, coro);
936}
937
938static PyObject *
939coro_await(PyCoroObject *coro)
940{
941 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
942 if (cw == NULL) {
943 return NULL;
944 }
945 Py_INCREF(coro);
946 cw->cw_coroutine = coro;
947 _PyObject_GC_TRACK(cw);
948 return (PyObject *)cw;
949}
950
Yury Selivanove13f8f32015-07-03 00:23:30 -0400951static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200952coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400953{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500954 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400955 if (yf == NULL)
956 Py_RETURN_NONE;
957 return yf;
958}
959
Mark Shannoncb9879b2020-07-17 11:44:23 +0100960static PyObject *
961cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
962{
963 if (coro->cr_frame == NULL) {
964 Py_RETURN_FALSE;
965 }
966 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
967}
968
Yury Selivanov5376ba92015-06-22 12:19:30 -0400969static PyGetSetDef coro_getsetlist[] = {
970 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
971 PyDoc_STR("name of the coroutine")},
972 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
973 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400974 {"cr_await", (getter)coro_get_cr_await, NULL,
975 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100976 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400977 {NULL} /* Sentinel */
978};
979
980static PyMemberDef coro_memberlist[] = {
Ryan Hileman9a2c2a92021-04-29 16:15:55 -0700981 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY|AUDIT_READ},
982 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY|AUDIT_READ},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800983 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400984 {NULL} /* Sentinel */
985};
986
987PyDoc_STRVAR(coro_send_doc,
988"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400989return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400990
991PyDoc_STRVAR(coro_throw_doc,
992"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400993return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400994
995PyDoc_STRVAR(coro_close_doc,
996"close() -> raise GeneratorExit inside coroutine.");
997
998static PyMethodDef coro_methods[] = {
Vladimir Matveev037245c2020-10-09 17:15:15 -0700999 {"send",(PyCFunction)gen_send, METH_O, coro_send_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001000 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1001 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1002 {NULL, NULL} /* Sentinel */
1003};
1004
1005static PyAsyncMethods coro_as_async = {
1006 (unaryfunc)coro_await, /* am_await */
1007 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001008 0, /* am_anext */
1009 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001010};
1011
1012PyTypeObject PyCoro_Type = {
1013 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1014 "coroutine", /* tp_name */
1015 sizeof(PyCoroObject), /* tp_basicsize */
1016 0, /* tp_itemsize */
1017 /* methods */
1018 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001019 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001020 0, /* tp_getattr */
1021 0, /* tp_setattr */
1022 &coro_as_async, /* tp_as_async */
1023 (reprfunc)coro_repr, /* tp_repr */
1024 0, /* tp_as_number */
1025 0, /* tp_as_sequence */
1026 0, /* tp_as_mapping */
1027 0, /* tp_hash */
1028 0, /* tp_call */
1029 0, /* tp_str */
1030 PyObject_GenericGetAttr, /* tp_getattro */
1031 0, /* tp_setattro */
1032 0, /* tp_as_buffer */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001033 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1034 Py_TPFLAGS_HAVE_AM_SEND, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001035 0, /* tp_doc */
1036 (traverseproc)gen_traverse, /* tp_traverse */
1037 0, /* tp_clear */
1038 0, /* tp_richcompare */
1039 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1040 0, /* tp_iter */
1041 0, /* tp_iternext */
1042 coro_methods, /* tp_methods */
1043 coro_memberlist, /* tp_members */
1044 coro_getsetlist, /* tp_getset */
1045 0, /* tp_base */
1046 0, /* tp_dict */
1047 0, /* tp_descr_get */
1048 0, /* tp_descr_set */
1049 0, /* tp_dictoffset */
1050 0, /* tp_init */
1051 0, /* tp_alloc */
1052 0, /* tp_new */
1053 0, /* tp_free */
1054 0, /* tp_is_gc */
1055 0, /* tp_bases */
1056 0, /* tp_mro */
1057 0, /* tp_cache */
1058 0, /* tp_subclasses */
1059 0, /* tp_weaklist */
1060 0, /* tp_del */
1061 0, /* tp_version_tag */
1062 _PyGen_Finalize, /* tp_finalize */
1063};
1064
1065static void
1066coro_wrapper_dealloc(PyCoroWrapper *cw)
1067{
1068 _PyObject_GC_UNTRACK((PyObject *)cw);
1069 Py_CLEAR(cw->cw_coroutine);
1070 PyObject_GC_Del(cw);
1071}
1072
1073static PyObject *
1074coro_wrapper_iternext(PyCoroWrapper *cw)
1075{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001076 return gen_iternext((PyGenObject *)cw->cw_coroutine);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001077}
1078
1079static PyObject *
1080coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1081{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001082 return gen_send((PyGenObject *)cw->cw_coroutine, arg);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001083}
1084
1085static PyObject *
1086coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1087{
1088 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1089}
1090
1091static PyObject *
1092coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1093{
1094 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1095}
1096
1097static int
1098coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1099{
1100 Py_VISIT((PyObject *)cw->cw_coroutine);
1101 return 0;
1102}
1103
1104static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001105 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1106 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1107 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001108 {NULL, NULL} /* Sentinel */
1109};
1110
1111PyTypeObject _PyCoroWrapper_Type = {
1112 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1113 "coroutine_wrapper",
1114 sizeof(PyCoroWrapper), /* tp_basicsize */
1115 0, /* tp_itemsize */
1116 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001117 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001118 0, /* tp_getattr */
1119 0, /* tp_setattr */
1120 0, /* tp_as_async */
1121 0, /* tp_repr */
1122 0, /* tp_as_number */
1123 0, /* tp_as_sequence */
1124 0, /* tp_as_mapping */
1125 0, /* tp_hash */
1126 0, /* tp_call */
1127 0, /* tp_str */
1128 PyObject_GenericGetAttr, /* tp_getattro */
1129 0, /* tp_setattro */
1130 0, /* tp_as_buffer */
1131 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1132 "A wrapper object implementing __await__ for coroutines.",
1133 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1134 0, /* tp_clear */
1135 0, /* tp_richcompare */
1136 0, /* tp_weaklistoffset */
1137 PyObject_SelfIter, /* tp_iter */
1138 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1139 coro_wrapper_methods, /* tp_methods */
1140 0, /* tp_members */
1141 0, /* tp_getset */
1142 0, /* tp_base */
1143 0, /* tp_dict */
1144 0, /* tp_descr_get */
1145 0, /* tp_descr_set */
1146 0, /* tp_dictoffset */
1147 0, /* tp_init */
1148 0, /* tp_alloc */
1149 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001150 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001151};
1152
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001153static PyObject *
1154compute_cr_origin(int origin_depth)
1155{
1156 PyFrameObject *frame = PyEval_GetFrame();
1157 /* First count how many frames we have */
1158 int frame_count = 0;
1159 for (; frame && frame_count < origin_depth; ++frame_count) {
1160 frame = frame->f_back;
1161 }
1162
1163 /* Now collect them */
1164 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001165 if (cr_origin == NULL) {
1166 return NULL;
1167 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001168 frame = PyEval_GetFrame();
1169 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001170 PyCodeObject *code = frame->f_code;
1171 PyObject *frameinfo = Py_BuildValue("OiO",
1172 code->co_filename,
1173 PyFrame_GetLineNumber(frame),
1174 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001175 if (!frameinfo) {
1176 Py_DECREF(cr_origin);
1177 return NULL;
1178 }
1179 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1180 frame = frame->f_back;
1181 }
1182
1183 return cr_origin;
1184}
1185
Yury Selivanov5376ba92015-06-22 12:19:30 -04001186PyObject *
1187PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1188{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001189 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1190 if (!coro) {
1191 return NULL;
1192 }
1193
Victor Stinner50b48572018-11-01 01:51:40 +01001194 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001195 int origin_depth = tstate->coroutine_origin_tracking_depth;
1196
1197 if (origin_depth == 0) {
1198 ((PyCoroObject *)coro)->cr_origin = NULL;
1199 } else {
1200 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001201 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001202 if (!cr_origin) {
1203 Py_DECREF(coro);
1204 return NULL;
1205 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001206 }
1207
1208 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001209}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001210
1211
Yury Selivanoveb636452016-09-08 22:01:51 -07001212/* ========= Asynchronous Generators ========= */
1213
1214
1215typedef enum {
1216 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1217 AWAITABLE_STATE_ITER, /* being iterated */
1218 AWAITABLE_STATE_CLOSED, /* closed */
1219} AwaitableState;
1220
1221
Victor Stinner78a02c22020-06-05 02:34:14 +02001222typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001223 PyObject_HEAD
1224 PyAsyncGenObject *ags_gen;
1225
1226 /* Can be NULL, when in the __anext__() mode
1227 (equivalent of "asend(None)") */
1228 PyObject *ags_sendval;
1229
1230 AwaitableState ags_state;
1231} PyAsyncGenASend;
1232
1233
Victor Stinner78a02c22020-06-05 02:34:14 +02001234typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001235 PyObject_HEAD
1236 PyAsyncGenObject *agt_gen;
1237
1238 /* Can be NULL, when in the "aclose()" mode
1239 (equivalent of "athrow(GeneratorExit)") */
1240 PyObject *agt_args;
1241
1242 AwaitableState agt_state;
1243} PyAsyncGenAThrow;
1244
1245
Victor Stinner78a02c22020-06-05 02:34:14 +02001246typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001247 PyObject_HEAD
1248 PyObject *agw_val;
1249} _PyAsyncGenWrappedValue;
1250
1251
Yury Selivanoveb636452016-09-08 22:01:51 -07001252#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001253 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001254
1255#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001256 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001257
1258
1259static int
1260async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1261{
1262 Py_VISIT(gen->ag_finalizer);
1263 return gen_traverse((PyGenObject*)gen, visit, arg);
1264}
1265
1266
1267static PyObject *
1268async_gen_repr(PyAsyncGenObject *o)
1269{
1270 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1271 o->ag_qualname, o);
1272}
1273
1274
1275static int
1276async_gen_init_hooks(PyAsyncGenObject *o)
1277{
1278 PyThreadState *tstate;
1279 PyObject *finalizer;
1280 PyObject *firstiter;
1281
1282 if (o->ag_hooks_inited) {
1283 return 0;
1284 }
1285
1286 o->ag_hooks_inited = 1;
1287
Victor Stinner50b48572018-11-01 01:51:40 +01001288 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001289
1290 finalizer = tstate->async_gen_finalizer;
1291 if (finalizer) {
1292 Py_INCREF(finalizer);
1293 o->ag_finalizer = finalizer;
1294 }
1295
1296 firstiter = tstate->async_gen_firstiter;
1297 if (firstiter) {
1298 PyObject *res;
1299
1300 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001301 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001302 Py_DECREF(firstiter);
1303 if (res == NULL) {
1304 return 1;
1305 }
1306 Py_DECREF(res);
1307 }
1308
1309 return 0;
1310}
1311
1312
1313static PyObject *
1314async_gen_anext(PyAsyncGenObject *o)
1315{
1316 if (async_gen_init_hooks(o)) {
1317 return NULL;
1318 }
1319 return async_gen_asend_new(o, NULL);
1320}
1321
1322
1323static PyObject *
1324async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1325{
1326 if (async_gen_init_hooks(o)) {
1327 return NULL;
1328 }
1329 return async_gen_asend_new(o, arg);
1330}
1331
1332
1333static PyObject *
1334async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1335{
1336 if (async_gen_init_hooks(o)) {
1337 return NULL;
1338 }
1339 return async_gen_athrow_new(o, NULL);
1340}
1341
1342static PyObject *
1343async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1344{
1345 if (async_gen_init_hooks(o)) {
1346 return NULL;
1347 }
1348 return async_gen_athrow_new(o, args);
1349}
1350
1351
1352static PyGetSetDef async_gen_getsetlist[] = {
1353 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1354 PyDoc_STR("name of the async generator")},
1355 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1356 PyDoc_STR("qualified name of the async generator")},
1357 {"ag_await", (getter)coro_get_cr_await, NULL,
1358 PyDoc_STR("object being awaited on, or None")},
1359 {NULL} /* Sentinel */
1360};
1361
1362static PyMemberDef async_gen_memberlist[] = {
Ryan Hileman9a2c2a92021-04-29 16:15:55 -07001363 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY|AUDIT_READ},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001364 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1365 READONLY},
Ryan Hileman9a2c2a92021-04-29 16:15:55 -07001366 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY|AUDIT_READ},
Yury Selivanoveb636452016-09-08 22:01:51 -07001367 {NULL} /* Sentinel */
1368};
1369
1370PyDoc_STRVAR(async_aclose_doc,
1371"aclose() -> raise GeneratorExit inside generator.");
1372
1373PyDoc_STRVAR(async_asend_doc,
1374"asend(v) -> send 'v' in generator.");
1375
1376PyDoc_STRVAR(async_athrow_doc,
1377"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1378
1379static PyMethodDef async_gen_methods[] = {
1380 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1381 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1382 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001383 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1384 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001385 {NULL, NULL} /* Sentinel */
1386};
1387
1388
1389static PyAsyncMethods async_gen_as_async = {
1390 0, /* am_await */
1391 PyObject_SelfIter, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001392 (unaryfunc)async_gen_anext, /* am_anext */
1393 (sendfunc)PyGen_am_send, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001394};
1395
1396
1397PyTypeObject PyAsyncGen_Type = {
1398 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1399 "async_generator", /* tp_name */
1400 sizeof(PyAsyncGenObject), /* tp_basicsize */
1401 0, /* tp_itemsize */
1402 /* methods */
1403 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001404 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001405 0, /* tp_getattr */
1406 0, /* tp_setattr */
1407 &async_gen_as_async, /* tp_as_async */
1408 (reprfunc)async_gen_repr, /* tp_repr */
1409 0, /* tp_as_number */
1410 0, /* tp_as_sequence */
1411 0, /* tp_as_mapping */
1412 0, /* tp_hash */
1413 0, /* tp_call */
1414 0, /* tp_str */
1415 PyObject_GenericGetAttr, /* tp_getattro */
1416 0, /* tp_setattro */
1417 0, /* tp_as_buffer */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001418 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1419 Py_TPFLAGS_HAVE_AM_SEND, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001420 0, /* tp_doc */
1421 (traverseproc)async_gen_traverse, /* tp_traverse */
1422 0, /* tp_clear */
1423 0, /* tp_richcompare */
1424 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1425 0, /* tp_iter */
1426 0, /* tp_iternext */
1427 async_gen_methods, /* tp_methods */
1428 async_gen_memberlist, /* tp_members */
1429 async_gen_getsetlist, /* tp_getset */
1430 0, /* tp_base */
1431 0, /* tp_dict */
1432 0, /* tp_descr_get */
1433 0, /* tp_descr_set */
1434 0, /* tp_dictoffset */
1435 0, /* tp_init */
1436 0, /* tp_alloc */
1437 0, /* tp_new */
1438 0, /* tp_free */
1439 0, /* tp_is_gc */
1440 0, /* tp_bases */
1441 0, /* tp_mro */
1442 0, /* tp_cache */
1443 0, /* tp_subclasses */
1444 0, /* tp_weaklist */
1445 0, /* tp_del */
1446 0, /* tp_version_tag */
1447 _PyGen_Finalize, /* tp_finalize */
1448};
1449
1450
Victor Stinner522691c2020-06-23 16:40:40 +02001451static struct _Py_async_gen_state *
1452get_async_gen_state(void)
1453{
1454 PyInterpreterState *interp = _PyInterpreterState_GET();
1455 return &interp->async_gen;
1456}
1457
1458
Yury Selivanoveb636452016-09-08 22:01:51 -07001459PyObject *
1460PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1461{
1462 PyAsyncGenObject *o;
1463 o = (PyAsyncGenObject *)gen_new_with_qualname(
1464 &PyAsyncGen_Type, f, name, qualname);
1465 if (o == NULL) {
1466 return NULL;
1467 }
1468 o->ag_finalizer = NULL;
1469 o->ag_closed = 0;
1470 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001471 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001472 return (PyObject*)o;
1473}
1474
1475
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001476void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001477_PyAsyncGen_ClearFreeLists(PyInterpreterState *interp)
Yury Selivanoveb636452016-09-08 22:01:51 -07001478{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001479 struct _Py_async_gen_state *state = &interp->async_gen;
Victor Stinner78a02c22020-06-05 02:34:14 +02001480
1481 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001482 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001483 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001484 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001485 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001486 }
1487
Victor Stinner78a02c22020-06-05 02:34:14 +02001488 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001489 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001490 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001491 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001492 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001493 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001494}
1495
1496void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001497_PyAsyncGen_Fini(PyInterpreterState *interp)
Yury Selivanoveb636452016-09-08 22:01:51 -07001498{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001499 _PyAsyncGen_ClearFreeLists(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001500#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001501 struct _Py_async_gen_state *state = &interp->async_gen;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001502 state->value_numfree = -1;
1503 state->asend_numfree = -1;
1504#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001505}
1506
1507
1508static PyObject *
1509async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1510{
1511 if (result == NULL) {
1512 if (!PyErr_Occurred()) {
1513 PyErr_SetNone(PyExc_StopAsyncIteration);
1514 }
1515
1516 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1517 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1518 ) {
1519 gen->ag_closed = 1;
1520 }
1521
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001522 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001523 return NULL;
1524 }
1525
1526 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1527 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001528 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001529 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001530 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001531 return NULL;
1532 }
1533
1534 return result;
1535}
1536
1537
1538/* ---------- Async Generator ASend Awaitable ------------ */
1539
1540
1541static void
1542async_gen_asend_dealloc(PyAsyncGenASend *o)
1543{
Yury Selivanov29310c42016-11-08 19:46:22 -05001544 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001545 Py_CLEAR(o->ags_gen);
1546 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001547 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001548#ifdef Py_DEBUG
1549 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1550 assert(state->asend_numfree != -1);
1551#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001552 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001553 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001554 state->asend_freelist[state->asend_numfree++] = o;
1555 }
1556 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001557 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001558 }
1559}
1560
Yury Selivanov29310c42016-11-08 19:46:22 -05001561static int
1562async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1563{
1564 Py_VISIT(o->ags_gen);
1565 Py_VISIT(o->ags_sendval);
1566 return 0;
1567}
1568
Yury Selivanoveb636452016-09-08 22:01:51 -07001569
1570static PyObject *
1571async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1572{
1573 PyObject *result;
1574
1575 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001576 PyErr_SetString(
1577 PyExc_RuntimeError,
1578 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001579 return NULL;
1580 }
1581
1582 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001583 if (o->ags_gen->ag_running_async) {
1584 PyErr_SetString(
1585 PyExc_RuntimeError,
1586 "anext(): asynchronous generator is already running");
1587 return NULL;
1588 }
1589
Yury Selivanoveb636452016-09-08 22:01:51 -07001590 if (arg == NULL || arg == Py_None) {
1591 arg = o->ags_sendval;
1592 }
1593 o->ags_state = AWAITABLE_STATE_ITER;
1594 }
1595
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001596 o->ags_gen->ag_running_async = 1;
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001597 result = gen_send((PyGenObject*)o->ags_gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001598 result = async_gen_unwrap_value(o->ags_gen, result);
1599
1600 if (result == NULL) {
1601 o->ags_state = AWAITABLE_STATE_CLOSED;
1602 }
1603
1604 return result;
1605}
1606
1607
1608static PyObject *
1609async_gen_asend_iternext(PyAsyncGenASend *o)
1610{
1611 return async_gen_asend_send(o, NULL);
1612}
1613
1614
1615static PyObject *
1616async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1617{
1618 PyObject *result;
1619
1620 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001621 PyErr_SetString(
1622 PyExc_RuntimeError,
1623 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001624 return NULL;
1625 }
1626
1627 result = gen_throw((PyGenObject*)o->ags_gen, args);
1628 result = async_gen_unwrap_value(o->ags_gen, result);
1629
1630 if (result == NULL) {
1631 o->ags_state = AWAITABLE_STATE_CLOSED;
1632 }
1633
1634 return result;
1635}
1636
1637
1638static PyObject *
1639async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1640{
1641 o->ags_state = AWAITABLE_STATE_CLOSED;
1642 Py_RETURN_NONE;
1643}
1644
1645
1646static PyMethodDef async_gen_asend_methods[] = {
1647 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1648 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1649 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1650 {NULL, NULL} /* Sentinel */
1651};
1652
1653
1654static PyAsyncMethods async_gen_asend_as_async = {
1655 PyObject_SelfIter, /* am_await */
1656 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08001657 0, /* am_anext */
1658 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07001659};
1660
1661
1662PyTypeObject _PyAsyncGenASend_Type = {
1663 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1664 "async_generator_asend", /* tp_name */
1665 sizeof(PyAsyncGenASend), /* tp_basicsize */
1666 0, /* tp_itemsize */
1667 /* methods */
1668 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001669 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001670 0, /* tp_getattr */
1671 0, /* tp_setattr */
1672 &async_gen_asend_as_async, /* tp_as_async */
1673 0, /* tp_repr */
1674 0, /* tp_as_number */
1675 0, /* tp_as_sequence */
1676 0, /* tp_as_mapping */
1677 0, /* tp_hash */
1678 0, /* tp_call */
1679 0, /* tp_str */
1680 PyObject_GenericGetAttr, /* tp_getattro */
1681 0, /* tp_setattro */
1682 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001683 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001684 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001685 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001686 0, /* tp_clear */
1687 0, /* tp_richcompare */
1688 0, /* tp_weaklistoffset */
1689 PyObject_SelfIter, /* tp_iter */
1690 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1691 async_gen_asend_methods, /* tp_methods */
1692 0, /* tp_members */
1693 0, /* tp_getset */
1694 0, /* tp_base */
1695 0, /* tp_dict */
1696 0, /* tp_descr_get */
1697 0, /* tp_descr_set */
1698 0, /* tp_dictoffset */
1699 0, /* tp_init */
1700 0, /* tp_alloc */
1701 0, /* tp_new */
1702};
1703
1704
1705static PyObject *
1706async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1707{
1708 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001709 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001710#ifdef Py_DEBUG
1711 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1712 assert(state->asend_numfree != -1);
1713#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001714 if (state->asend_numfree) {
1715 state->asend_numfree--;
1716 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001717 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001718 }
1719 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001720 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001721 if (o == NULL) {
1722 return NULL;
1723 }
1724 }
1725
1726 Py_INCREF(gen);
1727 o->ags_gen = gen;
1728
1729 Py_XINCREF(sendval);
1730 o->ags_sendval = sendval;
1731
1732 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001733
1734 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001735 return (PyObject*)o;
1736}
1737
1738
1739/* ---------- Async Generator Value Wrapper ------------ */
1740
1741
1742static void
1743async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1744{
Yury Selivanov29310c42016-11-08 19:46:22 -05001745 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001746 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001747 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001748#ifdef Py_DEBUG
1749 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1750 assert(state->value_numfree != -1);
1751#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001752 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001753 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001754 state->value_freelist[state->value_numfree++] = o;
1755 }
1756 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001757 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001758 }
1759}
1760
1761
Yury Selivanov29310c42016-11-08 19:46:22 -05001762static int
1763async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1764 visitproc visit, void *arg)
1765{
1766 Py_VISIT(o->agw_val);
1767 return 0;
1768}
1769
1770
Yury Selivanoveb636452016-09-08 22:01:51 -07001771PyTypeObject _PyAsyncGenWrappedValue_Type = {
1772 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1773 "async_generator_wrapped_value", /* tp_name */
1774 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1775 0, /* tp_itemsize */
1776 /* methods */
1777 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001778 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001779 0, /* tp_getattr */
1780 0, /* tp_setattr */
1781 0, /* tp_as_async */
1782 0, /* tp_repr */
1783 0, /* tp_as_number */
1784 0, /* tp_as_sequence */
1785 0, /* tp_as_mapping */
1786 0, /* tp_hash */
1787 0, /* tp_call */
1788 0, /* tp_str */
1789 PyObject_GenericGetAttr, /* tp_getattro */
1790 0, /* tp_setattro */
1791 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001792 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001793 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001794 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001795 0, /* tp_clear */
1796 0, /* tp_richcompare */
1797 0, /* tp_weaklistoffset */
1798 0, /* tp_iter */
1799 0, /* tp_iternext */
1800 0, /* tp_methods */
1801 0, /* tp_members */
1802 0, /* tp_getset */
1803 0, /* tp_base */
1804 0, /* tp_dict */
1805 0, /* tp_descr_get */
1806 0, /* tp_descr_set */
1807 0, /* tp_dictoffset */
1808 0, /* tp_init */
1809 0, /* tp_alloc */
1810 0, /* tp_new */
1811};
1812
1813
1814PyObject *
1815_PyAsyncGenValueWrapperNew(PyObject *val)
1816{
1817 _PyAsyncGenWrappedValue *o;
1818 assert(val);
1819
Victor Stinner522691c2020-06-23 16:40:40 +02001820 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001821#ifdef Py_DEBUG
1822 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1823 assert(state->value_numfree != -1);
1824#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001825 if (state->value_numfree) {
1826 state->value_numfree--;
1827 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001828 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1829 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001830 }
1831 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001832 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1833 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001834 if (o == NULL) {
1835 return NULL;
1836 }
1837 }
1838 o->agw_val = val;
1839 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001840 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001841 return (PyObject*)o;
1842}
1843
1844
1845/* ---------- Async Generator AThrow awaitable ------------ */
1846
1847
1848static void
1849async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1850{
Yury Selivanov29310c42016-11-08 19:46:22 -05001851 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001852 Py_CLEAR(o->agt_gen);
1853 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001854 PyObject_GC_Del(o);
1855}
1856
1857
1858static int
1859async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1860{
1861 Py_VISIT(o->agt_gen);
1862 Py_VISIT(o->agt_args);
1863 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001864}
1865
1866
1867static PyObject *
1868async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1869{
1870 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1871 PyFrameObject *f = gen->gi_frame;
1872 PyObject *retval;
1873
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001874 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001875 PyErr_SetString(
1876 PyExc_RuntimeError,
1877 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001878 return NULL;
1879 }
1880
Mark Shannoncb9879b2020-07-17 11:44:23 +01001881 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001882 o->agt_state = AWAITABLE_STATE_CLOSED;
1883 PyErr_SetNone(PyExc_StopIteration);
1884 return NULL;
1885 }
1886
Yury Selivanoveb636452016-09-08 22:01:51 -07001887 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001888 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001889 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001890 if (o->agt_args == NULL) {
1891 PyErr_SetString(
1892 PyExc_RuntimeError,
1893 "aclose(): asynchronous generator is already running");
1894 }
1895 else {
1896 PyErr_SetString(
1897 PyExc_RuntimeError,
1898 "athrow(): asynchronous generator is already running");
1899 }
1900 return NULL;
1901 }
1902
Yury Selivanoveb636452016-09-08 22:01:51 -07001903 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001904 o->agt_state = AWAITABLE_STATE_CLOSED;
1905 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001906 return NULL;
1907 }
1908
1909 if (arg != Py_None) {
1910 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1911 return NULL;
1912 }
1913
1914 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001915 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001916
1917 if (o->agt_args == NULL) {
1918 /* aclose() mode */
1919 o->agt_gen->ag_closed = 1;
1920
1921 retval = _gen_throw((PyGenObject *)gen,
1922 0, /* Do not close generator when
1923 PyExc_GeneratorExit is passed */
1924 PyExc_GeneratorExit, NULL, NULL);
1925
1926 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1927 Py_DECREF(retval);
1928 goto yield_close;
1929 }
1930 } else {
1931 PyObject *typ;
1932 PyObject *tb = NULL;
1933 PyObject *val = NULL;
1934
1935 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1936 &typ, &val, &tb)) {
1937 return NULL;
1938 }
1939
1940 retval = _gen_throw((PyGenObject *)gen,
1941 0, /* Do not close generator when
1942 PyExc_GeneratorExit is passed */
1943 typ, val, tb);
1944 retval = async_gen_unwrap_value(o->agt_gen, retval);
1945 }
1946 if (retval == NULL) {
1947 goto check_error;
1948 }
1949 return retval;
1950 }
1951
1952 assert(o->agt_state == AWAITABLE_STATE_ITER);
1953
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001954 retval = gen_send((PyGenObject *)gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001955 if (o->agt_args) {
1956 return async_gen_unwrap_value(o->agt_gen, retval);
1957 } else {
1958 /* aclose() mode */
1959 if (retval) {
1960 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1961 Py_DECREF(retval);
1962 goto yield_close;
1963 }
1964 else {
1965 return retval;
1966 }
1967 }
1968 else {
1969 goto check_error;
1970 }
1971 }
1972
1973yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001974 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001975 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001976 PyErr_SetString(
1977 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1978 return NULL;
1979
1980check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001981 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001982 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001983 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1984 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1985 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001986 if (o->agt_args == NULL) {
1987 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001988 StopAsyncIteration or GeneratorExit; just raise
1989 StopIteration, signalling that this 'aclose()' await
1990 is done.
1991 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001992 PyErr_Clear();
1993 PyErr_SetNone(PyExc_StopIteration);
1994 }
1995 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001996 return NULL;
1997}
1998
1999
2000static PyObject *
2001async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
2002{
2003 PyObject *retval;
2004
Yury Selivanoveb636452016-09-08 22:01:51 -07002005 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02002006 PyErr_SetString(
2007 PyExc_RuntimeError,
2008 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07002009 return NULL;
2010 }
2011
2012 retval = gen_throw((PyGenObject*)o->agt_gen, args);
2013 if (o->agt_args) {
2014 return async_gen_unwrap_value(o->agt_gen, retval);
2015 } else {
2016 /* aclose() mode */
2017 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002018 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002019 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07002020 Py_DECREF(retval);
2021 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2022 return NULL;
2023 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08002024 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2025 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2026 {
2027 /* when aclose() is called we don't want to propagate
2028 StopAsyncIteration or GeneratorExit; just raise
2029 StopIteration, signalling that this 'aclose()' await
2030 is done.
2031 */
2032 PyErr_Clear();
2033 PyErr_SetNone(PyExc_StopIteration);
2034 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002035 return retval;
2036 }
2037}
2038
2039
2040static PyObject *
2041async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2042{
2043 return async_gen_athrow_send(o, Py_None);
2044}
2045
2046
2047static PyObject *
2048async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2049{
2050 o->agt_state = AWAITABLE_STATE_CLOSED;
2051 Py_RETURN_NONE;
2052}
2053
2054
2055static PyMethodDef async_gen_athrow_methods[] = {
2056 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2057 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2058 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2059 {NULL, NULL} /* Sentinel */
2060};
2061
2062
2063static PyAsyncMethods async_gen_athrow_as_async = {
2064 PyObject_SelfIter, /* am_await */
2065 0, /* am_aiter */
Vladimir Matveev1e996c32020-11-10 12:09:55 -08002066 0, /* am_anext */
2067 0, /* am_send */
Yury Selivanoveb636452016-09-08 22:01:51 -07002068};
2069
2070
2071PyTypeObject _PyAsyncGenAThrow_Type = {
2072 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2073 "async_generator_athrow", /* tp_name */
2074 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2075 0, /* tp_itemsize */
2076 /* methods */
2077 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002078 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002079 0, /* tp_getattr */
2080 0, /* tp_setattr */
2081 &async_gen_athrow_as_async, /* tp_as_async */
2082 0, /* tp_repr */
2083 0, /* tp_as_number */
2084 0, /* tp_as_sequence */
2085 0, /* tp_as_mapping */
2086 0, /* tp_hash */
2087 0, /* tp_call */
2088 0, /* tp_str */
2089 PyObject_GenericGetAttr, /* tp_getattro */
2090 0, /* tp_setattro */
2091 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002092 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002093 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002094 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002095 0, /* tp_clear */
2096 0, /* tp_richcompare */
2097 0, /* tp_weaklistoffset */
2098 PyObject_SelfIter, /* tp_iter */
2099 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2100 async_gen_athrow_methods, /* tp_methods */
2101 0, /* tp_members */
2102 0, /* tp_getset */
2103 0, /* tp_base */
2104 0, /* tp_dict */
2105 0, /* tp_descr_get */
2106 0, /* tp_descr_set */
2107 0, /* tp_dictoffset */
2108 0, /* tp_init */
2109 0, /* tp_alloc */
2110 0, /* tp_new */
2111};
2112
2113
2114static PyObject *
2115async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2116{
2117 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002118 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002119 if (o == NULL) {
2120 return NULL;
2121 }
2122 o->agt_gen = gen;
2123 o->agt_args = args;
2124 o->agt_state = AWAITABLE_STATE_INIT;
2125 Py_INCREF(gen);
2126 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002127 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002128 return (PyObject*)o;
2129}