blob: 271720bdf8b4cef7a5a8755e0c077114ac6f8e2f [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
Miss Islington (bot)f02c3042020-05-18 19:14:13 -0700206 if (exc) {
207 _PyErr_ChainStackItem(&gen->gi_exc_state);
Chris Jerdonek75cd8e42020-05-13 16:18:27 -0700208 }
209
Antoine Pitrou93963562013-05-14 20:37:52 +0200210 gen->gi_running = 1;
Mark Shannonae3087c2017-10-22 22:41:51 +0100211 gen->gi_exc_state.previous_item = tstate->exc_info;
212 tstate->exc_info = &gen->gi_exc_state;
Victor Stinnerb9e68122019-11-14 12:20:46 +0100213 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100214 tstate->exc_info = gen->gi_exc_state.previous_item;
215 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200216 gen->gi_running = 0;
217
218 /* Don't keep the reference to f_back any longer than necessary. It
219 * may keep a chain of frames alive or it could create a reference
220 * cycle. */
221 assert(f->f_back == tstate->frame);
222 Py_CLEAR(f->f_back);
223
224 /* If the generator just returned (as opposed to yielding), signal
225 * that the generator is exhausted. */
226 if (result && f->f_stacktop == NULL) {
227 if (result == Py_None) {
228 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700229 if (PyAsyncGen_CheckExact(gen)) {
230 PyErr_SetNone(PyExc_StopAsyncIteration);
231 }
232 else {
233 PyErr_SetNone(PyExc_StopIteration);
234 }
235 }
236 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700237 /* Async generators cannot return anything but None */
238 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200239 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200240 }
241 Py_CLEAR(result);
242 }
Yury Selivanov68333392015-05-22 11:16:47 -0400243 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500244 const char *msg = "generator raised StopIteration";
245 if (PyCoro_CheckExact(gen)) {
246 msg = "coroutine raised StopIteration";
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400247 }
Dong-hee Nad905df72020-02-14 02:37:17 +0900248 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500249 msg = "async generator raised StopIteration";
Yury Selivanov68333392015-05-22 11:16:47 -0400250 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500251 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
252
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400253 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500254 else if (!result && PyAsyncGen_CheckExact(gen) &&
Yury Selivanoveb636452016-09-08 22:01:51 -0700255 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
256 {
257 /* code in `gen` raised a StopAsyncIteration error:
258 raise a RuntimeError.
259 */
260 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300261 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700262 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200263
264 if (!result || f->f_stacktop == NULL) {
265 /* generator can't be rerun, so release the frame */
266 /* first clean reference cycle through stored exception traceback */
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700267 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200268 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200269 gen->gi_frame = NULL;
270 Py_DECREF(f);
271 }
272
273 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000274}
275
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000276PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277"send(arg) -> send 'arg' into generator,\n\
278return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000279
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500280PyObject *
281_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000282{
Yury Selivanov77c96812016-02-13 17:59:05 -0500283 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000284}
285
286PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400287"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000288
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000289/*
290 * This helper function is used by gen_close and gen_throw to
291 * close a subiterator being delegated to by yield-from.
292 */
293
Antoine Pitrou93963562013-05-14 20:37:52 +0200294static int
295gen_close_iter(PyObject *yf)
296{
297 PyObject *retval = NULL;
298 _Py_IDENTIFIER(close);
299
Yury Selivanoveb636452016-09-08 22:01:51 -0700300 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200301 retval = gen_close((PyGenObject *)yf, NULL);
302 if (retval == NULL)
303 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700304 }
305 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200306 PyObject *meth;
307 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
308 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700309 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200310 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700311 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200312 Py_DECREF(meth);
313 if (retval == NULL)
314 return -1;
315 }
316 }
317 Py_XDECREF(retval);
318 return 0;
319}
320
Yury Selivanovc724bae2016-03-02 11:30:46 -0500321PyObject *
322_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500323{
Antoine Pitrou93963562013-05-14 20:37:52 +0200324 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500325 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200326
327 if (f && f->f_stacktop) {
328 PyObject *bytecode = f->f_code->co_code;
329 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
330
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100331 if (f->f_lasti < 0) {
332 /* Return immediately if the frame didn't start yet. YIELD_FROM
333 always come after LOAD_CONST: a code object should not start
334 with YIELD_FROM */
335 assert(code[0] != YIELD_FROM);
336 return NULL;
337 }
338
Serhiy Storchakaab874002016-09-11 13:48:15 +0300339 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200340 return NULL;
341 yf = f->f_stacktop[-1];
342 Py_INCREF(yf);
343 }
344
345 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500346}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000347
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000348static PyObject *
349gen_close(PyGenObject *gen, PyObject *args)
350{
Antoine Pitrou93963562013-05-14 20:37:52 +0200351 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500352 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200353 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000354
Antoine Pitrou93963562013-05-14 20:37:52 +0200355 if (yf) {
356 gen->gi_running = 1;
357 err = gen_close_iter(yf);
358 gen->gi_running = 0;
359 Py_DECREF(yf);
360 }
361 if (err == 0)
362 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500363 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200364 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200365 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700366 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400367 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700368 } else if (PyAsyncGen_CheckExact(gen)) {
369 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
370 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200371 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400372 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 return NULL;
374 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200375 if (PyErr_ExceptionMatches(PyExc_StopIteration)
376 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
377 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200378 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200379 }
380 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000381}
382
Antoine Pitrou93963562013-05-14 20:37:52 +0200383
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000384PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000385"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
386return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000387
388static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700389_gen_throw(PyGenObject *gen, int close_on_genexit,
390 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000391{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500392 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000393 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000394
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000395 if (yf) {
396 PyObject *ret;
397 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700398 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
399 close_on_genexit
400 ) {
401 /* Asynchronous generators *should not* be closed right away.
402 We have to allow some awaits to work it through, hence the
403 `close_on_genexit` parameter here.
404 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500405 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200406 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500407 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000408 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000409 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500410 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000411 goto throw_here;
412 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700413 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
414 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500415 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700416 /* Close the generator that we are currently iterating with
417 'yield from' or awaiting on with 'await'. */
418 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
419 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500420 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000421 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700422 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200423 PyObject *meth;
424 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
425 Py_DECREF(yf);
426 return NULL;
427 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000428 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000429 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000430 goto throw_here;
431 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500432 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700433 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500434 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000435 Py_DECREF(meth);
436 }
437 Py_DECREF(yf);
438 if (!ret) {
439 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500440 /* Pop subiterator from stack */
441 ret = *(--gen->gi_frame->f_stacktop);
442 assert(ret == yf);
443 Py_DECREF(ret);
444 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100445 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300446 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000447 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500448 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000449 Py_DECREF(val);
450 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500451 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000452 }
453 }
454 return ret;
455 }
456
457throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 /* First, check the traceback argument, replacing None with
459 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400460 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 else if (tb != NULL && !PyTraceBack_Check(tb)) {
464 PyErr_SetString(PyExc_TypeError,
465 "throw() third argument must be a traceback object");
466 return NULL;
467 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_INCREF(typ);
470 Py_XINCREF(val);
471 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000472
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400473 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 else if (PyExceptionInstance_Check(typ)) {
477 /* Raising an instance. The value should be a dummy. */
478 if (val && val != Py_None) {
479 PyErr_SetString(PyExc_TypeError,
480 "instance exception may not have a separate value");
481 goto failed_throw;
482 }
483 else {
484 /* Normalize to raise <class>, <instance> */
485 Py_XDECREF(val);
486 val = typ;
487 typ = PyExceptionInstance_Class(typ);
488 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200489
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400490 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200491 /* Returns NULL if there's no traceback */
492 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 }
494 }
495 else {
496 /* Not something you can raise. throw() fails. */
497 PyErr_Format(PyExc_TypeError,
498 "exceptions must be classes or instances "
499 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000500 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 goto failed_throw;
502 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500505 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000506
507failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* Didn't use our arguments, so restore their original refcounts */
509 Py_DECREF(typ);
510 Py_XDECREF(val);
511 Py_XDECREF(tb);
512 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000513}
514
515
516static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700517gen_throw(PyGenObject *gen, PyObject *args)
518{
519 PyObject *typ;
520 PyObject *tb = NULL;
521 PyObject *val = NULL;
522
523 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
524 return NULL;
525 }
526
527 return _gen_throw(gen, 1, typ, val, tb);
528}
529
530
531static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000532gen_iternext(PyGenObject *gen)
533{
Yury Selivanov77c96812016-02-13 17:59:05 -0500534 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000535}
536
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000537/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200538 * Set StopIteration with specified value. Value can be arbitrary object
539 * or NULL.
540 *
541 * Returns 0 if StopIteration is set and -1 if any other exception is set.
542 */
543int
544_PyGen_SetStopIterationValue(PyObject *value)
545{
546 PyObject *e;
547
548 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400549 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200550 {
551 /* Delay exception instantiation if we can */
552 PyErr_SetObject(PyExc_StopIteration, value);
553 return 0;
554 }
555 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100556 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200557 *
558 * We do this to handle a situation when "value" is a tuple, in which
559 * case PyErr_SetObject would set the value of StopIteration to
560 * the first element of the tuple.
561 *
562 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
563 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100564 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200565 if (e == NULL) {
566 return -1;
567 }
568 PyErr_SetObject(PyExc_StopIteration, e);
569 Py_DECREF(e);
570 return 0;
571}
572
573/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000574 * If StopIteration exception is set, fetches its 'value'
575 * attribute if any, otherwise sets pvalue to None.
576 *
577 * Returns 0 if no exception or StopIteration is set.
578 * If any other exception is set, returns -1 and leaves
579 * pvalue unchanged.
580 */
581
582int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200583_PyGen_FetchStopIterationValue(PyObject **pvalue)
584{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000585 PyObject *et, *ev, *tb;
586 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500587
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000588 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
589 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200590 if (ev) {
591 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300592 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200593 value = ((PyStopIterationObject *)ev)->value;
594 Py_INCREF(value);
595 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200596 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
597 /* Avoid normalisation and take ev as value.
598 *
599 * Normalization is required if the value is a tuple, in
600 * that case the value of StopIteration would be set to
601 * the first element of the tuple.
602 *
603 * (See _PyErr_CreateException code for details.)
604 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200605 value = ev;
606 } else {
607 /* normalisation required */
608 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300609 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200610 PyErr_Restore(et, ev, tb);
611 return -1;
612 }
613 value = ((PyStopIterationObject *)ev)->value;
614 Py_INCREF(value);
615 Py_DECREF(ev);
616 }
617 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000618 Py_XDECREF(et);
619 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000620 } else if (PyErr_Occurred()) {
621 return -1;
622 }
623 if (value == NULL) {
624 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100625 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000626 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000627 *pvalue = value;
628 return 0;
629}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000630
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000631static PyObject *
632gen_repr(PyGenObject *gen)
633{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400634 return PyUnicode_FromFormat("<generator object %S at %p>",
635 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000636}
637
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000638static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200639gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000640{
Victor Stinner40ee3012014-06-16 15:59:28 +0200641 Py_INCREF(op->gi_name);
642 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000643}
644
Victor Stinner40ee3012014-06-16 15:59:28 +0200645static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200646gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200647{
Victor Stinner40ee3012014-06-16 15:59:28 +0200648 /* Not legal to del gen.gi_name or to set it to anything
649 * other than a string object. */
650 if (value == NULL || !PyUnicode_Check(value)) {
651 PyErr_SetString(PyExc_TypeError,
652 "__name__ must be set to a string object");
653 return -1;
654 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200655 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300656 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200657 return 0;
658}
659
660static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200661gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200662{
663 Py_INCREF(op->gi_qualname);
664 return op->gi_qualname;
665}
666
667static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200668gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200669{
Victor Stinner40ee3012014-06-16 15:59:28 +0200670 /* Not legal to del gen.__qualname__ or to set it to anything
671 * other than a string object. */
672 if (value == NULL || !PyUnicode_Check(value)) {
673 PyErr_SetString(PyExc_TypeError,
674 "__qualname__ must be set to a string object");
675 return -1;
676 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200677 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300678 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200679 return 0;
680}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000681
Yury Selivanove13f8f32015-07-03 00:23:30 -0400682static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200683gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400684{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500685 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400686 if (yf == NULL)
687 Py_RETURN_NONE;
688 return yf;
689}
690
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000691static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200692 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
693 PyDoc_STR("name of the generator")},
694 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
695 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400696 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
697 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200698 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000699};
700
Martin v. Löwise440e472004-06-01 15:22:42 +0000701static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200702 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
703 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
704 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000706};
707
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000708static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500709 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
711 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
712 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000713};
714
Martin v. Löwise440e472004-06-01 15:22:42 +0000715PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyVarObject_HEAD_INIT(&PyType_Type, 0)
717 "generator", /* tp_name */
718 sizeof(PyGenObject), /* tp_basicsize */
719 0, /* tp_itemsize */
720 /* methods */
721 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200722 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 0, /* tp_getattr */
724 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400725 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 (reprfunc)gen_repr, /* tp_repr */
727 0, /* tp_as_number */
728 0, /* tp_as_sequence */
729 0, /* tp_as_mapping */
730 0, /* tp_hash */
731 0, /* tp_call */
732 0, /* tp_str */
733 PyObject_GenericGetAttr, /* tp_getattro */
734 0, /* tp_setattro */
735 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200736 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 0, /* tp_doc */
738 (traverseproc)gen_traverse, /* tp_traverse */
739 0, /* tp_clear */
740 0, /* tp_richcompare */
741 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400742 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 (iternextfunc)gen_iternext, /* tp_iternext */
744 gen_methods, /* tp_methods */
745 gen_memberlist, /* tp_members */
746 gen_getsetlist, /* tp_getset */
747 0, /* tp_base */
748 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 0, /* tp_descr_get */
751 0, /* tp_descr_set */
752 0, /* tp_dictoffset */
753 0, /* tp_init */
754 0, /* tp_alloc */
755 0, /* tp_new */
756 0, /* tp_free */
757 0, /* tp_is_gc */
758 0, /* tp_bases */
759 0, /* tp_mro */
760 0, /* tp_cache */
761 0, /* tp_subclasses */
762 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200763 0, /* tp_del */
764 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200765 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000766};
767
Yury Selivanov5376ba92015-06-22 12:19:30 -0400768static PyObject *
769gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
770 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000771{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400772 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (gen == NULL) {
774 Py_DECREF(f);
775 return NULL;
776 }
777 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200778 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 Py_INCREF(f->f_code);
780 gen->gi_code = (PyObject *)(f->f_code);
781 gen->gi_running = 0;
782 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100783 gen->gi_exc_state.exc_type = NULL;
784 gen->gi_exc_state.exc_value = NULL;
785 gen->gi_exc_state.exc_traceback = NULL;
786 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200787 if (name != NULL)
788 gen->gi_name = name;
789 else
790 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
791 Py_INCREF(gen->gi_name);
792 if (qualname != NULL)
793 gen->gi_qualname = qualname;
794 else
795 gen->gi_qualname = gen->gi_name;
796 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 _PyObject_GC_TRACK(gen);
798 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000799}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000800
Victor Stinner40ee3012014-06-16 15:59:28 +0200801PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400802PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
803{
804 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
805}
806
807PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200808PyGen_New(PyFrameObject *f)
809{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400810 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200811}
812
Yury Selivanov5376ba92015-06-22 12:19:30 -0400813/* Coroutine Object */
814
815typedef struct {
816 PyObject_HEAD
817 PyCoroObject *cw_coroutine;
818} PyCoroWrapper;
819
820static int
821gen_is_coroutine(PyObject *o)
822{
823 if (PyGen_CheckExact(o)) {
824 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
825 if (code->co_flags & CO_ITERABLE_COROUTINE) {
826 return 1;
827 }
828 }
829 return 0;
830}
831
Yury Selivanov75445082015-05-11 22:57:16 -0400832/*
833 * This helper function returns an awaitable for `o`:
834 * - `o` if `o` is a coroutine-object;
835 * - `type(o)->tp_as_async->am_await(o)`
836 *
837 * Raises a TypeError if it's not possible to return
838 * an awaitable and returns NULL.
839 */
840PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400841_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400842{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400843 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400844 PyTypeObject *ot;
845
Yury Selivanov5376ba92015-06-22 12:19:30 -0400846 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
847 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400848 Py_INCREF(o);
849 return o;
850 }
851
852 ot = Py_TYPE(o);
853 if (ot->tp_as_async != NULL) {
854 getter = ot->tp_as_async->am_await;
855 }
856 if (getter != NULL) {
857 PyObject *res = (*getter)(o);
858 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400859 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
860 /* __await__ must return an *iterator*, not
861 a coroutine or another awaitable (see PEP 492) */
862 PyErr_SetString(PyExc_TypeError,
863 "__await__() returned a coroutine");
864 Py_CLEAR(res);
865 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400866 PyErr_Format(PyExc_TypeError,
867 "__await__() returned non-iterator "
868 "of type '%.100s'",
869 Py_TYPE(res)->tp_name);
870 Py_CLEAR(res);
871 }
Yury Selivanov75445082015-05-11 22:57:16 -0400872 }
873 return res;
874 }
875
876 PyErr_Format(PyExc_TypeError,
877 "object %.100s can't be used in 'await' expression",
878 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400879 return NULL;
880}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400881
882static PyObject *
883coro_repr(PyCoroObject *coro)
884{
885 return PyUnicode_FromFormat("<coroutine object %S at %p>",
886 coro->cr_qualname, coro);
887}
888
889static PyObject *
890coro_await(PyCoroObject *coro)
891{
892 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
893 if (cw == NULL) {
894 return NULL;
895 }
896 Py_INCREF(coro);
897 cw->cw_coroutine = coro;
898 _PyObject_GC_TRACK(cw);
899 return (PyObject *)cw;
900}
901
Yury Selivanove13f8f32015-07-03 00:23:30 -0400902static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200903coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400904{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500905 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400906 if (yf == NULL)
907 Py_RETURN_NONE;
908 return yf;
909}
910
Yury Selivanov5376ba92015-06-22 12:19:30 -0400911static PyGetSetDef coro_getsetlist[] = {
912 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
913 PyDoc_STR("name of the coroutine")},
914 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
915 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400916 {"cr_await", (getter)coro_get_cr_await, NULL,
917 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400918 {NULL} /* Sentinel */
919};
920
921static PyMemberDef coro_memberlist[] = {
922 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
923 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
924 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800925 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400926 {NULL} /* Sentinel */
927};
928
929PyDoc_STRVAR(coro_send_doc,
930"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400931return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400932
933PyDoc_STRVAR(coro_throw_doc,
934"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400935return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400936
937PyDoc_STRVAR(coro_close_doc,
938"close() -> raise GeneratorExit inside coroutine.");
939
940static PyMethodDef coro_methods[] = {
941 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
942 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
943 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
944 {NULL, NULL} /* Sentinel */
945};
946
947static PyAsyncMethods coro_as_async = {
948 (unaryfunc)coro_await, /* am_await */
949 0, /* am_aiter */
950 0 /* am_anext */
951};
952
953PyTypeObject PyCoro_Type = {
954 PyVarObject_HEAD_INIT(&PyType_Type, 0)
955 "coroutine", /* tp_name */
956 sizeof(PyCoroObject), /* tp_basicsize */
957 0, /* tp_itemsize */
958 /* methods */
959 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200960 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400961 0, /* tp_getattr */
962 0, /* tp_setattr */
963 &coro_as_async, /* tp_as_async */
964 (reprfunc)coro_repr, /* tp_repr */
965 0, /* tp_as_number */
966 0, /* tp_as_sequence */
967 0, /* tp_as_mapping */
968 0, /* tp_hash */
969 0, /* tp_call */
970 0, /* tp_str */
971 PyObject_GenericGetAttr, /* tp_getattro */
972 0, /* tp_setattro */
973 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200974 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400975 0, /* tp_doc */
976 (traverseproc)gen_traverse, /* tp_traverse */
977 0, /* tp_clear */
978 0, /* tp_richcompare */
979 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
980 0, /* tp_iter */
981 0, /* tp_iternext */
982 coro_methods, /* tp_methods */
983 coro_memberlist, /* tp_members */
984 coro_getsetlist, /* tp_getset */
985 0, /* tp_base */
986 0, /* tp_dict */
987 0, /* tp_descr_get */
988 0, /* tp_descr_set */
989 0, /* tp_dictoffset */
990 0, /* tp_init */
991 0, /* tp_alloc */
992 0, /* tp_new */
993 0, /* tp_free */
994 0, /* tp_is_gc */
995 0, /* tp_bases */
996 0, /* tp_mro */
997 0, /* tp_cache */
998 0, /* tp_subclasses */
999 0, /* tp_weaklist */
1000 0, /* tp_del */
1001 0, /* tp_version_tag */
1002 _PyGen_Finalize, /* tp_finalize */
1003};
1004
1005static void
1006coro_wrapper_dealloc(PyCoroWrapper *cw)
1007{
1008 _PyObject_GC_UNTRACK((PyObject *)cw);
1009 Py_CLEAR(cw->cw_coroutine);
1010 PyObject_GC_Del(cw);
1011}
1012
1013static PyObject *
1014coro_wrapper_iternext(PyCoroWrapper *cw)
1015{
Yury Selivanov77c96812016-02-13 17:59:05 -05001016 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001017}
1018
1019static PyObject *
1020coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1021{
Yury Selivanov77c96812016-02-13 17:59:05 -05001022 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001023}
1024
1025static PyObject *
1026coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1027{
1028 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1029}
1030
1031static PyObject *
1032coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1033{
1034 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1035}
1036
1037static int
1038coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1039{
1040 Py_VISIT((PyObject *)cw->cw_coroutine);
1041 return 0;
1042}
1043
1044static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001045 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1046 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1047 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001048 {NULL, NULL} /* Sentinel */
1049};
1050
1051PyTypeObject _PyCoroWrapper_Type = {
1052 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1053 "coroutine_wrapper",
1054 sizeof(PyCoroWrapper), /* tp_basicsize */
1055 0, /* tp_itemsize */
1056 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001057 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001058 0, /* tp_getattr */
1059 0, /* tp_setattr */
1060 0, /* tp_as_async */
1061 0, /* tp_repr */
1062 0, /* tp_as_number */
1063 0, /* tp_as_sequence */
1064 0, /* tp_as_mapping */
1065 0, /* tp_hash */
1066 0, /* tp_call */
1067 0, /* tp_str */
1068 PyObject_GenericGetAttr, /* tp_getattro */
1069 0, /* tp_setattro */
1070 0, /* tp_as_buffer */
1071 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1072 "A wrapper object implementing __await__ for coroutines.",
1073 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1074 0, /* tp_clear */
1075 0, /* tp_richcompare */
1076 0, /* tp_weaklistoffset */
1077 PyObject_SelfIter, /* tp_iter */
1078 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1079 coro_wrapper_methods, /* tp_methods */
1080 0, /* tp_members */
1081 0, /* tp_getset */
1082 0, /* tp_base */
1083 0, /* tp_dict */
1084 0, /* tp_descr_get */
1085 0, /* tp_descr_set */
1086 0, /* tp_dictoffset */
1087 0, /* tp_init */
1088 0, /* tp_alloc */
1089 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001090 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001091};
1092
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001093static PyObject *
1094compute_cr_origin(int origin_depth)
1095{
1096 PyFrameObject *frame = PyEval_GetFrame();
1097 /* First count how many frames we have */
1098 int frame_count = 0;
1099 for (; frame && frame_count < origin_depth; ++frame_count) {
1100 frame = frame->f_back;
1101 }
1102
1103 /* Now collect them */
1104 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001105 if (cr_origin == NULL) {
1106 return NULL;
1107 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001108 frame = PyEval_GetFrame();
1109 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001110 PyCodeObject *code = frame->f_code;
1111 PyObject *frameinfo = Py_BuildValue("OiO",
1112 code->co_filename,
1113 PyFrame_GetLineNumber(frame),
1114 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001115 if (!frameinfo) {
1116 Py_DECREF(cr_origin);
1117 return NULL;
1118 }
1119 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1120 frame = frame->f_back;
1121 }
1122
1123 return cr_origin;
1124}
1125
Yury Selivanov5376ba92015-06-22 12:19:30 -04001126PyObject *
1127PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1128{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001129 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1130 if (!coro) {
1131 return NULL;
1132 }
1133
Victor Stinner50b48572018-11-01 01:51:40 +01001134 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001135 int origin_depth = tstate->coroutine_origin_tracking_depth;
1136
1137 if (origin_depth == 0) {
1138 ((PyCoroObject *)coro)->cr_origin = NULL;
1139 } else {
1140 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001141 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001142 if (!cr_origin) {
1143 Py_DECREF(coro);
1144 return NULL;
1145 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001146 }
1147
1148 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001149}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001150
1151
Yury Selivanoveb636452016-09-08 22:01:51 -07001152/* ========= Asynchronous Generators ========= */
1153
1154
1155typedef enum {
1156 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1157 AWAITABLE_STATE_ITER, /* being iterated */
1158 AWAITABLE_STATE_CLOSED, /* closed */
1159} AwaitableState;
1160
1161
1162typedef struct {
1163 PyObject_HEAD
1164 PyAsyncGenObject *ags_gen;
1165
1166 /* Can be NULL, when in the __anext__() mode
1167 (equivalent of "asend(None)") */
1168 PyObject *ags_sendval;
1169
1170 AwaitableState ags_state;
1171} PyAsyncGenASend;
1172
1173
1174typedef struct {
1175 PyObject_HEAD
1176 PyAsyncGenObject *agt_gen;
1177
1178 /* Can be NULL, when in the "aclose()" mode
1179 (equivalent of "athrow(GeneratorExit)") */
1180 PyObject *agt_args;
1181
1182 AwaitableState agt_state;
1183} PyAsyncGenAThrow;
1184
1185
1186typedef struct {
1187 PyObject_HEAD
1188 PyObject *agw_val;
1189} _PyAsyncGenWrappedValue;
1190
1191
1192#ifndef _PyAsyncGen_MAXFREELIST
1193#define _PyAsyncGen_MAXFREELIST 80
1194#endif
1195
1196/* Freelists boost performance 6-10%; they also reduce memory
1197 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1198 are short-living objects that are instantiated for every
1199 __anext__ call.
1200*/
1201
1202static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1203static int ag_value_freelist_free = 0;
1204
1205static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1206static int ag_asend_freelist_free = 0;
1207
1208#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001209 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001210
1211#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001212 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001213
1214
1215static int
1216async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1217{
1218 Py_VISIT(gen->ag_finalizer);
1219 return gen_traverse((PyGenObject*)gen, visit, arg);
1220}
1221
1222
1223static PyObject *
1224async_gen_repr(PyAsyncGenObject *o)
1225{
1226 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1227 o->ag_qualname, o);
1228}
1229
1230
1231static int
1232async_gen_init_hooks(PyAsyncGenObject *o)
1233{
1234 PyThreadState *tstate;
1235 PyObject *finalizer;
1236 PyObject *firstiter;
1237
1238 if (o->ag_hooks_inited) {
1239 return 0;
1240 }
1241
1242 o->ag_hooks_inited = 1;
1243
Victor Stinner50b48572018-11-01 01:51:40 +01001244 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001245
1246 finalizer = tstate->async_gen_finalizer;
1247 if (finalizer) {
1248 Py_INCREF(finalizer);
1249 o->ag_finalizer = finalizer;
1250 }
1251
1252 firstiter = tstate->async_gen_firstiter;
1253 if (firstiter) {
1254 PyObject *res;
1255
1256 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001257 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001258 Py_DECREF(firstiter);
1259 if (res == NULL) {
1260 return 1;
1261 }
1262 Py_DECREF(res);
1263 }
1264
1265 return 0;
1266}
1267
1268
1269static PyObject *
1270async_gen_anext(PyAsyncGenObject *o)
1271{
1272 if (async_gen_init_hooks(o)) {
1273 return NULL;
1274 }
1275 return async_gen_asend_new(o, NULL);
1276}
1277
1278
1279static PyObject *
1280async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1281{
1282 if (async_gen_init_hooks(o)) {
1283 return NULL;
1284 }
1285 return async_gen_asend_new(o, arg);
1286}
1287
1288
1289static PyObject *
1290async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1291{
1292 if (async_gen_init_hooks(o)) {
1293 return NULL;
1294 }
1295 return async_gen_athrow_new(o, NULL);
1296}
1297
1298static PyObject *
1299async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1300{
1301 if (async_gen_init_hooks(o)) {
1302 return NULL;
1303 }
1304 return async_gen_athrow_new(o, args);
1305}
1306
1307
1308static PyGetSetDef async_gen_getsetlist[] = {
1309 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1310 PyDoc_STR("name of the async generator")},
1311 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1312 PyDoc_STR("qualified name of the async generator")},
1313 {"ag_await", (getter)coro_get_cr_await, NULL,
1314 PyDoc_STR("object being awaited on, or None")},
1315 {NULL} /* Sentinel */
1316};
1317
1318static PyMemberDef async_gen_memberlist[] = {
1319 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001320 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1321 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001322 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1323 {NULL} /* Sentinel */
1324};
1325
1326PyDoc_STRVAR(async_aclose_doc,
1327"aclose() -> raise GeneratorExit inside generator.");
1328
1329PyDoc_STRVAR(async_asend_doc,
1330"asend(v) -> send 'v' in generator.");
1331
1332PyDoc_STRVAR(async_athrow_doc,
1333"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1334
1335static PyMethodDef async_gen_methods[] = {
1336 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1337 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1338 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001339 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1340 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001341 {NULL, NULL} /* Sentinel */
1342};
1343
1344
1345static PyAsyncMethods async_gen_as_async = {
1346 0, /* am_await */
1347 PyObject_SelfIter, /* am_aiter */
1348 (unaryfunc)async_gen_anext /* am_anext */
1349};
1350
1351
1352PyTypeObject PyAsyncGen_Type = {
1353 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1354 "async_generator", /* tp_name */
1355 sizeof(PyAsyncGenObject), /* tp_basicsize */
1356 0, /* tp_itemsize */
1357 /* methods */
1358 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001359 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001360 0, /* tp_getattr */
1361 0, /* tp_setattr */
1362 &async_gen_as_async, /* tp_as_async */
1363 (reprfunc)async_gen_repr, /* tp_repr */
1364 0, /* tp_as_number */
1365 0, /* tp_as_sequence */
1366 0, /* tp_as_mapping */
1367 0, /* tp_hash */
1368 0, /* tp_call */
1369 0, /* tp_str */
1370 PyObject_GenericGetAttr, /* tp_getattro */
1371 0, /* tp_setattro */
1372 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001373 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001374 0, /* tp_doc */
1375 (traverseproc)async_gen_traverse, /* tp_traverse */
1376 0, /* tp_clear */
1377 0, /* tp_richcompare */
1378 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1379 0, /* tp_iter */
1380 0, /* tp_iternext */
1381 async_gen_methods, /* tp_methods */
1382 async_gen_memberlist, /* tp_members */
1383 async_gen_getsetlist, /* tp_getset */
1384 0, /* tp_base */
1385 0, /* tp_dict */
1386 0, /* tp_descr_get */
1387 0, /* tp_descr_set */
1388 0, /* tp_dictoffset */
1389 0, /* tp_init */
1390 0, /* tp_alloc */
1391 0, /* tp_new */
1392 0, /* tp_free */
1393 0, /* tp_is_gc */
1394 0, /* tp_bases */
1395 0, /* tp_mro */
1396 0, /* tp_cache */
1397 0, /* tp_subclasses */
1398 0, /* tp_weaklist */
1399 0, /* tp_del */
1400 0, /* tp_version_tag */
1401 _PyGen_Finalize, /* tp_finalize */
1402};
1403
1404
1405PyObject *
1406PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1407{
1408 PyAsyncGenObject *o;
1409 o = (PyAsyncGenObject *)gen_new_with_qualname(
1410 &PyAsyncGen_Type, f, name, qualname);
1411 if (o == NULL) {
1412 return NULL;
1413 }
1414 o->ag_finalizer = NULL;
1415 o->ag_closed = 0;
1416 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001417 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001418 return (PyObject*)o;
1419}
1420
1421
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001422void
1423_PyAsyncGen_ClearFreeLists(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001424{
Yury Selivanoveb636452016-09-08 22:01:51 -07001425 while (ag_value_freelist_free) {
1426 _PyAsyncGenWrappedValue *o;
1427 o = ag_value_freelist[--ag_value_freelist_free];
1428 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001429 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001430 }
1431
1432 while (ag_asend_freelist_free) {
1433 PyAsyncGenASend *o;
1434 o = ag_asend_freelist[--ag_asend_freelist_free];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001435 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001436 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001437 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001438}
1439
1440void
Victor Stinnerbed48172019-08-27 00:12:32 +02001441_PyAsyncGen_Fini(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001442{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001443 _PyAsyncGen_ClearFreeLists();
Yury Selivanoveb636452016-09-08 22:01:51 -07001444}
1445
1446
1447static PyObject *
1448async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1449{
1450 if (result == NULL) {
1451 if (!PyErr_Occurred()) {
1452 PyErr_SetNone(PyExc_StopAsyncIteration);
1453 }
1454
1455 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1456 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1457 ) {
1458 gen->ag_closed = 1;
1459 }
1460
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001461 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001462 return NULL;
1463 }
1464
1465 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1466 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001467 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001468 Py_DECREF(result);
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 return result;
1474}
1475
1476
1477/* ---------- Async Generator ASend Awaitable ------------ */
1478
1479
1480static void
1481async_gen_asend_dealloc(PyAsyncGenASend *o)
1482{
Yury Selivanov29310c42016-11-08 19:46:22 -05001483 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001484 Py_CLEAR(o->ags_gen);
1485 Py_CLEAR(o->ags_sendval);
1486 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1487 assert(PyAsyncGenASend_CheckExact(o));
1488 ag_asend_freelist[ag_asend_freelist_free++] = o;
1489 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001490 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001491 }
1492}
1493
Yury Selivanov29310c42016-11-08 19:46:22 -05001494static int
1495async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1496{
1497 Py_VISIT(o->ags_gen);
1498 Py_VISIT(o->ags_sendval);
1499 return 0;
1500}
1501
Yury Selivanoveb636452016-09-08 22:01:51 -07001502
1503static PyObject *
1504async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1505{
1506 PyObject *result;
1507
1508 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001509 PyErr_SetString(
1510 PyExc_RuntimeError,
1511 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001512 return NULL;
1513 }
1514
1515 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001516 if (o->ags_gen->ag_running_async) {
1517 PyErr_SetString(
1518 PyExc_RuntimeError,
1519 "anext(): asynchronous generator is already running");
1520 return NULL;
1521 }
1522
Yury Selivanoveb636452016-09-08 22:01:51 -07001523 if (arg == NULL || arg == Py_None) {
1524 arg = o->ags_sendval;
1525 }
1526 o->ags_state = AWAITABLE_STATE_ITER;
1527 }
1528
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001529 o->ags_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001530 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1531 result = async_gen_unwrap_value(o->ags_gen, result);
1532
1533 if (result == NULL) {
1534 o->ags_state = AWAITABLE_STATE_CLOSED;
1535 }
1536
1537 return result;
1538}
1539
1540
1541static PyObject *
1542async_gen_asend_iternext(PyAsyncGenASend *o)
1543{
1544 return async_gen_asend_send(o, NULL);
1545}
1546
1547
1548static PyObject *
1549async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1550{
1551 PyObject *result;
1552
1553 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001554 PyErr_SetString(
1555 PyExc_RuntimeError,
1556 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001557 return NULL;
1558 }
1559
1560 result = gen_throw((PyGenObject*)o->ags_gen, args);
1561 result = async_gen_unwrap_value(o->ags_gen, result);
1562
1563 if (result == NULL) {
1564 o->ags_state = AWAITABLE_STATE_CLOSED;
1565 }
1566
1567 return result;
1568}
1569
1570
1571static PyObject *
1572async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1573{
1574 o->ags_state = AWAITABLE_STATE_CLOSED;
1575 Py_RETURN_NONE;
1576}
1577
1578
1579static PyMethodDef async_gen_asend_methods[] = {
1580 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1581 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1582 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1583 {NULL, NULL} /* Sentinel */
1584};
1585
1586
1587static PyAsyncMethods async_gen_asend_as_async = {
1588 PyObject_SelfIter, /* am_await */
1589 0, /* am_aiter */
1590 0 /* am_anext */
1591};
1592
1593
1594PyTypeObject _PyAsyncGenASend_Type = {
1595 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1596 "async_generator_asend", /* tp_name */
1597 sizeof(PyAsyncGenASend), /* tp_basicsize */
1598 0, /* tp_itemsize */
1599 /* methods */
1600 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001601 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001602 0, /* tp_getattr */
1603 0, /* tp_setattr */
1604 &async_gen_asend_as_async, /* tp_as_async */
1605 0, /* tp_repr */
1606 0, /* tp_as_number */
1607 0, /* tp_as_sequence */
1608 0, /* tp_as_mapping */
1609 0, /* tp_hash */
1610 0, /* tp_call */
1611 0, /* tp_str */
1612 PyObject_GenericGetAttr, /* tp_getattro */
1613 0, /* tp_setattro */
1614 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001615 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001616 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001617 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001618 0, /* tp_clear */
1619 0, /* tp_richcompare */
1620 0, /* tp_weaklistoffset */
1621 PyObject_SelfIter, /* tp_iter */
1622 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1623 async_gen_asend_methods, /* tp_methods */
1624 0, /* tp_members */
1625 0, /* tp_getset */
1626 0, /* tp_base */
1627 0, /* tp_dict */
1628 0, /* tp_descr_get */
1629 0, /* tp_descr_set */
1630 0, /* tp_dictoffset */
1631 0, /* tp_init */
1632 0, /* tp_alloc */
1633 0, /* tp_new */
1634};
1635
1636
1637static PyObject *
1638async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1639{
1640 PyAsyncGenASend *o;
1641 if (ag_asend_freelist_free) {
1642 ag_asend_freelist_free--;
1643 o = ag_asend_freelist[ag_asend_freelist_free];
1644 _Py_NewReference((PyObject *)o);
1645 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001646 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001647 if (o == NULL) {
1648 return NULL;
1649 }
1650 }
1651
1652 Py_INCREF(gen);
1653 o->ags_gen = gen;
1654
1655 Py_XINCREF(sendval);
1656 o->ags_sendval = sendval;
1657
1658 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001659
1660 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001661 return (PyObject*)o;
1662}
1663
1664
1665/* ---------- Async Generator Value Wrapper ------------ */
1666
1667
1668static void
1669async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1670{
Yury Selivanov29310c42016-11-08 19:46:22 -05001671 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001672 Py_CLEAR(o->agw_val);
1673 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1674 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1675 ag_value_freelist[ag_value_freelist_free++] = o;
1676 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001677 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001678 }
1679}
1680
1681
Yury Selivanov29310c42016-11-08 19:46:22 -05001682static int
1683async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1684 visitproc visit, void *arg)
1685{
1686 Py_VISIT(o->agw_val);
1687 return 0;
1688}
1689
1690
Yury Selivanoveb636452016-09-08 22:01:51 -07001691PyTypeObject _PyAsyncGenWrappedValue_Type = {
1692 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1693 "async_generator_wrapped_value", /* tp_name */
1694 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1695 0, /* tp_itemsize */
1696 /* methods */
1697 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001698 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001699 0, /* tp_getattr */
1700 0, /* tp_setattr */
1701 0, /* tp_as_async */
1702 0, /* tp_repr */
1703 0, /* tp_as_number */
1704 0, /* tp_as_sequence */
1705 0, /* tp_as_mapping */
1706 0, /* tp_hash */
1707 0, /* tp_call */
1708 0, /* tp_str */
1709 PyObject_GenericGetAttr, /* tp_getattro */
1710 0, /* tp_setattro */
1711 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001712 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001713 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001714 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001715 0, /* tp_clear */
1716 0, /* tp_richcompare */
1717 0, /* tp_weaklistoffset */
1718 0, /* tp_iter */
1719 0, /* tp_iternext */
1720 0, /* tp_methods */
1721 0, /* tp_members */
1722 0, /* tp_getset */
1723 0, /* tp_base */
1724 0, /* tp_dict */
1725 0, /* tp_descr_get */
1726 0, /* tp_descr_set */
1727 0, /* tp_dictoffset */
1728 0, /* tp_init */
1729 0, /* tp_alloc */
1730 0, /* tp_new */
1731};
1732
1733
1734PyObject *
1735_PyAsyncGenValueWrapperNew(PyObject *val)
1736{
1737 _PyAsyncGenWrappedValue *o;
1738 assert(val);
1739
1740 if (ag_value_freelist_free) {
1741 ag_value_freelist_free--;
1742 o = ag_value_freelist[ag_value_freelist_free];
1743 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1744 _Py_NewReference((PyObject*)o);
1745 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001746 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1747 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001748 if (o == NULL) {
1749 return NULL;
1750 }
1751 }
1752 o->agw_val = val;
1753 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001754 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001755 return (PyObject*)o;
1756}
1757
1758
1759/* ---------- Async Generator AThrow awaitable ------------ */
1760
1761
1762static void
1763async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1764{
Yury Selivanov29310c42016-11-08 19:46:22 -05001765 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001766 Py_CLEAR(o->agt_gen);
1767 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001768 PyObject_GC_Del(o);
1769}
1770
1771
1772static int
1773async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1774{
1775 Py_VISIT(o->agt_gen);
1776 Py_VISIT(o->agt_args);
1777 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001778}
1779
1780
1781static PyObject *
1782async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1783{
1784 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1785 PyFrameObject *f = gen->gi_frame;
1786 PyObject *retval;
1787
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001788 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001789 PyErr_SetString(
1790 PyExc_RuntimeError,
1791 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001792 return NULL;
1793 }
1794
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001795 if (f == NULL || f->f_stacktop == NULL) {
1796 o->agt_state = AWAITABLE_STATE_CLOSED;
1797 PyErr_SetNone(PyExc_StopIteration);
1798 return NULL;
1799 }
1800
Yury Selivanoveb636452016-09-08 22:01:51 -07001801 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001802 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001803 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001804 if (o->agt_args == NULL) {
1805 PyErr_SetString(
1806 PyExc_RuntimeError,
1807 "aclose(): asynchronous generator is already running");
1808 }
1809 else {
1810 PyErr_SetString(
1811 PyExc_RuntimeError,
1812 "athrow(): asynchronous generator is already running");
1813 }
1814 return NULL;
1815 }
1816
Yury Selivanoveb636452016-09-08 22:01:51 -07001817 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001818 o->agt_state = AWAITABLE_STATE_CLOSED;
1819 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001820 return NULL;
1821 }
1822
1823 if (arg != Py_None) {
1824 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1825 return NULL;
1826 }
1827
1828 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001829 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001830
1831 if (o->agt_args == NULL) {
1832 /* aclose() mode */
1833 o->agt_gen->ag_closed = 1;
1834
1835 retval = _gen_throw((PyGenObject *)gen,
1836 0, /* Do not close generator when
1837 PyExc_GeneratorExit is passed */
1838 PyExc_GeneratorExit, NULL, NULL);
1839
1840 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1841 Py_DECREF(retval);
1842 goto yield_close;
1843 }
1844 } else {
1845 PyObject *typ;
1846 PyObject *tb = NULL;
1847 PyObject *val = NULL;
1848
1849 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1850 &typ, &val, &tb)) {
1851 return NULL;
1852 }
1853
1854 retval = _gen_throw((PyGenObject *)gen,
1855 0, /* Do not close generator when
1856 PyExc_GeneratorExit is passed */
1857 typ, val, tb);
1858 retval = async_gen_unwrap_value(o->agt_gen, retval);
1859 }
1860 if (retval == NULL) {
1861 goto check_error;
1862 }
1863 return retval;
1864 }
1865
1866 assert(o->agt_state == AWAITABLE_STATE_ITER);
1867
1868 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1869 if (o->agt_args) {
1870 return async_gen_unwrap_value(o->agt_gen, retval);
1871 } else {
1872 /* aclose() mode */
1873 if (retval) {
1874 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1875 Py_DECREF(retval);
1876 goto yield_close;
1877 }
1878 else {
1879 return retval;
1880 }
1881 }
1882 else {
1883 goto check_error;
1884 }
1885 }
1886
1887yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001888 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001889 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001890 PyErr_SetString(
1891 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1892 return NULL;
1893
1894check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001895 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001896 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001897 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1898 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1899 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001900 if (o->agt_args == NULL) {
1901 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001902 StopAsyncIteration or GeneratorExit; just raise
1903 StopIteration, signalling that this 'aclose()' await
1904 is done.
1905 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001906 PyErr_Clear();
1907 PyErr_SetNone(PyExc_StopIteration);
1908 }
1909 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001910 return NULL;
1911}
1912
1913
1914static PyObject *
1915async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1916{
1917 PyObject *retval;
1918
Yury Selivanoveb636452016-09-08 22:01:51 -07001919 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001920 PyErr_SetString(
1921 PyExc_RuntimeError,
1922 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001923 return NULL;
1924 }
1925
1926 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1927 if (o->agt_args) {
1928 return async_gen_unwrap_value(o->agt_gen, retval);
1929 } else {
1930 /* aclose() mode */
1931 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001932 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001933 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001934 Py_DECREF(retval);
1935 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1936 return NULL;
1937 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08001938 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1939 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1940 {
1941 /* when aclose() is called we don't want to propagate
1942 StopAsyncIteration or GeneratorExit; just raise
1943 StopIteration, signalling that this 'aclose()' await
1944 is done.
1945 */
1946 PyErr_Clear();
1947 PyErr_SetNone(PyExc_StopIteration);
1948 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001949 return retval;
1950 }
1951}
1952
1953
1954static PyObject *
1955async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1956{
1957 return async_gen_athrow_send(o, Py_None);
1958}
1959
1960
1961static PyObject *
1962async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1963{
1964 o->agt_state = AWAITABLE_STATE_CLOSED;
1965 Py_RETURN_NONE;
1966}
1967
1968
1969static PyMethodDef async_gen_athrow_methods[] = {
1970 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1971 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1972 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1973 {NULL, NULL} /* Sentinel */
1974};
1975
1976
1977static PyAsyncMethods async_gen_athrow_as_async = {
1978 PyObject_SelfIter, /* am_await */
1979 0, /* am_aiter */
1980 0 /* am_anext */
1981};
1982
1983
1984PyTypeObject _PyAsyncGenAThrow_Type = {
1985 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1986 "async_generator_athrow", /* tp_name */
1987 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1988 0, /* tp_itemsize */
1989 /* methods */
1990 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001991 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001992 0, /* tp_getattr */
1993 0, /* tp_setattr */
1994 &async_gen_athrow_as_async, /* tp_as_async */
1995 0, /* tp_repr */
1996 0, /* tp_as_number */
1997 0, /* tp_as_sequence */
1998 0, /* tp_as_mapping */
1999 0, /* tp_hash */
2000 0, /* tp_call */
2001 0, /* tp_str */
2002 PyObject_GenericGetAttr, /* tp_getattro */
2003 0, /* tp_setattro */
2004 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002005 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002006 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002007 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002008 0, /* tp_clear */
2009 0, /* tp_richcompare */
2010 0, /* tp_weaklistoffset */
2011 PyObject_SelfIter, /* tp_iter */
2012 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2013 async_gen_athrow_methods, /* tp_methods */
2014 0, /* tp_members */
2015 0, /* tp_getset */
2016 0, /* tp_base */
2017 0, /* tp_dict */
2018 0, /* tp_descr_get */
2019 0, /* tp_descr_set */
2020 0, /* tp_dictoffset */
2021 0, /* tp_init */
2022 0, /* tp_alloc */
2023 0, /* tp_new */
2024};
2025
2026
2027static PyObject *
2028async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2029{
2030 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002031 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002032 if (o == NULL) {
2033 return NULL;
2034 }
2035 o->agt_gen = gen;
2036 o->agt_args = args;
2037 o->agt_state = AWAITABLE_STATE_INIT;
2038 Py_INCREF(gen);
2039 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002040 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002041 return (PyObject*)o;
2042}