blob: 72aa872c6b59f5d988a2481e9570a6c708bf9969 [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +01004#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pystate.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00006#include "frameobject.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00007#include "structmember.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00009
Yury Selivanoveb636452016-09-08 22:01:51 -070010static PyObject *gen_close(PyGenObject *, PyObject *);
11static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
12static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
13
14static char *NON_INIT_CORO_MSG = "can't send non-None value to a "
15 "just-started coroutine";
16
17static char *ASYNC_GEN_IGNORED_EXIT_MSG =
18 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100019
Mark Shannonae3087c2017-10-22 22:41:51 +010020static inline int
21exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
22{
23 Py_VISIT(exc_state->exc_type);
24 Py_VISIT(exc_state->exc_value);
25 Py_VISIT(exc_state->exc_traceback);
26 return 0;
27}
28
Martin v. Löwise440e472004-06-01 15:22:42 +000029static int
30gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
31{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 Py_VISIT((PyObject *)gen->gi_frame);
33 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020034 Py_VISIT(gen->gi_name);
35 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080036 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
37 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010038 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000039}
40
Antoine Pitrou58720d62013-08-05 23:26:40 +020041void
42_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020043{
44 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070045 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020046 PyObject *error_type, *error_value, *error_traceback;
47
Yury Selivanov2a2270d2018-01-29 14:31:47 -050048 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) {
Antoine Pitrou796564c2013-07-30 19:59:21 +020049 /* Generator isn't paused, so no need to close */
50 return;
Yury Selivanov2a2270d2018-01-29 14:31:47 -050051 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020052
Yury Selivanoveb636452016-09-08 22:01:51 -070053 if (PyAsyncGen_CheckExact(self)) {
54 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
55 PyObject *finalizer = agen->ag_finalizer;
56 if (finalizer && !agen->ag_closed) {
57 /* Save the current exception, if any. */
58 PyErr_Fetch(&error_type, &error_value, &error_traceback);
59
Victor Stinnerde4ae3d2016-12-04 22:59:09 +010060 res = PyObject_CallFunctionObjArgs(finalizer, self, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -070061
62 if (res == NULL) {
63 PyErr_WriteUnraisable(self);
64 } else {
65 Py_DECREF(res);
66 }
67 /* Restore the saved exception. */
68 PyErr_Restore(error_type, error_value, error_traceback);
69 return;
70 }
71 }
72
Antoine Pitrou796564c2013-07-30 19:59:21 +020073 /* Save the current exception, if any. */
74 PyErr_Fetch(&error_type, &error_value, &error_traceback);
75
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070076 /* If `gen` is a coroutine, and if it was never awaited on,
77 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070078 if (gen->gi_code != NULL &&
79 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
Yury Selivanov2a2270d2018-01-29 14:31:47 -050080 gen->gi_frame->f_lasti == -1)
81 {
82 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070083 }
84 else {
85 res = gen_close(gen, NULL);
86 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020087
Benjamin Petersonb88db872016-09-07 08:46:59 -070088 if (res == NULL) {
Yury Selivanov2a2270d2018-01-29 14:31:47 -050089 if (PyErr_Occurred()) {
Benjamin Petersonb88db872016-09-07 08:46:59 -070090 PyErr_WriteUnraisable(self);
Yury Selivanov2a2270d2018-01-29 14:31:47 -050091 }
Benjamin Petersonb88db872016-09-07 08:46:59 -070092 }
93 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020094 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070095 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020096
97 /* Restore the saved exception. */
98 PyErr_Restore(error_type, error_value, error_traceback);
99}
100
Mark Shannonae3087c2017-10-22 22:41:51 +0100101static inline void
102exc_state_clear(_PyErr_StackItem *exc_state)
103{
104 PyObject *t, *v, *tb;
105 t = exc_state->exc_type;
106 v = exc_state->exc_value;
107 tb = exc_state->exc_traceback;
108 exc_state->exc_type = NULL;
109 exc_state->exc_value = NULL;
110 exc_state->exc_traceback = NULL;
111 Py_XDECREF(t);
112 Py_XDECREF(v);
113 Py_XDECREF(tb);
114}
115
Antoine Pitrou796564c2013-07-30 19:59:21 +0200116static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000117gen_dealloc(PyGenObject *gen)
118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (gen->gi_weakreflist != NULL)
124 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000125
Antoine Pitrou93963562013-05-14 20:37:52 +0200126 _PyObject_GC_TRACK(self);
127
Antoine Pitrou796564c2013-07-30 19:59:21 +0200128 if (PyObject_CallFinalizerFromDealloc(self))
129 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200130
131 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700132 if (PyAsyncGen_CheckExact(gen)) {
133 /* We have to handle this case for asynchronous generators
134 right here, because this code has to be between UNTRACK
135 and GC_Del. */
136 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
137 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700138 if (gen->gi_frame != NULL) {
139 gen->gi_frame->f_gen = NULL;
140 Py_CLEAR(gen->gi_frame);
141 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800142 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
143 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200146 Py_CLEAR(gen->gi_name);
147 Py_CLEAR(gen->gi_qualname);
Mark Shannonae3087c2017-10-22 22:41:51 +0100148 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000150}
151
152static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500153gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000154{
Victor Stinner50b48572018-11-01 01:51:40 +0100155 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200157 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000158
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500159 if (gen->gi_running) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200160 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700161 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400162 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700163 }
164 else if (PyAsyncGen_CheckExact(gen)) {
165 msg = "async generator already executing";
166 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400167 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500168 return NULL;
169 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200170 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500171 if (PyCoro_CheckExact(gen) && !closing) {
172 /* `gen` is an exhausted coroutine: raise an error,
173 except when called from gen_close(), which should
174 always be a silent method. */
175 PyErr_SetString(
176 PyExc_RuntimeError,
177 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700178 }
179 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500180 /* `gen` is an exhausted generator:
181 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700182 if (PyAsyncGen_CheckExact(gen)) {
183 PyErr_SetNone(PyExc_StopAsyncIteration);
184 }
185 else {
186 PyErr_SetNone(PyExc_StopIteration);
187 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500188 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 return NULL;
190 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000191
Antoine Pitrou93963562013-05-14 20:37:52 +0200192 if (f->f_lasti == -1) {
193 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200194 const char *msg = "can't send non-None value to a "
195 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700196 if (PyCoro_CheckExact(gen)) {
197 msg = NON_INIT_CORO_MSG;
198 }
199 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400200 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700201 "just-started async generator";
202 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400203 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200204 return NULL;
205 }
206 } else {
207 /* Push arg onto the frame's value stack */
208 result = arg ? arg : Py_None;
209 Py_INCREF(result);
210 *(f->f_stacktop++) = result;
211 }
212
213 /* Generators always return to their most recent caller, not
214 * necessarily their creator. */
215 Py_XINCREF(tstate->frame);
216 assert(f->f_back == NULL);
217 f->f_back = tstate->frame;
218
219 gen->gi_running = 1;
Mark Shannonae3087c2017-10-22 22:41:51 +0100220 gen->gi_exc_state.previous_item = tstate->exc_info;
221 tstate->exc_info = &gen->gi_exc_state;
Victor Stinner59a73272016-12-09 18:51:13 +0100222 result = PyEval_EvalFrameEx(f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100223 tstate->exc_info = gen->gi_exc_state.previous_item;
224 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200225 gen->gi_running = 0;
226
227 /* Don't keep the reference to f_back any longer than necessary. It
228 * may keep a chain of frames alive or it could create a reference
229 * cycle. */
230 assert(f->f_back == tstate->frame);
231 Py_CLEAR(f->f_back);
232
233 /* If the generator just returned (as opposed to yielding), signal
234 * that the generator is exhausted. */
235 if (result && f->f_stacktop == NULL) {
236 if (result == Py_None) {
237 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700238 if (PyAsyncGen_CheckExact(gen)) {
239 PyErr_SetNone(PyExc_StopAsyncIteration);
240 }
241 else {
242 PyErr_SetNone(PyExc_StopIteration);
243 }
244 }
245 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700246 /* Async generators cannot return anything but None */
247 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200248 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200249 }
250 Py_CLEAR(result);
251 }
Yury Selivanov68333392015-05-22 11:16:47 -0400252 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500253 const char *msg = "generator raised StopIteration";
254 if (PyCoro_CheckExact(gen)) {
255 msg = "coroutine raised StopIteration";
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400256 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500257 else if PyAsyncGen_CheckExact(gen) {
258 msg = "async generator raised StopIteration";
Yury Selivanov68333392015-05-22 11:16:47 -0400259 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500260 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
261
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400262 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500263 else if (!result && PyAsyncGen_CheckExact(gen) &&
Yury Selivanoveb636452016-09-08 22:01:51 -0700264 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
265 {
266 /* code in `gen` raised a StopAsyncIteration error:
267 raise a RuntimeError.
268 */
269 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300270 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700271 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200272
273 if (!result || f->f_stacktop == NULL) {
274 /* generator can't be rerun, so release the frame */
275 /* first clean reference cycle through stored exception traceback */
Mark Shannonae3087c2017-10-22 22:41:51 +0100276 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200277 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200278 gen->gi_frame = NULL;
279 Py_DECREF(f);
280 }
281
282 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000283}
284
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000285PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286"send(arg) -> send 'arg' into generator,\n\
287return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000288
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500289PyObject *
290_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000291{
Yury Selivanov77c96812016-02-13 17:59:05 -0500292 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000293}
294
295PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400296"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000297
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000298/*
299 * This helper function is used by gen_close and gen_throw to
300 * close a subiterator being delegated to by yield-from.
301 */
302
Antoine Pitrou93963562013-05-14 20:37:52 +0200303static int
304gen_close_iter(PyObject *yf)
305{
306 PyObject *retval = NULL;
307 _Py_IDENTIFIER(close);
308
Yury Selivanoveb636452016-09-08 22:01:51 -0700309 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200310 retval = gen_close((PyGenObject *)yf, NULL);
311 if (retval == NULL)
312 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700313 }
314 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200315 PyObject *meth;
316 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
317 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700318 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200319 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700320 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200321 Py_DECREF(meth);
322 if (retval == NULL)
323 return -1;
324 }
325 }
326 Py_XDECREF(retval);
327 return 0;
328}
329
Yury Selivanovc724bae2016-03-02 11:30:46 -0500330PyObject *
331_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500332{
Antoine Pitrou93963562013-05-14 20:37:52 +0200333 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500334 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200335
336 if (f && f->f_stacktop) {
337 PyObject *bytecode = f->f_code->co_code;
338 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
339
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100340 if (f->f_lasti < 0) {
341 /* Return immediately if the frame didn't start yet. YIELD_FROM
342 always come after LOAD_CONST: a code object should not start
343 with YIELD_FROM */
344 assert(code[0] != YIELD_FROM);
345 return NULL;
346 }
347
Serhiy Storchakaab874002016-09-11 13:48:15 +0300348 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200349 return NULL;
350 yf = f->f_stacktop[-1];
351 Py_INCREF(yf);
352 }
353
354 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500355}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000356
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000357static PyObject *
358gen_close(PyGenObject *gen, PyObject *args)
359{
Antoine Pitrou93963562013-05-14 20:37:52 +0200360 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500361 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200362 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000363
Antoine Pitrou93963562013-05-14 20:37:52 +0200364 if (yf) {
365 gen->gi_running = 1;
366 err = gen_close_iter(yf);
367 gen->gi_running = 0;
368 Py_DECREF(yf);
369 }
370 if (err == 0)
371 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500372 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200373 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200374 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700375 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400376 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700377 } else if (PyAsyncGen_CheckExact(gen)) {
378 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
379 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200380 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400381 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 return NULL;
383 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200384 if (PyErr_ExceptionMatches(PyExc_StopIteration)
385 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
386 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200387 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200388 }
389 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000390}
391
Antoine Pitrou93963562013-05-14 20:37:52 +0200392
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000393PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000394"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
395return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000396
397static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700398_gen_throw(PyGenObject *gen, int close_on_genexit,
399 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000400{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500401 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000402 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000403
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000404 if (yf) {
405 PyObject *ret;
406 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700407 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
408 close_on_genexit
409 ) {
410 /* Asynchronous generators *should not* be closed right away.
411 We have to allow some awaits to work it through, hence the
412 `close_on_genexit` parameter here.
413 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500414 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200415 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500416 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000417 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000418 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500419 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000420 goto throw_here;
421 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700422 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
423 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500424 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700425 /* Close the generator that we are currently iterating with
426 'yield from' or awaiting on with 'await'. */
427 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
428 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500429 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000430 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700431 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200432 PyObject *meth;
433 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
434 Py_DECREF(yf);
435 return NULL;
436 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000437 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000439 goto throw_here;
440 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500441 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700442 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500443 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000444 Py_DECREF(meth);
445 }
446 Py_DECREF(yf);
447 if (!ret) {
448 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500449 /* Pop subiterator from stack */
450 ret = *(--gen->gi_frame->f_stacktop);
451 assert(ret == yf);
452 Py_DECREF(ret);
453 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100454 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300455 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000456 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500457 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000458 Py_DECREF(val);
459 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500460 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000461 }
462 }
463 return ret;
464 }
465
466throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* First, check the traceback argument, replacing None with
468 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400469 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400471 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 else if (tb != NULL && !PyTraceBack_Check(tb)) {
473 PyErr_SetString(PyExc_TypeError,
474 "throw() third argument must be a traceback object");
475 return NULL;
476 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Py_INCREF(typ);
479 Py_XINCREF(val);
480 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000481
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400482 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 else if (PyExceptionInstance_Check(typ)) {
486 /* Raising an instance. The value should be a dummy. */
487 if (val && val != Py_None) {
488 PyErr_SetString(PyExc_TypeError,
489 "instance exception may not have a separate value");
490 goto failed_throw;
491 }
492 else {
493 /* Normalize to raise <class>, <instance> */
494 Py_XDECREF(val);
495 val = typ;
496 typ = PyExceptionInstance_Class(typ);
497 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200498
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400499 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200500 /* Returns NULL if there's no traceback */
501 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
503 }
504 else {
505 /* Not something you can raise. throw() fails. */
506 PyErr_Format(PyExc_TypeError,
507 "exceptions must be classes or instances "
508 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000509 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 goto failed_throw;
511 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500514 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000515
516failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Didn't use our arguments, so restore their original refcounts */
518 Py_DECREF(typ);
519 Py_XDECREF(val);
520 Py_XDECREF(tb);
521 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000522}
523
524
525static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700526gen_throw(PyGenObject *gen, PyObject *args)
527{
528 PyObject *typ;
529 PyObject *tb = NULL;
530 PyObject *val = NULL;
531
532 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
533 return NULL;
534 }
535
536 return _gen_throw(gen, 1, typ, val, tb);
537}
538
539
540static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000541gen_iternext(PyGenObject *gen)
542{
Yury Selivanov77c96812016-02-13 17:59:05 -0500543 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000544}
545
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000546/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200547 * Set StopIteration with specified value. Value can be arbitrary object
548 * or NULL.
549 *
550 * Returns 0 if StopIteration is set and -1 if any other exception is set.
551 */
552int
553_PyGen_SetStopIterationValue(PyObject *value)
554{
555 PyObject *e;
556
557 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400558 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200559 {
560 /* Delay exception instantiation if we can */
561 PyErr_SetObject(PyExc_StopIteration, value);
562 return 0;
563 }
564 /* Construct an exception instance manually with
565 * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject.
566 *
567 * We do this to handle a situation when "value" is a tuple, in which
568 * case PyErr_SetObject would set the value of StopIteration to
569 * the first element of the tuple.
570 *
571 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
572 */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100573 e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200574 if (e == NULL) {
575 return -1;
576 }
577 PyErr_SetObject(PyExc_StopIteration, e);
578 Py_DECREF(e);
579 return 0;
580}
581
582/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000583 * If StopIteration exception is set, fetches its 'value'
584 * attribute if any, otherwise sets pvalue to None.
585 *
586 * Returns 0 if no exception or StopIteration is set.
587 * If any other exception is set, returns -1 and leaves
588 * pvalue unchanged.
589 */
590
591int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200592_PyGen_FetchStopIterationValue(PyObject **pvalue)
593{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000594 PyObject *et, *ev, *tb;
595 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500596
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000597 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
598 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200599 if (ev) {
600 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300601 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200602 value = ((PyStopIterationObject *)ev)->value;
603 Py_INCREF(value);
604 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200605 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
606 /* Avoid normalisation and take ev as value.
607 *
608 * Normalization is required if the value is a tuple, in
609 * that case the value of StopIteration would be set to
610 * the first element of the tuple.
611 *
612 * (See _PyErr_CreateException code for details.)
613 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200614 value = ev;
615 } else {
616 /* normalisation required */
617 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300618 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200619 PyErr_Restore(et, ev, tb);
620 return -1;
621 }
622 value = ((PyStopIterationObject *)ev)->value;
623 Py_INCREF(value);
624 Py_DECREF(ev);
625 }
626 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000627 Py_XDECREF(et);
628 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000629 } else if (PyErr_Occurred()) {
630 return -1;
631 }
632 if (value == NULL) {
633 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100634 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000635 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000636 *pvalue = value;
637 return 0;
638}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000639
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000640static PyObject *
641gen_repr(PyGenObject *gen)
642{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400643 return PyUnicode_FromFormat("<generator object %S at %p>",
644 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000645}
646
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000647static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200648gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000649{
Victor Stinner40ee3012014-06-16 15:59:28 +0200650 Py_INCREF(op->gi_name);
651 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000652}
653
Victor Stinner40ee3012014-06-16 15:59:28 +0200654static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200655gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200656{
Victor Stinner40ee3012014-06-16 15:59:28 +0200657 /* Not legal to del gen.gi_name or to set it to anything
658 * other than a string object. */
659 if (value == NULL || !PyUnicode_Check(value)) {
660 PyErr_SetString(PyExc_TypeError,
661 "__name__ must be set to a string object");
662 return -1;
663 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200664 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300665 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200666 return 0;
667}
668
669static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200670gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200671{
672 Py_INCREF(op->gi_qualname);
673 return op->gi_qualname;
674}
675
676static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200677gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200678{
Victor Stinner40ee3012014-06-16 15:59:28 +0200679 /* Not legal to del gen.__qualname__ or to set it to anything
680 * other than a string object. */
681 if (value == NULL || !PyUnicode_Check(value)) {
682 PyErr_SetString(PyExc_TypeError,
683 "__qualname__ must be set to a string object");
684 return -1;
685 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200686 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300687 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200688 return 0;
689}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000690
Yury Selivanove13f8f32015-07-03 00:23:30 -0400691static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200692gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400693{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500694 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400695 if (yf == NULL)
696 Py_RETURN_NONE;
697 return yf;
698}
699
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000700static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200701 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
702 PyDoc_STR("name of the generator")},
703 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
704 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400705 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
706 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200707 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000708};
709
Martin v. Löwise440e472004-06-01 15:22:42 +0000710static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200711 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
712 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
713 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000715};
716
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000717static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500718 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
720 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
721 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000722};
723
Martin v. Löwise440e472004-06-01 15:22:42 +0000724PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyVarObject_HEAD_INIT(&PyType_Type, 0)
726 "generator", /* tp_name */
727 sizeof(PyGenObject), /* tp_basicsize */
728 0, /* tp_itemsize */
729 /* methods */
730 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200731 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 0, /* tp_getattr */
733 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400734 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 (reprfunc)gen_repr, /* tp_repr */
736 0, /* tp_as_number */
737 0, /* tp_as_sequence */
738 0, /* tp_as_mapping */
739 0, /* tp_hash */
740 0, /* tp_call */
741 0, /* tp_str */
742 PyObject_GenericGetAttr, /* tp_getattro */
743 0, /* tp_setattro */
744 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200745 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 0, /* tp_doc */
747 (traverseproc)gen_traverse, /* tp_traverse */
748 0, /* tp_clear */
749 0, /* tp_richcompare */
750 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400751 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 (iternextfunc)gen_iternext, /* tp_iternext */
753 gen_methods, /* tp_methods */
754 gen_memberlist, /* tp_members */
755 gen_getsetlist, /* tp_getset */
756 0, /* tp_base */
757 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 0, /* tp_descr_get */
760 0, /* tp_descr_set */
761 0, /* tp_dictoffset */
762 0, /* tp_init */
763 0, /* tp_alloc */
764 0, /* tp_new */
765 0, /* tp_free */
766 0, /* tp_is_gc */
767 0, /* tp_bases */
768 0, /* tp_mro */
769 0, /* tp_cache */
770 0, /* tp_subclasses */
771 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200772 0, /* tp_del */
773 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200774 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000775};
776
Yury Selivanov5376ba92015-06-22 12:19:30 -0400777static PyObject *
778gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
779 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000780{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400781 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (gen == NULL) {
783 Py_DECREF(f);
784 return NULL;
785 }
786 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200787 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_INCREF(f->f_code);
789 gen->gi_code = (PyObject *)(f->f_code);
790 gen->gi_running = 0;
791 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100792 gen->gi_exc_state.exc_type = NULL;
793 gen->gi_exc_state.exc_value = NULL;
794 gen->gi_exc_state.exc_traceback = NULL;
795 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200796 if (name != NULL)
797 gen->gi_name = name;
798 else
799 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
800 Py_INCREF(gen->gi_name);
801 if (qualname != NULL)
802 gen->gi_qualname = qualname;
803 else
804 gen->gi_qualname = gen->gi_name;
805 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 _PyObject_GC_TRACK(gen);
807 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000808}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809
Victor Stinner40ee3012014-06-16 15:59:28 +0200810PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400811PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
812{
813 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
814}
815
816PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200817PyGen_New(PyFrameObject *f)
818{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400819 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200820}
821
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822int
823PyGen_NeedsFinalizing(PyGenObject *gen)
824{
Antoine Pitrou93963562013-05-14 20:37:52 +0200825 PyFrameObject *f = gen->gi_frame;
826
827 if (f == NULL || f->f_stacktop == NULL)
828 return 0; /* no frame or empty blockstack == no finalization */
829
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200830 /* Any (exception-handling) block type requires cleanup. */
831 if (f->f_iblock > 0)
832 return 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200833
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200834 /* No blocks, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836}
Yury Selivanov75445082015-05-11 22:57:16 -0400837
Yury Selivanov5376ba92015-06-22 12:19:30 -0400838/* Coroutine Object */
839
840typedef struct {
841 PyObject_HEAD
842 PyCoroObject *cw_coroutine;
843} PyCoroWrapper;
844
845static int
846gen_is_coroutine(PyObject *o)
847{
848 if (PyGen_CheckExact(o)) {
849 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
850 if (code->co_flags & CO_ITERABLE_COROUTINE) {
851 return 1;
852 }
853 }
854 return 0;
855}
856
Yury Selivanov75445082015-05-11 22:57:16 -0400857/*
858 * This helper function returns an awaitable for `o`:
859 * - `o` if `o` is a coroutine-object;
860 * - `type(o)->tp_as_async->am_await(o)`
861 *
862 * Raises a TypeError if it's not possible to return
863 * an awaitable and returns NULL.
864 */
865PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400866_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400867{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400868 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400869 PyTypeObject *ot;
870
Yury Selivanov5376ba92015-06-22 12:19:30 -0400871 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
872 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400873 Py_INCREF(o);
874 return o;
875 }
876
877 ot = Py_TYPE(o);
878 if (ot->tp_as_async != NULL) {
879 getter = ot->tp_as_async->am_await;
880 }
881 if (getter != NULL) {
882 PyObject *res = (*getter)(o);
883 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400884 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
885 /* __await__ must return an *iterator*, not
886 a coroutine or another awaitable (see PEP 492) */
887 PyErr_SetString(PyExc_TypeError,
888 "__await__() returned a coroutine");
889 Py_CLEAR(res);
890 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400891 PyErr_Format(PyExc_TypeError,
892 "__await__() returned non-iterator "
893 "of type '%.100s'",
894 Py_TYPE(res)->tp_name);
895 Py_CLEAR(res);
896 }
Yury Selivanov75445082015-05-11 22:57:16 -0400897 }
898 return res;
899 }
900
901 PyErr_Format(PyExc_TypeError,
902 "object %.100s can't be used in 'await' expression",
903 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400904 return NULL;
905}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400906
907static PyObject *
908coro_repr(PyCoroObject *coro)
909{
910 return PyUnicode_FromFormat("<coroutine object %S at %p>",
911 coro->cr_qualname, coro);
912}
913
914static PyObject *
915coro_await(PyCoroObject *coro)
916{
917 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
918 if (cw == NULL) {
919 return NULL;
920 }
921 Py_INCREF(coro);
922 cw->cw_coroutine = coro;
923 _PyObject_GC_TRACK(cw);
924 return (PyObject *)cw;
925}
926
Yury Selivanove13f8f32015-07-03 00:23:30 -0400927static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200928coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400929{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500930 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400931 if (yf == NULL)
932 Py_RETURN_NONE;
933 return yf;
934}
935
Yury Selivanov5376ba92015-06-22 12:19:30 -0400936static PyGetSetDef coro_getsetlist[] = {
937 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
938 PyDoc_STR("name of the coroutine")},
939 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
940 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400941 {"cr_await", (getter)coro_get_cr_await, NULL,
942 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400943 {NULL} /* Sentinel */
944};
945
946static PyMemberDef coro_memberlist[] = {
947 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
948 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
949 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800950 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400951 {NULL} /* Sentinel */
952};
953
954PyDoc_STRVAR(coro_send_doc,
955"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400956return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400957
958PyDoc_STRVAR(coro_throw_doc,
959"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400960return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400961
962PyDoc_STRVAR(coro_close_doc,
963"close() -> raise GeneratorExit inside coroutine.");
964
965static PyMethodDef coro_methods[] = {
966 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
967 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
968 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
969 {NULL, NULL} /* Sentinel */
970};
971
972static PyAsyncMethods coro_as_async = {
973 (unaryfunc)coro_await, /* am_await */
974 0, /* am_aiter */
975 0 /* am_anext */
976};
977
978PyTypeObject PyCoro_Type = {
979 PyVarObject_HEAD_INIT(&PyType_Type, 0)
980 "coroutine", /* tp_name */
981 sizeof(PyCoroObject), /* tp_basicsize */
982 0, /* tp_itemsize */
983 /* methods */
984 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200985 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400986 0, /* tp_getattr */
987 0, /* tp_setattr */
988 &coro_as_async, /* tp_as_async */
989 (reprfunc)coro_repr, /* tp_repr */
990 0, /* tp_as_number */
991 0, /* tp_as_sequence */
992 0, /* tp_as_mapping */
993 0, /* tp_hash */
994 0, /* tp_call */
995 0, /* tp_str */
996 PyObject_GenericGetAttr, /* tp_getattro */
997 0, /* tp_setattro */
998 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200999 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001000 0, /* tp_doc */
1001 (traverseproc)gen_traverse, /* tp_traverse */
1002 0, /* tp_clear */
1003 0, /* tp_richcompare */
1004 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1005 0, /* tp_iter */
1006 0, /* tp_iternext */
1007 coro_methods, /* tp_methods */
1008 coro_memberlist, /* tp_members */
1009 coro_getsetlist, /* tp_getset */
1010 0, /* tp_base */
1011 0, /* tp_dict */
1012 0, /* tp_descr_get */
1013 0, /* tp_descr_set */
1014 0, /* tp_dictoffset */
1015 0, /* tp_init */
1016 0, /* tp_alloc */
1017 0, /* tp_new */
1018 0, /* tp_free */
1019 0, /* tp_is_gc */
1020 0, /* tp_bases */
1021 0, /* tp_mro */
1022 0, /* tp_cache */
1023 0, /* tp_subclasses */
1024 0, /* tp_weaklist */
1025 0, /* tp_del */
1026 0, /* tp_version_tag */
1027 _PyGen_Finalize, /* tp_finalize */
1028};
1029
1030static void
1031coro_wrapper_dealloc(PyCoroWrapper *cw)
1032{
1033 _PyObject_GC_UNTRACK((PyObject *)cw);
1034 Py_CLEAR(cw->cw_coroutine);
1035 PyObject_GC_Del(cw);
1036}
1037
1038static PyObject *
1039coro_wrapper_iternext(PyCoroWrapper *cw)
1040{
Yury Selivanov77c96812016-02-13 17:59:05 -05001041 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001042}
1043
1044static PyObject *
1045coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1046{
Yury Selivanov77c96812016-02-13 17:59:05 -05001047 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001048}
1049
1050static PyObject *
1051coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1052{
1053 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1054}
1055
1056static PyObject *
1057coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1058{
1059 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1060}
1061
1062static int
1063coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1064{
1065 Py_VISIT((PyObject *)cw->cw_coroutine);
1066 return 0;
1067}
1068
1069static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001070 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1071 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1072 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001073 {NULL, NULL} /* Sentinel */
1074};
1075
1076PyTypeObject _PyCoroWrapper_Type = {
1077 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1078 "coroutine_wrapper",
1079 sizeof(PyCoroWrapper), /* tp_basicsize */
1080 0, /* tp_itemsize */
1081 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001082 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001083 0, /* tp_getattr */
1084 0, /* tp_setattr */
1085 0, /* tp_as_async */
1086 0, /* tp_repr */
1087 0, /* tp_as_number */
1088 0, /* tp_as_sequence */
1089 0, /* tp_as_mapping */
1090 0, /* tp_hash */
1091 0, /* tp_call */
1092 0, /* tp_str */
1093 PyObject_GenericGetAttr, /* tp_getattro */
1094 0, /* tp_setattro */
1095 0, /* tp_as_buffer */
1096 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1097 "A wrapper object implementing __await__ for coroutines.",
1098 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1099 0, /* tp_clear */
1100 0, /* tp_richcompare */
1101 0, /* tp_weaklistoffset */
1102 PyObject_SelfIter, /* tp_iter */
1103 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1104 coro_wrapper_methods, /* tp_methods */
1105 0, /* tp_members */
1106 0, /* tp_getset */
1107 0, /* tp_base */
1108 0, /* tp_dict */
1109 0, /* tp_descr_get */
1110 0, /* tp_descr_set */
1111 0, /* tp_dictoffset */
1112 0, /* tp_init */
1113 0, /* tp_alloc */
1114 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001115 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001116};
1117
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001118static PyObject *
1119compute_cr_origin(int origin_depth)
1120{
1121 PyFrameObject *frame = PyEval_GetFrame();
1122 /* First count how many frames we have */
1123 int frame_count = 0;
1124 for (; frame && frame_count < origin_depth; ++frame_count) {
1125 frame = frame->f_back;
1126 }
1127
1128 /* Now collect them */
1129 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001130 if (cr_origin == NULL) {
1131 return NULL;
1132 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001133 frame = PyEval_GetFrame();
1134 for (int i = 0; i < frame_count; ++i) {
1135 PyObject *frameinfo = Py_BuildValue(
1136 "OiO",
1137 frame->f_code->co_filename,
1138 PyFrame_GetLineNumber(frame),
1139 frame->f_code->co_name);
1140 if (!frameinfo) {
1141 Py_DECREF(cr_origin);
1142 return NULL;
1143 }
1144 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1145 frame = frame->f_back;
1146 }
1147
1148 return cr_origin;
1149}
1150
Yury Selivanov5376ba92015-06-22 12:19:30 -04001151PyObject *
1152PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1153{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001154 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1155 if (!coro) {
1156 return NULL;
1157 }
1158
Victor Stinner50b48572018-11-01 01:51:40 +01001159 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001160 int origin_depth = tstate->coroutine_origin_tracking_depth;
1161
1162 if (origin_depth == 0) {
1163 ((PyCoroObject *)coro)->cr_origin = NULL;
1164 } else {
1165 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001166 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001167 if (!cr_origin) {
1168 Py_DECREF(coro);
1169 return NULL;
1170 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001171 }
1172
1173 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001174}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001175
1176
Yury Selivanoveb636452016-09-08 22:01:51 -07001177/* ========= Asynchronous Generators ========= */
1178
1179
1180typedef enum {
1181 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1182 AWAITABLE_STATE_ITER, /* being iterated */
1183 AWAITABLE_STATE_CLOSED, /* closed */
1184} AwaitableState;
1185
1186
1187typedef struct {
1188 PyObject_HEAD
1189 PyAsyncGenObject *ags_gen;
1190
1191 /* Can be NULL, when in the __anext__() mode
1192 (equivalent of "asend(None)") */
1193 PyObject *ags_sendval;
1194
1195 AwaitableState ags_state;
1196} PyAsyncGenASend;
1197
1198
1199typedef struct {
1200 PyObject_HEAD
1201 PyAsyncGenObject *agt_gen;
1202
1203 /* Can be NULL, when in the "aclose()" mode
1204 (equivalent of "athrow(GeneratorExit)") */
1205 PyObject *agt_args;
1206
1207 AwaitableState agt_state;
1208} PyAsyncGenAThrow;
1209
1210
1211typedef struct {
1212 PyObject_HEAD
1213 PyObject *agw_val;
1214} _PyAsyncGenWrappedValue;
1215
1216
1217#ifndef _PyAsyncGen_MAXFREELIST
1218#define _PyAsyncGen_MAXFREELIST 80
1219#endif
1220
1221/* Freelists boost performance 6-10%; they also reduce memory
1222 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1223 are short-living objects that are instantiated for every
1224 __anext__ call.
1225*/
1226
1227static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1228static int ag_value_freelist_free = 0;
1229
1230static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1231static int ag_asend_freelist_free = 0;
1232
1233#define _PyAsyncGenWrappedValue_CheckExact(o) \
1234 (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type)
1235
1236#define PyAsyncGenASend_CheckExact(o) \
1237 (Py_TYPE(o) == &_PyAsyncGenASend_Type)
1238
1239
1240static int
1241async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1242{
1243 Py_VISIT(gen->ag_finalizer);
1244 return gen_traverse((PyGenObject*)gen, visit, arg);
1245}
1246
1247
1248static PyObject *
1249async_gen_repr(PyAsyncGenObject *o)
1250{
1251 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1252 o->ag_qualname, o);
1253}
1254
1255
1256static int
1257async_gen_init_hooks(PyAsyncGenObject *o)
1258{
1259 PyThreadState *tstate;
1260 PyObject *finalizer;
1261 PyObject *firstiter;
1262
1263 if (o->ag_hooks_inited) {
1264 return 0;
1265 }
1266
1267 o->ag_hooks_inited = 1;
1268
Victor Stinner50b48572018-11-01 01:51:40 +01001269 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001270
1271 finalizer = tstate->async_gen_finalizer;
1272 if (finalizer) {
1273 Py_INCREF(finalizer);
1274 o->ag_finalizer = finalizer;
1275 }
1276
1277 firstiter = tstate->async_gen_firstiter;
1278 if (firstiter) {
1279 PyObject *res;
1280
1281 Py_INCREF(firstiter);
Victor Stinner7bfb42d2016-12-05 17:04:32 +01001282 res = PyObject_CallFunctionObjArgs(firstiter, o, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -07001283 Py_DECREF(firstiter);
1284 if (res == NULL) {
1285 return 1;
1286 }
1287 Py_DECREF(res);
1288 }
1289
1290 return 0;
1291}
1292
1293
1294static PyObject *
1295async_gen_anext(PyAsyncGenObject *o)
1296{
1297 if (async_gen_init_hooks(o)) {
1298 return NULL;
1299 }
1300 return async_gen_asend_new(o, NULL);
1301}
1302
1303
1304static PyObject *
1305async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1306{
1307 if (async_gen_init_hooks(o)) {
1308 return NULL;
1309 }
1310 return async_gen_asend_new(o, arg);
1311}
1312
1313
1314static PyObject *
1315async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1316{
1317 if (async_gen_init_hooks(o)) {
1318 return NULL;
1319 }
1320 return async_gen_athrow_new(o, NULL);
1321}
1322
1323static PyObject *
1324async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1325{
1326 if (async_gen_init_hooks(o)) {
1327 return NULL;
1328 }
1329 return async_gen_athrow_new(o, args);
1330}
1331
1332
1333static PyGetSetDef async_gen_getsetlist[] = {
1334 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1335 PyDoc_STR("name of the async generator")},
1336 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1337 PyDoc_STR("qualified name of the async generator")},
1338 {"ag_await", (getter)coro_get_cr_await, NULL,
1339 PyDoc_STR("object being awaited on, or None")},
1340 {NULL} /* Sentinel */
1341};
1342
1343static PyMemberDef async_gen_memberlist[] = {
1344 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001345 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1346 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001347 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1348 {NULL} /* Sentinel */
1349};
1350
1351PyDoc_STRVAR(async_aclose_doc,
1352"aclose() -> raise GeneratorExit inside generator.");
1353
1354PyDoc_STRVAR(async_asend_doc,
1355"asend(v) -> send 'v' in generator.");
1356
1357PyDoc_STRVAR(async_athrow_doc,
1358"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1359
1360static PyMethodDef async_gen_methods[] = {
1361 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1362 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1363 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
1364 {NULL, NULL} /* Sentinel */
1365};
1366
1367
1368static PyAsyncMethods async_gen_as_async = {
1369 0, /* am_await */
1370 PyObject_SelfIter, /* am_aiter */
1371 (unaryfunc)async_gen_anext /* am_anext */
1372};
1373
1374
1375PyTypeObject PyAsyncGen_Type = {
1376 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1377 "async_generator", /* tp_name */
1378 sizeof(PyAsyncGenObject), /* tp_basicsize */
1379 0, /* tp_itemsize */
1380 /* methods */
1381 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001382 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001383 0, /* tp_getattr */
1384 0, /* tp_setattr */
1385 &async_gen_as_async, /* tp_as_async */
1386 (reprfunc)async_gen_repr, /* tp_repr */
1387 0, /* tp_as_number */
1388 0, /* tp_as_sequence */
1389 0, /* tp_as_mapping */
1390 0, /* tp_hash */
1391 0, /* tp_call */
1392 0, /* tp_str */
1393 PyObject_GenericGetAttr, /* tp_getattro */
1394 0, /* tp_setattro */
1395 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001396 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001397 0, /* tp_doc */
1398 (traverseproc)async_gen_traverse, /* tp_traverse */
1399 0, /* tp_clear */
1400 0, /* tp_richcompare */
1401 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1402 0, /* tp_iter */
1403 0, /* tp_iternext */
1404 async_gen_methods, /* tp_methods */
1405 async_gen_memberlist, /* tp_members */
1406 async_gen_getsetlist, /* tp_getset */
1407 0, /* tp_base */
1408 0, /* tp_dict */
1409 0, /* tp_descr_get */
1410 0, /* tp_descr_set */
1411 0, /* tp_dictoffset */
1412 0, /* tp_init */
1413 0, /* tp_alloc */
1414 0, /* tp_new */
1415 0, /* tp_free */
1416 0, /* tp_is_gc */
1417 0, /* tp_bases */
1418 0, /* tp_mro */
1419 0, /* tp_cache */
1420 0, /* tp_subclasses */
1421 0, /* tp_weaklist */
1422 0, /* tp_del */
1423 0, /* tp_version_tag */
1424 _PyGen_Finalize, /* tp_finalize */
1425};
1426
1427
1428PyObject *
1429PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1430{
1431 PyAsyncGenObject *o;
1432 o = (PyAsyncGenObject *)gen_new_with_qualname(
1433 &PyAsyncGen_Type, f, name, qualname);
1434 if (o == NULL) {
1435 return NULL;
1436 }
1437 o->ag_finalizer = NULL;
1438 o->ag_closed = 0;
1439 o->ag_hooks_inited = 0;
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001440 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001441 return (PyObject*)o;
1442}
1443
1444
1445int
1446PyAsyncGen_ClearFreeLists(void)
1447{
1448 int ret = ag_value_freelist_free + ag_asend_freelist_free;
1449
1450 while (ag_value_freelist_free) {
1451 _PyAsyncGenWrappedValue *o;
1452 o = ag_value_freelist[--ag_value_freelist_free];
1453 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001454 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001455 }
1456
1457 while (ag_asend_freelist_free) {
1458 PyAsyncGenASend *o;
1459 o = ag_asend_freelist[--ag_asend_freelist_free];
1460 assert(Py_TYPE(o) == &_PyAsyncGenASend_Type);
Yury Selivanov29310c42016-11-08 19:46:22 -05001461 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001462 }
1463
1464 return ret;
1465}
1466
1467void
1468PyAsyncGen_Fini(void)
1469{
1470 PyAsyncGen_ClearFreeLists();
1471}
1472
1473
1474static PyObject *
1475async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1476{
1477 if (result == NULL) {
1478 if (!PyErr_Occurred()) {
1479 PyErr_SetNone(PyExc_StopAsyncIteration);
1480 }
1481
1482 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1483 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1484 ) {
1485 gen->ag_closed = 1;
1486 }
1487
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001488 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001489 return NULL;
1490 }
1491
1492 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1493 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001494 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001495 Py_DECREF(result);
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001496 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001497 return NULL;
1498 }
1499
1500 return result;
1501}
1502
1503
1504/* ---------- Async Generator ASend Awaitable ------------ */
1505
1506
1507static void
1508async_gen_asend_dealloc(PyAsyncGenASend *o)
1509{
Yury Selivanov29310c42016-11-08 19:46:22 -05001510 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001511 Py_CLEAR(o->ags_gen);
1512 Py_CLEAR(o->ags_sendval);
1513 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1514 assert(PyAsyncGenASend_CheckExact(o));
1515 ag_asend_freelist[ag_asend_freelist_free++] = o;
1516 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001517 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001518 }
1519}
1520
Yury Selivanov29310c42016-11-08 19:46:22 -05001521static int
1522async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1523{
1524 Py_VISIT(o->ags_gen);
1525 Py_VISIT(o->ags_sendval);
1526 return 0;
1527}
1528
Yury Selivanoveb636452016-09-08 22:01:51 -07001529
1530static PyObject *
1531async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1532{
1533 PyObject *result;
1534
1535 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Miss Islington (bot)5cadd3f2020-01-20 15:06:40 -08001536 PyErr_SetString(
1537 PyExc_RuntimeError,
1538 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001539 return NULL;
1540 }
1541
1542 if (o->ags_state == AWAITABLE_STATE_INIT) {
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001543 if (o->ags_gen->ag_running_async) {
1544 PyErr_SetString(
1545 PyExc_RuntimeError,
1546 "anext(): asynchronous generator is already running");
1547 return NULL;
1548 }
1549
Yury Selivanoveb636452016-09-08 22:01:51 -07001550 if (arg == NULL || arg == Py_None) {
1551 arg = o->ags_sendval;
1552 }
1553 o->ags_state = AWAITABLE_STATE_ITER;
1554 }
1555
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001556 o->ags_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001557 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1558 result = async_gen_unwrap_value(o->ags_gen, result);
1559
1560 if (result == NULL) {
1561 o->ags_state = AWAITABLE_STATE_CLOSED;
1562 }
1563
1564 return result;
1565}
1566
1567
1568static PyObject *
1569async_gen_asend_iternext(PyAsyncGenASend *o)
1570{
1571 return async_gen_asend_send(o, NULL);
1572}
1573
1574
1575static PyObject *
1576async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1577{
1578 PyObject *result;
1579
1580 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Miss Islington (bot)5cadd3f2020-01-20 15:06:40 -08001581 PyErr_SetString(
1582 PyExc_RuntimeError,
1583 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001584 return NULL;
1585 }
1586
1587 result = gen_throw((PyGenObject*)o->ags_gen, args);
1588 result = async_gen_unwrap_value(o->ags_gen, result);
1589
1590 if (result == NULL) {
1591 o->ags_state = AWAITABLE_STATE_CLOSED;
1592 }
1593
1594 return result;
1595}
1596
1597
1598static PyObject *
1599async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1600{
1601 o->ags_state = AWAITABLE_STATE_CLOSED;
1602 Py_RETURN_NONE;
1603}
1604
1605
1606static PyMethodDef async_gen_asend_methods[] = {
1607 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1608 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1609 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1610 {NULL, NULL} /* Sentinel */
1611};
1612
1613
1614static PyAsyncMethods async_gen_asend_as_async = {
1615 PyObject_SelfIter, /* am_await */
1616 0, /* am_aiter */
1617 0 /* am_anext */
1618};
1619
1620
1621PyTypeObject _PyAsyncGenASend_Type = {
1622 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1623 "async_generator_asend", /* tp_name */
1624 sizeof(PyAsyncGenASend), /* tp_basicsize */
1625 0, /* tp_itemsize */
1626 /* methods */
1627 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001628 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001629 0, /* tp_getattr */
1630 0, /* tp_setattr */
1631 &async_gen_asend_as_async, /* tp_as_async */
1632 0, /* tp_repr */
1633 0, /* tp_as_number */
1634 0, /* tp_as_sequence */
1635 0, /* tp_as_mapping */
1636 0, /* tp_hash */
1637 0, /* tp_call */
1638 0, /* tp_str */
1639 PyObject_GenericGetAttr, /* tp_getattro */
1640 0, /* tp_setattro */
1641 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001642 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001643 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001644 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001645 0, /* tp_clear */
1646 0, /* tp_richcompare */
1647 0, /* tp_weaklistoffset */
1648 PyObject_SelfIter, /* tp_iter */
1649 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1650 async_gen_asend_methods, /* tp_methods */
1651 0, /* tp_members */
1652 0, /* tp_getset */
1653 0, /* tp_base */
1654 0, /* tp_dict */
1655 0, /* tp_descr_get */
1656 0, /* tp_descr_set */
1657 0, /* tp_dictoffset */
1658 0, /* tp_init */
1659 0, /* tp_alloc */
1660 0, /* tp_new */
1661};
1662
1663
1664static PyObject *
1665async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1666{
1667 PyAsyncGenASend *o;
1668 if (ag_asend_freelist_free) {
1669 ag_asend_freelist_free--;
1670 o = ag_asend_freelist[ag_asend_freelist_free];
1671 _Py_NewReference((PyObject *)o);
1672 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001673 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001674 if (o == NULL) {
1675 return NULL;
1676 }
1677 }
1678
1679 Py_INCREF(gen);
1680 o->ags_gen = gen;
1681
1682 Py_XINCREF(sendval);
1683 o->ags_sendval = sendval;
1684
1685 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001686
1687 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001688 return (PyObject*)o;
1689}
1690
1691
1692/* ---------- Async Generator Value Wrapper ------------ */
1693
1694
1695static void
1696async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1697{
Yury Selivanov29310c42016-11-08 19:46:22 -05001698 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001699 Py_CLEAR(o->agw_val);
1700 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1701 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1702 ag_value_freelist[ag_value_freelist_free++] = o;
1703 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001704 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001705 }
1706}
1707
1708
Yury Selivanov29310c42016-11-08 19:46:22 -05001709static int
1710async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1711 visitproc visit, void *arg)
1712{
1713 Py_VISIT(o->agw_val);
1714 return 0;
1715}
1716
1717
Yury Selivanoveb636452016-09-08 22:01:51 -07001718PyTypeObject _PyAsyncGenWrappedValue_Type = {
1719 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1720 "async_generator_wrapped_value", /* tp_name */
1721 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1722 0, /* tp_itemsize */
1723 /* methods */
1724 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001725 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001726 0, /* tp_getattr */
1727 0, /* tp_setattr */
1728 0, /* tp_as_async */
1729 0, /* tp_repr */
1730 0, /* tp_as_number */
1731 0, /* tp_as_sequence */
1732 0, /* tp_as_mapping */
1733 0, /* tp_hash */
1734 0, /* tp_call */
1735 0, /* tp_str */
1736 PyObject_GenericGetAttr, /* tp_getattro */
1737 0, /* tp_setattro */
1738 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001739 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001740 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001741 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001742 0, /* tp_clear */
1743 0, /* tp_richcompare */
1744 0, /* tp_weaklistoffset */
1745 0, /* tp_iter */
1746 0, /* tp_iternext */
1747 0, /* tp_methods */
1748 0, /* tp_members */
1749 0, /* tp_getset */
1750 0, /* tp_base */
1751 0, /* tp_dict */
1752 0, /* tp_descr_get */
1753 0, /* tp_descr_set */
1754 0, /* tp_dictoffset */
1755 0, /* tp_init */
1756 0, /* tp_alloc */
1757 0, /* tp_new */
1758};
1759
1760
1761PyObject *
1762_PyAsyncGenValueWrapperNew(PyObject *val)
1763{
1764 _PyAsyncGenWrappedValue *o;
1765 assert(val);
1766
1767 if (ag_value_freelist_free) {
1768 ag_value_freelist_free--;
1769 o = ag_value_freelist[ag_value_freelist_free];
1770 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1771 _Py_NewReference((PyObject*)o);
1772 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001773 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1774 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001775 if (o == NULL) {
1776 return NULL;
1777 }
1778 }
1779 o->agw_val = val;
1780 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001781 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001782 return (PyObject*)o;
1783}
1784
1785
1786/* ---------- Async Generator AThrow awaitable ------------ */
1787
1788
1789static void
1790async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1791{
Yury Selivanov29310c42016-11-08 19:46:22 -05001792 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001793 Py_CLEAR(o->agt_gen);
1794 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001795 PyObject_GC_Del(o);
1796}
1797
1798
1799static int
1800async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1801{
1802 Py_VISIT(o->agt_gen);
1803 Py_VISIT(o->agt_args);
1804 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001805}
1806
1807
1808static PyObject *
1809async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1810{
1811 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1812 PyFrameObject *f = gen->gi_frame;
1813 PyObject *retval;
1814
1815 if (f == NULL || f->f_stacktop == NULL ||
1816 o->agt_state == AWAITABLE_STATE_CLOSED) {
Miss Islington (bot)5cadd3f2020-01-20 15:06:40 -08001817 PyErr_SetString(
1818 PyExc_RuntimeError,
1819 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001820 return NULL;
1821 }
1822
1823 if (o->agt_state == AWAITABLE_STATE_INIT) {
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001824 if (o->agt_gen->ag_running_async) {
1825 if (o->agt_args == NULL) {
1826 PyErr_SetString(
1827 PyExc_RuntimeError,
1828 "aclose(): asynchronous generator is already running");
1829 }
1830 else {
1831 PyErr_SetString(
1832 PyExc_RuntimeError,
1833 "athrow(): asynchronous generator is already running");
1834 }
1835 return NULL;
1836 }
1837
Yury Selivanoveb636452016-09-08 22:01:51 -07001838 if (o->agt_gen->ag_closed) {
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001839 o->agt_state = AWAITABLE_STATE_CLOSED;
1840 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001841 return NULL;
1842 }
1843
1844 if (arg != Py_None) {
1845 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1846 return NULL;
1847 }
1848
1849 o->agt_state = AWAITABLE_STATE_ITER;
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001850 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001851
1852 if (o->agt_args == NULL) {
1853 /* aclose() mode */
1854 o->agt_gen->ag_closed = 1;
1855
1856 retval = _gen_throw((PyGenObject *)gen,
1857 0, /* Do not close generator when
1858 PyExc_GeneratorExit is passed */
1859 PyExc_GeneratorExit, NULL, NULL);
1860
1861 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1862 Py_DECREF(retval);
1863 goto yield_close;
1864 }
1865 } else {
1866 PyObject *typ;
1867 PyObject *tb = NULL;
1868 PyObject *val = NULL;
1869
1870 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1871 &typ, &val, &tb)) {
1872 return NULL;
1873 }
1874
1875 retval = _gen_throw((PyGenObject *)gen,
1876 0, /* Do not close generator when
1877 PyExc_GeneratorExit is passed */
1878 typ, val, tb);
1879 retval = async_gen_unwrap_value(o->agt_gen, retval);
1880 }
1881 if (retval == NULL) {
1882 goto check_error;
1883 }
1884 return retval;
1885 }
1886
1887 assert(o->agt_state == AWAITABLE_STATE_ITER);
1888
1889 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1890 if (o->agt_args) {
1891 return async_gen_unwrap_value(o->agt_gen, retval);
1892 } else {
1893 /* aclose() mode */
1894 if (retval) {
1895 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001896 o->agt_gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001897 Py_DECREF(retval);
1898 goto yield_close;
1899 }
1900 else {
1901 return retval;
1902 }
1903 }
1904 else {
1905 goto check_error;
1906 }
1907 }
1908
1909yield_close:
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001910 o->agt_gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001911 PyErr_SetString(
1912 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1913 return NULL;
1914
1915check_error:
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001916 o->agt_gen->ag_running_async = 0;
Yury Selivanov52698c72018-06-07 20:31:26 -04001917 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1918 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1919 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001920 o->agt_state = AWAITABLE_STATE_CLOSED;
1921 if (o->agt_args == NULL) {
1922 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001923 StopAsyncIteration or GeneratorExit; just raise
1924 StopIteration, signalling that this 'aclose()' await
1925 is done.
1926 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001927 PyErr_Clear();
1928 PyErr_SetNone(PyExc_StopIteration);
1929 }
1930 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001931 return NULL;
1932}
1933
1934
1935static PyObject *
1936async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1937{
1938 PyObject *retval;
1939
Yury Selivanoveb636452016-09-08 22:01:51 -07001940 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Miss Islington (bot)5cadd3f2020-01-20 15:06:40 -08001941 PyErr_SetString(
1942 PyExc_RuntimeError,
1943 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001944 return NULL;
1945 }
1946
1947 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1948 if (o->agt_args) {
1949 return async_gen_unwrap_value(o->agt_gen, retval);
1950 } else {
1951 /* aclose() mode */
1952 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Miss Islington (bot)2f87a7d2019-09-29 23:19:02 -07001953 o->agt_gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001954 Py_DECREF(retval);
1955 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1956 return NULL;
1957 }
Miss Islington (bot)6c3b4712019-11-19 06:12:06 -08001958 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1959 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1960 {
1961 /* when aclose() is called we don't want to propagate
1962 StopAsyncIteration or GeneratorExit; just raise
1963 StopIteration, signalling that this 'aclose()' await
1964 is done.
1965 */
1966 PyErr_Clear();
1967 PyErr_SetNone(PyExc_StopIteration);
1968 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001969 return retval;
1970 }
1971}
1972
1973
1974static PyObject *
1975async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1976{
1977 return async_gen_athrow_send(o, Py_None);
1978}
1979
1980
1981static PyObject *
1982async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1983{
1984 o->agt_state = AWAITABLE_STATE_CLOSED;
1985 Py_RETURN_NONE;
1986}
1987
1988
1989static PyMethodDef async_gen_athrow_methods[] = {
1990 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1991 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1992 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1993 {NULL, NULL} /* Sentinel */
1994};
1995
1996
1997static PyAsyncMethods async_gen_athrow_as_async = {
1998 PyObject_SelfIter, /* am_await */
1999 0, /* am_aiter */
2000 0 /* am_anext */
2001};
2002
2003
2004PyTypeObject _PyAsyncGenAThrow_Type = {
2005 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2006 "async_generator_athrow", /* tp_name */
2007 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2008 0, /* tp_itemsize */
2009 /* methods */
2010 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002011 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002012 0, /* tp_getattr */
2013 0, /* tp_setattr */
2014 &async_gen_athrow_as_async, /* tp_as_async */
2015 0, /* tp_repr */
2016 0, /* tp_as_number */
2017 0, /* tp_as_sequence */
2018 0, /* tp_as_mapping */
2019 0, /* tp_hash */
2020 0, /* tp_call */
2021 0, /* tp_str */
2022 PyObject_GenericGetAttr, /* tp_getattro */
2023 0, /* tp_setattro */
2024 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002025 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002026 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002027 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002028 0, /* tp_clear */
2029 0, /* tp_richcompare */
2030 0, /* tp_weaklistoffset */
2031 PyObject_SelfIter, /* tp_iter */
2032 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2033 async_gen_athrow_methods, /* tp_methods */
2034 0, /* tp_members */
2035 0, /* tp_getset */
2036 0, /* tp_base */
2037 0, /* tp_dict */
2038 0, /* tp_descr_get */
2039 0, /* tp_descr_set */
2040 0, /* tp_dictoffset */
2041 0, /* tp_init */
2042 0, /* tp_alloc */
2043 0, /* tp_new */
2044};
2045
2046
2047static PyObject *
2048async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2049{
2050 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002051 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002052 if (o == NULL) {
2053 return NULL;
2054 }
2055 o->agt_gen = gen;
2056 o->agt_args = args;
2057 o->agt_state = AWAITABLE_STATE_INIT;
2058 Py_INCREF(gen);
2059 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002060 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002061 return (PyObject*)o;
2062}