blob: 40179cdbf7dbd2011f58877e148057a53dd39fa9 [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02004#include "pycore_ceval.h" // _PyEval_EvalFrame()
Victor Stinnerbcda8f12018-11-21 22:27:47 +01005#include "pycore_object.h"
Chris Jerdonekda742ba2020-05-17 22:47:31 -07006#include "pycore_pyerrors.h" // _PyErr_ClearExcState()
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include "pycore_pystate.h" // _PyThreadState_GET()
Martin v. Löwise440e472004-06-01 15:22:42 +00008#include "frameobject.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02009#include "structmember.h" // PyMemberDef
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +000011
Yury Selivanoveb636452016-09-08 22:01:51 -070012static PyObject *gen_close(PyGenObject *, PyObject *);
13static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
14static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
15
Andy Lester7386a702020-02-13 22:42:56 -060016static const char *NON_INIT_CORO_MSG = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -070017 "just-started coroutine";
18
Andy Lester7386a702020-02-13 22:42:56 -060019static const char *ASYNC_GEN_IGNORED_EXIT_MSG =
Yury Selivanoveb636452016-09-08 22:01:51 -070020 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100021
Mark Shannonae3087c2017-10-22 22:41:51 +010022static inline int
23exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
24{
25 Py_VISIT(exc_state->exc_type);
26 Py_VISIT(exc_state->exc_value);
27 Py_VISIT(exc_state->exc_traceback);
28 return 0;
29}
30
Martin v. Löwise440e472004-06-01 15:22:42 +000031static int
32gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
33{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_VISIT((PyObject *)gen->gi_frame);
35 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020036 Py_VISIT(gen->gi_name);
37 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080038 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
39 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010040 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000041}
42
Antoine Pitrou58720d62013-08-05 23:26:40 +020043void
44_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020045{
46 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070047 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020048 PyObject *error_type, *error_value, *error_traceback;
49
Yury Selivanov2a2270d2018-01-29 14:31:47 -050050 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) {
Antoine Pitrou796564c2013-07-30 19:59:21 +020051 /* Generator isn't paused, so no need to close */
52 return;
Yury Selivanov2a2270d2018-01-29 14:31:47 -050053 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020054
Yury Selivanoveb636452016-09-08 22:01:51 -070055 if (PyAsyncGen_CheckExact(self)) {
56 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
57 PyObject *finalizer = agen->ag_finalizer;
58 if (finalizer && !agen->ag_closed) {
59 /* Save the current exception, if any. */
60 PyErr_Fetch(&error_type, &error_value, &error_traceback);
61
Petr Viktorinffd97532020-02-11 17:46:57 +010062 res = PyObject_CallOneArg(finalizer, self);
Yury Selivanoveb636452016-09-08 22:01:51 -070063
64 if (res == NULL) {
65 PyErr_WriteUnraisable(self);
66 } else {
67 Py_DECREF(res);
68 }
69 /* Restore the saved exception. */
70 PyErr_Restore(error_type, error_value, error_traceback);
71 return;
72 }
73 }
74
Antoine Pitrou796564c2013-07-30 19:59:21 +020075 /* Save the current exception, if any. */
76 PyErr_Fetch(&error_type, &error_value, &error_traceback);
77
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070078 /* If `gen` is a coroutine, and if it was never awaited on,
79 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070080 if (gen->gi_code != NULL &&
81 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
Yury Selivanov2a2270d2018-01-29 14:31:47 -050082 gen->gi_frame->f_lasti == -1)
83 {
84 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070085 }
86 else {
87 res = gen_close(gen, NULL);
88 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020089
Benjamin Petersonb88db872016-09-07 08:46:59 -070090 if (res == NULL) {
Yury Selivanov2a2270d2018-01-29 14:31:47 -050091 if (PyErr_Occurred()) {
Benjamin Petersonb88db872016-09-07 08:46:59 -070092 PyErr_WriteUnraisable(self);
Yury Selivanov2a2270d2018-01-29 14:31:47 -050093 }
Benjamin Petersonb88db872016-09-07 08:46:59 -070094 }
95 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020096 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070097 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020098
99 /* Restore the saved exception. */
100 PyErr_Restore(error_type, error_value, error_traceback);
101}
102
103static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000104gen_dealloc(PyGenObject *gen)
105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (gen->gi_weakreflist != NULL)
111 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000112
Antoine Pitrou93963562013-05-14 20:37:52 +0200113 _PyObject_GC_TRACK(self);
114
Antoine Pitrou796564c2013-07-30 19:59:21 +0200115 if (PyObject_CallFinalizerFromDealloc(self))
116 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200117
118 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700119 if (PyAsyncGen_CheckExact(gen)) {
120 /* We have to handle this case for asynchronous generators
121 right here, because this code has to be between UNTRACK
122 and GC_Del. */
123 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
124 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700125 if (gen->gi_frame != NULL) {
126 gen->gi_frame->f_gen = NULL;
127 Py_CLEAR(gen->gi_frame);
128 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800129 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
130 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200133 Py_CLEAR(gen->gi_name);
134 Py_CLEAR(gen->gi_qualname);
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700135 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000137}
138
139static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500140gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000141{
Victor Stinner50b48572018-11-01 01:51:40 +0100142 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200144 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000145
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500146 if (gen->gi_running) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200147 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700148 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400149 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700150 }
151 else if (PyAsyncGen_CheckExact(gen)) {
152 msg = "async generator already executing";
153 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400154 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500155 return NULL;
156 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200157 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500158 if (PyCoro_CheckExact(gen) && !closing) {
159 /* `gen` is an exhausted coroutine: raise an error,
160 except when called from gen_close(), which should
161 always be a silent method. */
162 PyErr_SetString(
163 PyExc_RuntimeError,
164 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700165 }
166 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500167 /* `gen` is an exhausted generator:
168 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700169 if (PyAsyncGen_CheckExact(gen)) {
170 PyErr_SetNone(PyExc_StopAsyncIteration);
171 }
172 else {
173 PyErr_SetNone(PyExc_StopIteration);
174 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return NULL;
177 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000178
Antoine Pitrou93963562013-05-14 20:37:52 +0200179 if (f->f_lasti == -1) {
180 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200181 const char *msg = "can't send non-None value to a "
182 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700183 if (PyCoro_CheckExact(gen)) {
184 msg = NON_INIT_CORO_MSG;
185 }
186 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400187 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700188 "just-started async generator";
189 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400190 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200191 return NULL;
192 }
193 } else {
194 /* Push arg onto the frame's value stack */
195 result = arg ? arg : Py_None;
196 Py_INCREF(result);
197 *(f->f_stacktop++) = result;
198 }
199
200 /* Generators always return to their most recent caller, not
201 * necessarily their creator. */
202 Py_XINCREF(tstate->frame);
203 assert(f->f_back == NULL);
204 f->f_back = tstate->frame;
205
Chris Jerdonek75cd8e42020-05-13 16:18:27 -0700206 _PyErr_StackItem *gi_exc_state = &gen->gi_exc_state;
207 if (exc && gi_exc_state->exc_type != NULL &&
208 gi_exc_state->exc_type != Py_None)
209 {
210 Py_INCREF(gi_exc_state->exc_type);
211 Py_XINCREF(gi_exc_state->exc_value);
212 Py_XINCREF(gi_exc_state->exc_traceback);
213 _PyErr_ChainExceptions(gi_exc_state->exc_type,
214 gi_exc_state->exc_value,
215 gi_exc_state->exc_traceback);
216 }
217
Antoine Pitrou93963562013-05-14 20:37:52 +0200218 gen->gi_running = 1;
Mark Shannonae3087c2017-10-22 22:41:51 +0100219 gen->gi_exc_state.previous_item = tstate->exc_info;
220 tstate->exc_info = &gen->gi_exc_state;
Victor Stinnerb9e68122019-11-14 12:20:46 +0100221 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100222 tstate->exc_info = gen->gi_exc_state.previous_item;
223 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200224 gen->gi_running = 0;
225
226 /* Don't keep the reference to f_back any longer than necessary. It
227 * may keep a chain of frames alive or it could create a reference
228 * cycle. */
229 assert(f->f_back == tstate->frame);
230 Py_CLEAR(f->f_back);
231
232 /* If the generator just returned (as opposed to yielding), signal
233 * that the generator is exhausted. */
234 if (result && f->f_stacktop == NULL) {
235 if (result == Py_None) {
236 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700237 if (PyAsyncGen_CheckExact(gen)) {
238 PyErr_SetNone(PyExc_StopAsyncIteration);
239 }
240 else {
241 PyErr_SetNone(PyExc_StopIteration);
242 }
243 }
244 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700245 /* Async generators cannot return anything but None */
246 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200247 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200248 }
249 Py_CLEAR(result);
250 }
Yury Selivanov68333392015-05-22 11:16:47 -0400251 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500252 const char *msg = "generator raised StopIteration";
253 if (PyCoro_CheckExact(gen)) {
254 msg = "coroutine raised StopIteration";
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400255 }
Dong-hee Nad905df72020-02-14 02:37:17 +0900256 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500257 msg = "async generator raised StopIteration";
Yury Selivanov68333392015-05-22 11:16:47 -0400258 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500259 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
260
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400261 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500262 else if (!result && PyAsyncGen_CheckExact(gen) &&
Yury Selivanoveb636452016-09-08 22:01:51 -0700263 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
264 {
265 /* code in `gen` raised a StopAsyncIteration error:
266 raise a RuntimeError.
267 */
268 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300269 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700270 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200271
272 if (!result || f->f_stacktop == NULL) {
273 /* generator can't be rerun, so release the frame */
274 /* first clean reference cycle through stored exception traceback */
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700275 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200276 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200277 gen->gi_frame = NULL;
278 Py_DECREF(f);
279 }
280
281 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000282}
283
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000284PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000285"send(arg) -> send 'arg' into generator,\n\
286return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000287
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500288PyObject *
289_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000290{
Yury Selivanov77c96812016-02-13 17:59:05 -0500291 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000292}
293
294PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400295"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000296
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000297/*
298 * This helper function is used by gen_close and gen_throw to
299 * close a subiterator being delegated to by yield-from.
300 */
301
Antoine Pitrou93963562013-05-14 20:37:52 +0200302static int
303gen_close_iter(PyObject *yf)
304{
305 PyObject *retval = NULL;
306 _Py_IDENTIFIER(close);
307
Yury Selivanoveb636452016-09-08 22:01:51 -0700308 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200309 retval = gen_close((PyGenObject *)yf, NULL);
310 if (retval == NULL)
311 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700312 }
313 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200314 PyObject *meth;
315 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
316 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700317 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200318 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700319 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200320 Py_DECREF(meth);
321 if (retval == NULL)
322 return -1;
323 }
324 }
325 Py_XDECREF(retval);
326 return 0;
327}
328
Yury Selivanovc724bae2016-03-02 11:30:46 -0500329PyObject *
330_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500331{
Antoine Pitrou93963562013-05-14 20:37:52 +0200332 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500333 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200334
335 if (f && f->f_stacktop) {
336 PyObject *bytecode = f->f_code->co_code;
337 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
338
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100339 if (f->f_lasti < 0) {
340 /* Return immediately if the frame didn't start yet. YIELD_FROM
341 always come after LOAD_CONST: a code object should not start
342 with YIELD_FROM */
343 assert(code[0] != YIELD_FROM);
344 return NULL;
345 }
346
Serhiy Storchakaab874002016-09-11 13:48:15 +0300347 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200348 return NULL;
349 yf = f->f_stacktop[-1];
350 Py_INCREF(yf);
351 }
352
353 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500354}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000355
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000356static PyObject *
357gen_close(PyGenObject *gen, PyObject *args)
358{
Antoine Pitrou93963562013-05-14 20:37:52 +0200359 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500360 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200361 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000362
Antoine Pitrou93963562013-05-14 20:37:52 +0200363 if (yf) {
364 gen->gi_running = 1;
365 err = gen_close_iter(yf);
366 gen->gi_running = 0;
367 Py_DECREF(yf);
368 }
369 if (err == 0)
370 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500371 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 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500413 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200414 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500415 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000416 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000417 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500418 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000419 goto throw_here;
420 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700421 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
422 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500423 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700424 /* Close the generator that we are currently iterating with
425 'yield from' or awaiting on with 'await'. */
426 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
427 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500428 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000429 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700430 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200431 PyObject *meth;
432 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
433 Py_DECREF(yf);
434 return NULL;
435 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000436 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000437 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 goto throw_here;
439 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500440 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700441 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500442 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000443 Py_DECREF(meth);
444 }
445 Py_DECREF(yf);
446 if (!ret) {
447 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500448 /* Pop subiterator from stack */
449 ret = *(--gen->gi_frame->f_stacktop);
450 assert(ret == yf);
451 Py_DECREF(ret);
452 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100453 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300454 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000455 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500456 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000457 Py_DECREF(val);
458 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500459 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000460 }
461 }
462 return ret;
463 }
464
465throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 /* First, check the traceback argument, replacing None with
467 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400468 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400470 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 else if (tb != NULL && !PyTraceBack_Check(tb)) {
472 PyErr_SetString(PyExc_TypeError,
473 "throw() third argument must be a traceback object");
474 return NULL;
475 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 Py_INCREF(typ);
478 Py_XINCREF(val);
479 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000480
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400481 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 else if (PyExceptionInstance_Check(typ)) {
485 /* Raising an instance. The value should be a dummy. */
486 if (val && val != Py_None) {
487 PyErr_SetString(PyExc_TypeError,
488 "instance exception may not have a separate value");
489 goto failed_throw;
490 }
491 else {
492 /* Normalize to raise <class>, <instance> */
493 Py_XDECREF(val);
494 val = typ;
495 typ = PyExceptionInstance_Class(typ);
496 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200497
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400498 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200499 /* Returns NULL if there's no traceback */
500 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 }
502 }
503 else {
504 /* Not something you can raise. throw() fails. */
505 PyErr_Format(PyExc_TypeError,
506 "exceptions must be classes or instances "
507 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000508 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 goto failed_throw;
510 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500513 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000514
515failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* Didn't use our arguments, so restore their original refcounts */
517 Py_DECREF(typ);
518 Py_XDECREF(val);
519 Py_XDECREF(tb);
520 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000521}
522
523
524static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700525gen_throw(PyGenObject *gen, PyObject *args)
526{
527 PyObject *typ;
528 PyObject *tb = NULL;
529 PyObject *val = NULL;
530
531 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
532 return NULL;
533 }
534
535 return _gen_throw(gen, 1, typ, val, tb);
536}
537
538
539static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000540gen_iternext(PyGenObject *gen)
541{
Yury Selivanov77c96812016-02-13 17:59:05 -0500542 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000543}
544
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000545/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200546 * Set StopIteration with specified value. Value can be arbitrary object
547 * or NULL.
548 *
549 * Returns 0 if StopIteration is set and -1 if any other exception is set.
550 */
551int
552_PyGen_SetStopIterationValue(PyObject *value)
553{
554 PyObject *e;
555
556 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400557 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200558 {
559 /* Delay exception instantiation if we can */
560 PyErr_SetObject(PyExc_StopIteration, value);
561 return 0;
562 }
563 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100564 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200565 *
566 * We do this to handle a situation when "value" is a tuple, in which
567 * case PyErr_SetObject would set the value of StopIteration to
568 * the first element of the tuple.
569 *
570 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
571 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100572 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200573 if (e == NULL) {
574 return -1;
575 }
576 PyErr_SetObject(PyExc_StopIteration, e);
577 Py_DECREF(e);
578 return 0;
579}
580
581/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000582 * If StopIteration exception is set, fetches its 'value'
583 * attribute if any, otherwise sets pvalue to None.
584 *
585 * Returns 0 if no exception or StopIteration is set.
586 * If any other exception is set, returns -1 and leaves
587 * pvalue unchanged.
588 */
589
590int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200591_PyGen_FetchStopIterationValue(PyObject **pvalue)
592{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000593 PyObject *et, *ev, *tb;
594 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500595
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000596 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
597 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200598 if (ev) {
599 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300600 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200601 value = ((PyStopIterationObject *)ev)->value;
602 Py_INCREF(value);
603 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200604 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
605 /* Avoid normalisation and take ev as value.
606 *
607 * Normalization is required if the value is a tuple, in
608 * that case the value of StopIteration would be set to
609 * the first element of the tuple.
610 *
611 * (See _PyErr_CreateException code for details.)
612 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200613 value = ev;
614 } else {
615 /* normalisation required */
616 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300617 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200618 PyErr_Restore(et, ev, tb);
619 return -1;
620 }
621 value = ((PyStopIterationObject *)ev)->value;
622 Py_INCREF(value);
623 Py_DECREF(ev);
624 }
625 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000626 Py_XDECREF(et);
627 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000628 } else if (PyErr_Occurred()) {
629 return -1;
630 }
631 if (value == NULL) {
632 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100633 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000634 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000635 *pvalue = value;
636 return 0;
637}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000638
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000639static PyObject *
640gen_repr(PyGenObject *gen)
641{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400642 return PyUnicode_FromFormat("<generator object %S at %p>",
643 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000644}
645
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000646static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200647gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000648{
Victor Stinner40ee3012014-06-16 15:59:28 +0200649 Py_INCREF(op->gi_name);
650 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000651}
652
Victor Stinner40ee3012014-06-16 15:59:28 +0200653static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200654gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200655{
Victor Stinner40ee3012014-06-16 15:59:28 +0200656 /* Not legal to del gen.gi_name or to set it to anything
657 * other than a string object. */
658 if (value == NULL || !PyUnicode_Check(value)) {
659 PyErr_SetString(PyExc_TypeError,
660 "__name__ must be set to a string object");
661 return -1;
662 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200663 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300664 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200665 return 0;
666}
667
668static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200669gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200670{
671 Py_INCREF(op->gi_qualname);
672 return op->gi_qualname;
673}
674
675static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200676gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200677{
Victor Stinner40ee3012014-06-16 15:59:28 +0200678 /* Not legal to del gen.__qualname__ or to set it to anything
679 * other than a string object. */
680 if (value == NULL || !PyUnicode_Check(value)) {
681 PyErr_SetString(PyExc_TypeError,
682 "__qualname__ must be set to a string object");
683 return -1;
684 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200685 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300686 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200687 return 0;
688}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000689
Yury Selivanove13f8f32015-07-03 00:23:30 -0400690static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200691gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400692{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500693 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400694 if (yf == NULL)
695 Py_RETURN_NONE;
696 return yf;
697}
698
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000699static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200700 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
701 PyDoc_STR("name of the generator")},
702 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
703 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400704 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
705 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200706 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000707};
708
Martin v. Löwise440e472004-06-01 15:22:42 +0000709static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200710 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
711 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
712 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000714};
715
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000716static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500717 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
719 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
720 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000721};
722
Martin v. Löwise440e472004-06-01 15:22:42 +0000723PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyVarObject_HEAD_INIT(&PyType_Type, 0)
725 "generator", /* tp_name */
726 sizeof(PyGenObject), /* tp_basicsize */
727 0, /* tp_itemsize */
728 /* methods */
729 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200730 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 0, /* tp_getattr */
732 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400733 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 (reprfunc)gen_repr, /* tp_repr */
735 0, /* tp_as_number */
736 0, /* tp_as_sequence */
737 0, /* tp_as_mapping */
738 0, /* tp_hash */
739 0, /* tp_call */
740 0, /* tp_str */
741 PyObject_GenericGetAttr, /* tp_getattro */
742 0, /* tp_setattro */
743 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200744 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 0, /* tp_doc */
746 (traverseproc)gen_traverse, /* tp_traverse */
747 0, /* tp_clear */
748 0, /* tp_richcompare */
749 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400750 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 (iternextfunc)gen_iternext, /* tp_iternext */
752 gen_methods, /* tp_methods */
753 gen_memberlist, /* tp_members */
754 gen_getsetlist, /* tp_getset */
755 0, /* tp_base */
756 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 0, /* tp_descr_get */
759 0, /* tp_descr_set */
760 0, /* tp_dictoffset */
761 0, /* tp_init */
762 0, /* tp_alloc */
763 0, /* tp_new */
764 0, /* tp_free */
765 0, /* tp_is_gc */
766 0, /* tp_bases */
767 0, /* tp_mro */
768 0, /* tp_cache */
769 0, /* tp_subclasses */
770 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200771 0, /* tp_del */
772 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200773 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000774};
775
Yury Selivanov5376ba92015-06-22 12:19:30 -0400776static PyObject *
777gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
778 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000779{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400780 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (gen == NULL) {
782 Py_DECREF(f);
783 return NULL;
784 }
785 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200786 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_INCREF(f->f_code);
788 gen->gi_code = (PyObject *)(f->f_code);
789 gen->gi_running = 0;
790 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100791 gen->gi_exc_state.exc_type = NULL;
792 gen->gi_exc_state.exc_value = NULL;
793 gen->gi_exc_state.exc_traceback = NULL;
794 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200795 if (name != NULL)
796 gen->gi_name = name;
797 else
798 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
799 Py_INCREF(gen->gi_name);
800 if (qualname != NULL)
801 gen->gi_qualname = qualname;
802 else
803 gen->gi_qualname = gen->gi_name;
804 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 _PyObject_GC_TRACK(gen);
806 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000807}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000808
Victor Stinner40ee3012014-06-16 15:59:28 +0200809PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400810PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
811{
812 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
813}
814
815PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200816PyGen_New(PyFrameObject *f)
817{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400818 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200819}
820
Yury Selivanov5376ba92015-06-22 12:19:30 -0400821/* Coroutine Object */
822
823typedef struct {
824 PyObject_HEAD
825 PyCoroObject *cw_coroutine;
826} PyCoroWrapper;
827
828static int
829gen_is_coroutine(PyObject *o)
830{
831 if (PyGen_CheckExact(o)) {
832 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
833 if (code->co_flags & CO_ITERABLE_COROUTINE) {
834 return 1;
835 }
836 }
837 return 0;
838}
839
Yury Selivanov75445082015-05-11 22:57:16 -0400840/*
841 * This helper function returns an awaitable for `o`:
842 * - `o` if `o` is a coroutine-object;
843 * - `type(o)->tp_as_async->am_await(o)`
844 *
845 * Raises a TypeError if it's not possible to return
846 * an awaitable and returns NULL.
847 */
848PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400849_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400850{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400851 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400852 PyTypeObject *ot;
853
Yury Selivanov5376ba92015-06-22 12:19:30 -0400854 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
855 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400856 Py_INCREF(o);
857 return o;
858 }
859
860 ot = Py_TYPE(o);
861 if (ot->tp_as_async != NULL) {
862 getter = ot->tp_as_async->am_await;
863 }
864 if (getter != NULL) {
865 PyObject *res = (*getter)(o);
866 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400867 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
868 /* __await__ must return an *iterator*, not
869 a coroutine or another awaitable (see PEP 492) */
870 PyErr_SetString(PyExc_TypeError,
871 "__await__() returned a coroutine");
872 Py_CLEAR(res);
873 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400874 PyErr_Format(PyExc_TypeError,
875 "__await__() returned non-iterator "
876 "of type '%.100s'",
877 Py_TYPE(res)->tp_name);
878 Py_CLEAR(res);
879 }
Yury Selivanov75445082015-05-11 22:57:16 -0400880 }
881 return res;
882 }
883
884 PyErr_Format(PyExc_TypeError,
885 "object %.100s can't be used in 'await' expression",
886 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400887 return NULL;
888}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400889
890static PyObject *
891coro_repr(PyCoroObject *coro)
892{
893 return PyUnicode_FromFormat("<coroutine object %S at %p>",
894 coro->cr_qualname, coro);
895}
896
897static PyObject *
898coro_await(PyCoroObject *coro)
899{
900 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
901 if (cw == NULL) {
902 return NULL;
903 }
904 Py_INCREF(coro);
905 cw->cw_coroutine = coro;
906 _PyObject_GC_TRACK(cw);
907 return (PyObject *)cw;
908}
909
Yury Selivanove13f8f32015-07-03 00:23:30 -0400910static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200911coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400912{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500913 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400914 if (yf == NULL)
915 Py_RETURN_NONE;
916 return yf;
917}
918
Yury Selivanov5376ba92015-06-22 12:19:30 -0400919static PyGetSetDef coro_getsetlist[] = {
920 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
921 PyDoc_STR("name of the coroutine")},
922 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
923 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400924 {"cr_await", (getter)coro_get_cr_await, NULL,
925 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400926 {NULL} /* Sentinel */
927};
928
929static PyMemberDef coro_memberlist[] = {
930 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
931 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
932 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800933 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400934 {NULL} /* Sentinel */
935};
936
937PyDoc_STRVAR(coro_send_doc,
938"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400939return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400940
941PyDoc_STRVAR(coro_throw_doc,
942"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400943return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400944
945PyDoc_STRVAR(coro_close_doc,
946"close() -> raise GeneratorExit inside coroutine.");
947
948static PyMethodDef coro_methods[] = {
949 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
950 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
951 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
952 {NULL, NULL} /* Sentinel */
953};
954
955static PyAsyncMethods coro_as_async = {
956 (unaryfunc)coro_await, /* am_await */
957 0, /* am_aiter */
958 0 /* am_anext */
959};
960
961PyTypeObject PyCoro_Type = {
962 PyVarObject_HEAD_INIT(&PyType_Type, 0)
963 "coroutine", /* tp_name */
964 sizeof(PyCoroObject), /* tp_basicsize */
965 0, /* tp_itemsize */
966 /* methods */
967 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200968 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400969 0, /* tp_getattr */
970 0, /* tp_setattr */
971 &coro_as_async, /* tp_as_async */
972 (reprfunc)coro_repr, /* tp_repr */
973 0, /* tp_as_number */
974 0, /* tp_as_sequence */
975 0, /* tp_as_mapping */
976 0, /* tp_hash */
977 0, /* tp_call */
978 0, /* tp_str */
979 PyObject_GenericGetAttr, /* tp_getattro */
980 0, /* tp_setattro */
981 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200982 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400983 0, /* tp_doc */
984 (traverseproc)gen_traverse, /* tp_traverse */
985 0, /* tp_clear */
986 0, /* tp_richcompare */
987 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
988 0, /* tp_iter */
989 0, /* tp_iternext */
990 coro_methods, /* tp_methods */
991 coro_memberlist, /* tp_members */
992 coro_getsetlist, /* tp_getset */
993 0, /* tp_base */
994 0, /* tp_dict */
995 0, /* tp_descr_get */
996 0, /* tp_descr_set */
997 0, /* tp_dictoffset */
998 0, /* tp_init */
999 0, /* tp_alloc */
1000 0, /* tp_new */
1001 0, /* tp_free */
1002 0, /* tp_is_gc */
1003 0, /* tp_bases */
1004 0, /* tp_mro */
1005 0, /* tp_cache */
1006 0, /* tp_subclasses */
1007 0, /* tp_weaklist */
1008 0, /* tp_del */
1009 0, /* tp_version_tag */
1010 _PyGen_Finalize, /* tp_finalize */
1011};
1012
1013static void
1014coro_wrapper_dealloc(PyCoroWrapper *cw)
1015{
1016 _PyObject_GC_UNTRACK((PyObject *)cw);
1017 Py_CLEAR(cw->cw_coroutine);
1018 PyObject_GC_Del(cw);
1019}
1020
1021static PyObject *
1022coro_wrapper_iternext(PyCoroWrapper *cw)
1023{
Yury Selivanov77c96812016-02-13 17:59:05 -05001024 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001025}
1026
1027static PyObject *
1028coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1029{
Yury Selivanov77c96812016-02-13 17:59:05 -05001030 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001031}
1032
1033static PyObject *
1034coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1035{
1036 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1037}
1038
1039static PyObject *
1040coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1041{
1042 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1043}
1044
1045static int
1046coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1047{
1048 Py_VISIT((PyObject *)cw->cw_coroutine);
1049 return 0;
1050}
1051
1052static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001053 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1054 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1055 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001056 {NULL, NULL} /* Sentinel */
1057};
1058
1059PyTypeObject _PyCoroWrapper_Type = {
1060 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1061 "coroutine_wrapper",
1062 sizeof(PyCoroWrapper), /* tp_basicsize */
1063 0, /* tp_itemsize */
1064 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001065 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001066 0, /* tp_getattr */
1067 0, /* tp_setattr */
1068 0, /* tp_as_async */
1069 0, /* tp_repr */
1070 0, /* tp_as_number */
1071 0, /* tp_as_sequence */
1072 0, /* tp_as_mapping */
1073 0, /* tp_hash */
1074 0, /* tp_call */
1075 0, /* tp_str */
1076 PyObject_GenericGetAttr, /* tp_getattro */
1077 0, /* tp_setattro */
1078 0, /* tp_as_buffer */
1079 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1080 "A wrapper object implementing __await__ for coroutines.",
1081 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1082 0, /* tp_clear */
1083 0, /* tp_richcompare */
1084 0, /* tp_weaklistoffset */
1085 PyObject_SelfIter, /* tp_iter */
1086 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1087 coro_wrapper_methods, /* tp_methods */
1088 0, /* tp_members */
1089 0, /* tp_getset */
1090 0, /* tp_base */
1091 0, /* tp_dict */
1092 0, /* tp_descr_get */
1093 0, /* tp_descr_set */
1094 0, /* tp_dictoffset */
1095 0, /* tp_init */
1096 0, /* tp_alloc */
1097 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001098 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001099};
1100
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001101static PyObject *
1102compute_cr_origin(int origin_depth)
1103{
1104 PyFrameObject *frame = PyEval_GetFrame();
1105 /* First count how many frames we have */
1106 int frame_count = 0;
1107 for (; frame && frame_count < origin_depth; ++frame_count) {
1108 frame = frame->f_back;
1109 }
1110
1111 /* Now collect them */
1112 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001113 if (cr_origin == NULL) {
1114 return NULL;
1115 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001116 frame = PyEval_GetFrame();
1117 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001118 PyCodeObject *code = frame->f_code;
1119 PyObject *frameinfo = Py_BuildValue("OiO",
1120 code->co_filename,
1121 PyFrame_GetLineNumber(frame),
1122 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001123 if (!frameinfo) {
1124 Py_DECREF(cr_origin);
1125 return NULL;
1126 }
1127 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1128 frame = frame->f_back;
1129 }
1130
1131 return cr_origin;
1132}
1133
Yury Selivanov5376ba92015-06-22 12:19:30 -04001134PyObject *
1135PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1136{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001137 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1138 if (!coro) {
1139 return NULL;
1140 }
1141
Victor Stinner50b48572018-11-01 01:51:40 +01001142 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001143 int origin_depth = tstate->coroutine_origin_tracking_depth;
1144
1145 if (origin_depth == 0) {
1146 ((PyCoroObject *)coro)->cr_origin = NULL;
1147 } else {
1148 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001149 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001150 if (!cr_origin) {
1151 Py_DECREF(coro);
1152 return NULL;
1153 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001154 }
1155
1156 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001157}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001158
1159
Yury Selivanoveb636452016-09-08 22:01:51 -07001160/* ========= Asynchronous Generators ========= */
1161
1162
1163typedef enum {
1164 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1165 AWAITABLE_STATE_ITER, /* being iterated */
1166 AWAITABLE_STATE_CLOSED, /* closed */
1167} AwaitableState;
1168
1169
1170typedef struct {
1171 PyObject_HEAD
1172 PyAsyncGenObject *ags_gen;
1173
1174 /* Can be NULL, when in the __anext__() mode
1175 (equivalent of "asend(None)") */
1176 PyObject *ags_sendval;
1177
1178 AwaitableState ags_state;
1179} PyAsyncGenASend;
1180
1181
1182typedef struct {
1183 PyObject_HEAD
1184 PyAsyncGenObject *agt_gen;
1185
1186 /* Can be NULL, when in the "aclose()" mode
1187 (equivalent of "athrow(GeneratorExit)") */
1188 PyObject *agt_args;
1189
1190 AwaitableState agt_state;
1191} PyAsyncGenAThrow;
1192
1193
1194typedef struct {
1195 PyObject_HEAD
1196 PyObject *agw_val;
1197} _PyAsyncGenWrappedValue;
1198
1199
1200#ifndef _PyAsyncGen_MAXFREELIST
1201#define _PyAsyncGen_MAXFREELIST 80
1202#endif
1203
1204/* Freelists boost performance 6-10%; they also reduce memory
1205 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1206 are short-living objects that are instantiated for every
1207 __anext__ call.
1208*/
1209
1210static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1211static int ag_value_freelist_free = 0;
1212
1213static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1214static int ag_asend_freelist_free = 0;
1215
1216#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001217 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001218
1219#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001220 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001221
1222
1223static int
1224async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1225{
1226 Py_VISIT(gen->ag_finalizer);
1227 return gen_traverse((PyGenObject*)gen, visit, arg);
1228}
1229
1230
1231static PyObject *
1232async_gen_repr(PyAsyncGenObject *o)
1233{
1234 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1235 o->ag_qualname, o);
1236}
1237
1238
1239static int
1240async_gen_init_hooks(PyAsyncGenObject *o)
1241{
1242 PyThreadState *tstate;
1243 PyObject *finalizer;
1244 PyObject *firstiter;
1245
1246 if (o->ag_hooks_inited) {
1247 return 0;
1248 }
1249
1250 o->ag_hooks_inited = 1;
1251
Victor Stinner50b48572018-11-01 01:51:40 +01001252 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001253
1254 finalizer = tstate->async_gen_finalizer;
1255 if (finalizer) {
1256 Py_INCREF(finalizer);
1257 o->ag_finalizer = finalizer;
1258 }
1259
1260 firstiter = tstate->async_gen_firstiter;
1261 if (firstiter) {
1262 PyObject *res;
1263
1264 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001265 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001266 Py_DECREF(firstiter);
1267 if (res == NULL) {
1268 return 1;
1269 }
1270 Py_DECREF(res);
1271 }
1272
1273 return 0;
1274}
1275
1276
1277static PyObject *
1278async_gen_anext(PyAsyncGenObject *o)
1279{
1280 if (async_gen_init_hooks(o)) {
1281 return NULL;
1282 }
1283 return async_gen_asend_new(o, NULL);
1284}
1285
1286
1287static PyObject *
1288async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1289{
1290 if (async_gen_init_hooks(o)) {
1291 return NULL;
1292 }
1293 return async_gen_asend_new(o, arg);
1294}
1295
1296
1297static PyObject *
1298async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1299{
1300 if (async_gen_init_hooks(o)) {
1301 return NULL;
1302 }
1303 return async_gen_athrow_new(o, NULL);
1304}
1305
1306static PyObject *
1307async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1308{
1309 if (async_gen_init_hooks(o)) {
1310 return NULL;
1311 }
1312 return async_gen_athrow_new(o, args);
1313}
1314
1315
1316static PyGetSetDef async_gen_getsetlist[] = {
1317 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1318 PyDoc_STR("name of the async generator")},
1319 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1320 PyDoc_STR("qualified name of the async generator")},
1321 {"ag_await", (getter)coro_get_cr_await, NULL,
1322 PyDoc_STR("object being awaited on, or None")},
1323 {NULL} /* Sentinel */
1324};
1325
1326static PyMemberDef async_gen_memberlist[] = {
1327 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001328 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1329 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001330 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1331 {NULL} /* Sentinel */
1332};
1333
1334PyDoc_STRVAR(async_aclose_doc,
1335"aclose() -> raise GeneratorExit inside generator.");
1336
1337PyDoc_STRVAR(async_asend_doc,
1338"asend(v) -> send 'v' in generator.");
1339
1340PyDoc_STRVAR(async_athrow_doc,
1341"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1342
1343static PyMethodDef async_gen_methods[] = {
1344 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1345 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1346 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001347 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1348 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001349 {NULL, NULL} /* Sentinel */
1350};
1351
1352
1353static PyAsyncMethods async_gen_as_async = {
1354 0, /* am_await */
1355 PyObject_SelfIter, /* am_aiter */
1356 (unaryfunc)async_gen_anext /* am_anext */
1357};
1358
1359
1360PyTypeObject PyAsyncGen_Type = {
1361 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1362 "async_generator", /* tp_name */
1363 sizeof(PyAsyncGenObject), /* tp_basicsize */
1364 0, /* tp_itemsize */
1365 /* methods */
1366 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001367 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001368 0, /* tp_getattr */
1369 0, /* tp_setattr */
1370 &async_gen_as_async, /* tp_as_async */
1371 (reprfunc)async_gen_repr, /* tp_repr */
1372 0, /* tp_as_number */
1373 0, /* tp_as_sequence */
1374 0, /* tp_as_mapping */
1375 0, /* tp_hash */
1376 0, /* tp_call */
1377 0, /* tp_str */
1378 PyObject_GenericGetAttr, /* tp_getattro */
1379 0, /* tp_setattro */
1380 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001381 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001382 0, /* tp_doc */
1383 (traverseproc)async_gen_traverse, /* tp_traverse */
1384 0, /* tp_clear */
1385 0, /* tp_richcompare */
1386 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1387 0, /* tp_iter */
1388 0, /* tp_iternext */
1389 async_gen_methods, /* tp_methods */
1390 async_gen_memberlist, /* tp_members */
1391 async_gen_getsetlist, /* tp_getset */
1392 0, /* tp_base */
1393 0, /* tp_dict */
1394 0, /* tp_descr_get */
1395 0, /* tp_descr_set */
1396 0, /* tp_dictoffset */
1397 0, /* tp_init */
1398 0, /* tp_alloc */
1399 0, /* tp_new */
1400 0, /* tp_free */
1401 0, /* tp_is_gc */
1402 0, /* tp_bases */
1403 0, /* tp_mro */
1404 0, /* tp_cache */
1405 0, /* tp_subclasses */
1406 0, /* tp_weaklist */
1407 0, /* tp_del */
1408 0, /* tp_version_tag */
1409 _PyGen_Finalize, /* tp_finalize */
1410};
1411
1412
1413PyObject *
1414PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1415{
1416 PyAsyncGenObject *o;
1417 o = (PyAsyncGenObject *)gen_new_with_qualname(
1418 &PyAsyncGen_Type, f, name, qualname);
1419 if (o == NULL) {
1420 return NULL;
1421 }
1422 o->ag_finalizer = NULL;
1423 o->ag_closed = 0;
1424 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001425 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001426 return (PyObject*)o;
1427}
1428
1429
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001430void
1431_PyAsyncGen_ClearFreeLists(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001432{
Yury Selivanoveb636452016-09-08 22:01:51 -07001433 while (ag_value_freelist_free) {
1434 _PyAsyncGenWrappedValue *o;
1435 o = ag_value_freelist[--ag_value_freelist_free];
1436 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001437 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001438 }
1439
1440 while (ag_asend_freelist_free) {
1441 PyAsyncGenASend *o;
1442 o = ag_asend_freelist[--ag_asend_freelist_free];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001443 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001444 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001445 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001446}
1447
1448void
Victor Stinnerbed48172019-08-27 00:12:32 +02001449_PyAsyncGen_Fini(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001450{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001451 _PyAsyncGen_ClearFreeLists();
Yury Selivanoveb636452016-09-08 22:01:51 -07001452}
1453
1454
1455static PyObject *
1456async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1457{
1458 if (result == NULL) {
1459 if (!PyErr_Occurred()) {
1460 PyErr_SetNone(PyExc_StopAsyncIteration);
1461 }
1462
1463 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1464 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1465 ) {
1466 gen->ag_closed = 1;
1467 }
1468
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001469 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001470 return NULL;
1471 }
1472
1473 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1474 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001475 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001476 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001477 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001478 return NULL;
1479 }
1480
1481 return result;
1482}
1483
1484
1485/* ---------- Async Generator ASend Awaitable ------------ */
1486
1487
1488static void
1489async_gen_asend_dealloc(PyAsyncGenASend *o)
1490{
Yury Selivanov29310c42016-11-08 19:46:22 -05001491 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001492 Py_CLEAR(o->ags_gen);
1493 Py_CLEAR(o->ags_sendval);
1494 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1495 assert(PyAsyncGenASend_CheckExact(o));
1496 ag_asend_freelist[ag_asend_freelist_free++] = o;
1497 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001498 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001499 }
1500}
1501
Yury Selivanov29310c42016-11-08 19:46:22 -05001502static int
1503async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1504{
1505 Py_VISIT(o->ags_gen);
1506 Py_VISIT(o->ags_sendval);
1507 return 0;
1508}
1509
Yury Selivanoveb636452016-09-08 22:01:51 -07001510
1511static PyObject *
1512async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1513{
1514 PyObject *result;
1515
1516 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001517 PyErr_SetString(
1518 PyExc_RuntimeError,
1519 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001520 return NULL;
1521 }
1522
1523 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001524 if (o->ags_gen->ag_running_async) {
1525 PyErr_SetString(
1526 PyExc_RuntimeError,
1527 "anext(): asynchronous generator is already running");
1528 return NULL;
1529 }
1530
Yury Selivanoveb636452016-09-08 22:01:51 -07001531 if (arg == NULL || arg == Py_None) {
1532 arg = o->ags_sendval;
1533 }
1534 o->ags_state = AWAITABLE_STATE_ITER;
1535 }
1536
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001537 o->ags_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001538 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1539 result = async_gen_unwrap_value(o->ags_gen, result);
1540
1541 if (result == NULL) {
1542 o->ags_state = AWAITABLE_STATE_CLOSED;
1543 }
1544
1545 return result;
1546}
1547
1548
1549static PyObject *
1550async_gen_asend_iternext(PyAsyncGenASend *o)
1551{
1552 return async_gen_asend_send(o, NULL);
1553}
1554
1555
1556static PyObject *
1557async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1558{
1559 PyObject *result;
1560
1561 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001562 PyErr_SetString(
1563 PyExc_RuntimeError,
1564 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001565 return NULL;
1566 }
1567
1568 result = gen_throw((PyGenObject*)o->ags_gen, args);
1569 result = async_gen_unwrap_value(o->ags_gen, result);
1570
1571 if (result == NULL) {
1572 o->ags_state = AWAITABLE_STATE_CLOSED;
1573 }
1574
1575 return result;
1576}
1577
1578
1579static PyObject *
1580async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1581{
1582 o->ags_state = AWAITABLE_STATE_CLOSED;
1583 Py_RETURN_NONE;
1584}
1585
1586
1587static PyMethodDef async_gen_asend_methods[] = {
1588 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1589 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1590 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1591 {NULL, NULL} /* Sentinel */
1592};
1593
1594
1595static PyAsyncMethods async_gen_asend_as_async = {
1596 PyObject_SelfIter, /* am_await */
1597 0, /* am_aiter */
1598 0 /* am_anext */
1599};
1600
1601
1602PyTypeObject _PyAsyncGenASend_Type = {
1603 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1604 "async_generator_asend", /* tp_name */
1605 sizeof(PyAsyncGenASend), /* tp_basicsize */
1606 0, /* tp_itemsize */
1607 /* methods */
1608 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001609 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001610 0, /* tp_getattr */
1611 0, /* tp_setattr */
1612 &async_gen_asend_as_async, /* tp_as_async */
1613 0, /* tp_repr */
1614 0, /* tp_as_number */
1615 0, /* tp_as_sequence */
1616 0, /* tp_as_mapping */
1617 0, /* tp_hash */
1618 0, /* tp_call */
1619 0, /* tp_str */
1620 PyObject_GenericGetAttr, /* tp_getattro */
1621 0, /* tp_setattro */
1622 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001623 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001624 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001625 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001626 0, /* tp_clear */
1627 0, /* tp_richcompare */
1628 0, /* tp_weaklistoffset */
1629 PyObject_SelfIter, /* tp_iter */
1630 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1631 async_gen_asend_methods, /* tp_methods */
1632 0, /* tp_members */
1633 0, /* tp_getset */
1634 0, /* tp_base */
1635 0, /* tp_dict */
1636 0, /* tp_descr_get */
1637 0, /* tp_descr_set */
1638 0, /* tp_dictoffset */
1639 0, /* tp_init */
1640 0, /* tp_alloc */
1641 0, /* tp_new */
1642};
1643
1644
1645static PyObject *
1646async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1647{
1648 PyAsyncGenASend *o;
1649 if (ag_asend_freelist_free) {
1650 ag_asend_freelist_free--;
1651 o = ag_asend_freelist[ag_asend_freelist_free];
1652 _Py_NewReference((PyObject *)o);
1653 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001654 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001655 if (o == NULL) {
1656 return NULL;
1657 }
1658 }
1659
1660 Py_INCREF(gen);
1661 o->ags_gen = gen;
1662
1663 Py_XINCREF(sendval);
1664 o->ags_sendval = sendval;
1665
1666 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001667
1668 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001669 return (PyObject*)o;
1670}
1671
1672
1673/* ---------- Async Generator Value Wrapper ------------ */
1674
1675
1676static void
1677async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1678{
Yury Selivanov29310c42016-11-08 19:46:22 -05001679 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001680 Py_CLEAR(o->agw_val);
1681 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1682 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1683 ag_value_freelist[ag_value_freelist_free++] = o;
1684 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001685 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001686 }
1687}
1688
1689
Yury Selivanov29310c42016-11-08 19:46:22 -05001690static int
1691async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1692 visitproc visit, void *arg)
1693{
1694 Py_VISIT(o->agw_val);
1695 return 0;
1696}
1697
1698
Yury Selivanoveb636452016-09-08 22:01:51 -07001699PyTypeObject _PyAsyncGenWrappedValue_Type = {
1700 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1701 "async_generator_wrapped_value", /* tp_name */
1702 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1703 0, /* tp_itemsize */
1704 /* methods */
1705 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001706 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001707 0, /* tp_getattr */
1708 0, /* tp_setattr */
1709 0, /* tp_as_async */
1710 0, /* tp_repr */
1711 0, /* tp_as_number */
1712 0, /* tp_as_sequence */
1713 0, /* tp_as_mapping */
1714 0, /* tp_hash */
1715 0, /* tp_call */
1716 0, /* tp_str */
1717 PyObject_GenericGetAttr, /* tp_getattro */
1718 0, /* tp_setattro */
1719 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001720 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001721 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001722 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001723 0, /* tp_clear */
1724 0, /* tp_richcompare */
1725 0, /* tp_weaklistoffset */
1726 0, /* tp_iter */
1727 0, /* tp_iternext */
1728 0, /* tp_methods */
1729 0, /* tp_members */
1730 0, /* tp_getset */
1731 0, /* tp_base */
1732 0, /* tp_dict */
1733 0, /* tp_descr_get */
1734 0, /* tp_descr_set */
1735 0, /* tp_dictoffset */
1736 0, /* tp_init */
1737 0, /* tp_alloc */
1738 0, /* tp_new */
1739};
1740
1741
1742PyObject *
1743_PyAsyncGenValueWrapperNew(PyObject *val)
1744{
1745 _PyAsyncGenWrappedValue *o;
1746 assert(val);
1747
1748 if (ag_value_freelist_free) {
1749 ag_value_freelist_free--;
1750 o = ag_value_freelist[ag_value_freelist_free];
1751 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1752 _Py_NewReference((PyObject*)o);
1753 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001754 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1755 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001756 if (o == NULL) {
1757 return NULL;
1758 }
1759 }
1760 o->agw_val = val;
1761 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001762 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001763 return (PyObject*)o;
1764}
1765
1766
1767/* ---------- Async Generator AThrow awaitable ------------ */
1768
1769
1770static void
1771async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1772{
Yury Selivanov29310c42016-11-08 19:46:22 -05001773 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001774 Py_CLEAR(o->agt_gen);
1775 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001776 PyObject_GC_Del(o);
1777}
1778
1779
1780static int
1781async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1782{
1783 Py_VISIT(o->agt_gen);
1784 Py_VISIT(o->agt_args);
1785 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001786}
1787
1788
1789static PyObject *
1790async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1791{
1792 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1793 PyFrameObject *f = gen->gi_frame;
1794 PyObject *retval;
1795
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001796 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001797 PyErr_SetString(
1798 PyExc_RuntimeError,
1799 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001800 return NULL;
1801 }
1802
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001803 if (f == NULL || f->f_stacktop == NULL) {
1804 o->agt_state = AWAITABLE_STATE_CLOSED;
1805 PyErr_SetNone(PyExc_StopIteration);
1806 return NULL;
1807 }
1808
Yury Selivanoveb636452016-09-08 22:01:51 -07001809 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001810 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001811 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001812 if (o->agt_args == NULL) {
1813 PyErr_SetString(
1814 PyExc_RuntimeError,
1815 "aclose(): asynchronous generator is already running");
1816 }
1817 else {
1818 PyErr_SetString(
1819 PyExc_RuntimeError,
1820 "athrow(): asynchronous generator is already running");
1821 }
1822 return NULL;
1823 }
1824
Yury Selivanoveb636452016-09-08 22:01:51 -07001825 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001826 o->agt_state = AWAITABLE_STATE_CLOSED;
1827 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001828 return NULL;
1829 }
1830
1831 if (arg != Py_None) {
1832 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1833 return NULL;
1834 }
1835
1836 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001837 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001838
1839 if (o->agt_args == NULL) {
1840 /* aclose() mode */
1841 o->agt_gen->ag_closed = 1;
1842
1843 retval = _gen_throw((PyGenObject *)gen,
1844 0, /* Do not close generator when
1845 PyExc_GeneratorExit is passed */
1846 PyExc_GeneratorExit, NULL, NULL);
1847
1848 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1849 Py_DECREF(retval);
1850 goto yield_close;
1851 }
1852 } else {
1853 PyObject *typ;
1854 PyObject *tb = NULL;
1855 PyObject *val = NULL;
1856
1857 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1858 &typ, &val, &tb)) {
1859 return NULL;
1860 }
1861
1862 retval = _gen_throw((PyGenObject *)gen,
1863 0, /* Do not close generator when
1864 PyExc_GeneratorExit is passed */
1865 typ, val, tb);
1866 retval = async_gen_unwrap_value(o->agt_gen, retval);
1867 }
1868 if (retval == NULL) {
1869 goto check_error;
1870 }
1871 return retval;
1872 }
1873
1874 assert(o->agt_state == AWAITABLE_STATE_ITER);
1875
1876 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1877 if (o->agt_args) {
1878 return async_gen_unwrap_value(o->agt_gen, retval);
1879 } else {
1880 /* aclose() mode */
1881 if (retval) {
1882 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1883 Py_DECREF(retval);
1884 goto yield_close;
1885 }
1886 else {
1887 return retval;
1888 }
1889 }
1890 else {
1891 goto check_error;
1892 }
1893 }
1894
1895yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001896 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001897 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001898 PyErr_SetString(
1899 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1900 return NULL;
1901
1902check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001903 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001904 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001905 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1906 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1907 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001908 if (o->agt_args == NULL) {
1909 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001910 StopAsyncIteration or GeneratorExit; just raise
1911 StopIteration, signalling that this 'aclose()' await
1912 is done.
1913 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001914 PyErr_Clear();
1915 PyErr_SetNone(PyExc_StopIteration);
1916 }
1917 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001918 return NULL;
1919}
1920
1921
1922static PyObject *
1923async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1924{
1925 PyObject *retval;
1926
Yury Selivanoveb636452016-09-08 22:01:51 -07001927 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001928 PyErr_SetString(
1929 PyExc_RuntimeError,
1930 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001931 return NULL;
1932 }
1933
1934 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1935 if (o->agt_args) {
1936 return async_gen_unwrap_value(o->agt_gen, retval);
1937 } else {
1938 /* aclose() mode */
1939 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001940 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001941 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001942 Py_DECREF(retval);
1943 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1944 return NULL;
1945 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08001946 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1947 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1948 {
1949 /* when aclose() is called we don't want to propagate
1950 StopAsyncIteration or GeneratorExit; just raise
1951 StopIteration, signalling that this 'aclose()' await
1952 is done.
1953 */
1954 PyErr_Clear();
1955 PyErr_SetNone(PyExc_StopIteration);
1956 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001957 return retval;
1958 }
1959}
1960
1961
1962static PyObject *
1963async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1964{
1965 return async_gen_athrow_send(o, Py_None);
1966}
1967
1968
1969static PyObject *
1970async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1971{
1972 o->agt_state = AWAITABLE_STATE_CLOSED;
1973 Py_RETURN_NONE;
1974}
1975
1976
1977static PyMethodDef async_gen_athrow_methods[] = {
1978 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1979 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1980 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1981 {NULL, NULL} /* Sentinel */
1982};
1983
1984
1985static PyAsyncMethods async_gen_athrow_as_async = {
1986 PyObject_SelfIter, /* am_await */
1987 0, /* am_aiter */
1988 0 /* am_anext */
1989};
1990
1991
1992PyTypeObject _PyAsyncGenAThrow_Type = {
1993 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1994 "async_generator_athrow", /* tp_name */
1995 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1996 0, /* tp_itemsize */
1997 /* methods */
1998 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001999 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002000 0, /* tp_getattr */
2001 0, /* tp_setattr */
2002 &async_gen_athrow_as_async, /* tp_as_async */
2003 0, /* tp_repr */
2004 0, /* tp_as_number */
2005 0, /* tp_as_sequence */
2006 0, /* tp_as_mapping */
2007 0, /* tp_hash */
2008 0, /* tp_call */
2009 0, /* tp_str */
2010 PyObject_GenericGetAttr, /* tp_getattro */
2011 0, /* tp_setattro */
2012 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002013 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002014 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002015 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002016 0, /* tp_clear */
2017 0, /* tp_richcompare */
2018 0, /* tp_weaklistoffset */
2019 PyObject_SelfIter, /* tp_iter */
2020 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2021 async_gen_athrow_methods, /* tp_methods */
2022 0, /* tp_members */
2023 0, /* tp_getset */
2024 0, /* tp_base */
2025 0, /* tp_dict */
2026 0, /* tp_descr_get */
2027 0, /* tp_descr_set */
2028 0, /* tp_dictoffset */
2029 0, /* tp_init */
2030 0, /* tp_alloc */
2031 0, /* tp_new */
2032};
2033
2034
2035static PyObject *
2036async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2037{
2038 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002039 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002040 if (o == NULL) {
2041 return NULL;
2042 }
2043 o->agt_gen = gen;
2044 o->agt_args = args;
2045 o->agt_state = AWAITABLE_STATE_INIT;
2046 Py_INCREF(gen);
2047 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002048 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002049 return (PyObject*)o;
2050}