blob: 0a34c1f6a97fe2c3ab67a2fbfeb1fef337e6016a [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06004#include "internal/pystate.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00005#include "frameobject.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00006#include "structmember.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00008
Yury Selivanoveb636452016-09-08 22:01:51 -07009static PyObject *gen_close(PyGenObject *, PyObject *);
10static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
11static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
12
13static char *NON_INIT_CORO_MSG = "can't send non-None value to a "
14 "just-started coroutine";
15
16static char *ASYNC_GEN_IGNORED_EXIT_MSG =
17 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100018
Mark Shannonae3087c2017-10-22 22:41:51 +010019static inline int
20exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
21{
22 Py_VISIT(exc_state->exc_type);
23 Py_VISIT(exc_state->exc_value);
24 Py_VISIT(exc_state->exc_traceback);
25 return 0;
26}
27
Martin v. Löwise440e472004-06-01 15:22:42 +000028static int
29gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
30{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 Py_VISIT((PyObject *)gen->gi_frame);
32 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020033 Py_VISIT(gen->gi_name);
34 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080035 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
36 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010037 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000038}
39
Antoine Pitrou58720d62013-08-05 23:26:40 +020040void
41_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020042{
43 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070044 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020045 PyObject *error_type, *error_value, *error_traceback;
46
47 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
48 /* Generator isn't paused, so no need to close */
49 return;
50
Yury Selivanoveb636452016-09-08 22:01:51 -070051 if (PyAsyncGen_CheckExact(self)) {
52 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
53 PyObject *finalizer = agen->ag_finalizer;
54 if (finalizer && !agen->ag_closed) {
55 /* Save the current exception, if any. */
56 PyErr_Fetch(&error_type, &error_value, &error_traceback);
57
Victor Stinnerde4ae3d2016-12-04 22:59:09 +010058 res = PyObject_CallFunctionObjArgs(finalizer, self, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -070059
60 if (res == NULL) {
61 PyErr_WriteUnraisable(self);
62 } else {
63 Py_DECREF(res);
64 }
65 /* Restore the saved exception. */
66 PyErr_Restore(error_type, error_value, error_traceback);
67 return;
68 }
69 }
70
Antoine Pitrou796564c2013-07-30 19:59:21 +020071 /* Save the current exception, if any. */
72 PyErr_Fetch(&error_type, &error_value, &error_traceback);
73
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070074 /* If `gen` is a coroutine, and if it was never awaited on,
75 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070076 if (gen->gi_code != NULL &&
77 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
78 gen->gi_frame->f_lasti == -1) {
79 if (!error_value) {
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080080 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Petersonb88db872016-09-07 08:46:59 -070081 }
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070082 }
83 else {
84 res = gen_close(gen, NULL);
85 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020086
Benjamin Petersonb88db872016-09-07 08:46:59 -070087 if (res == NULL) {
88 if (PyErr_Occurred())
89 PyErr_WriteUnraisable(self);
90 }
91 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020092 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070093 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020094
95 /* Restore the saved exception. */
96 PyErr_Restore(error_type, error_value, error_traceback);
97}
98
Mark Shannonae3087c2017-10-22 22:41:51 +010099static inline void
100exc_state_clear(_PyErr_StackItem *exc_state)
101{
102 PyObject *t, *v, *tb;
103 t = exc_state->exc_type;
104 v = exc_state->exc_value;
105 tb = exc_state->exc_traceback;
106 exc_state->exc_type = NULL;
107 exc_state->exc_value = NULL;
108 exc_state->exc_traceback = NULL;
109 Py_XDECREF(t);
110 Py_XDECREF(v);
111 Py_XDECREF(tb);
112}
113
Antoine Pitrou796564c2013-07-30 19:59:21 +0200114static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000115gen_dealloc(PyGenObject *gen)
116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (gen->gi_weakreflist != NULL)
122 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000123
Antoine Pitrou93963562013-05-14 20:37:52 +0200124 _PyObject_GC_TRACK(self);
125
Antoine Pitrou796564c2013-07-30 19:59:21 +0200126 if (PyObject_CallFinalizerFromDealloc(self))
127 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200128
129 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700130 if (PyAsyncGen_CheckExact(gen)) {
131 /* We have to handle this case for asynchronous generators
132 right here, because this code has to be between UNTRACK
133 and GC_Del. */
134 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
135 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700136 if (gen->gi_frame != NULL) {
137 gen->gi_frame->f_gen = NULL;
138 Py_CLEAR(gen->gi_frame);
139 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800140 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
141 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200144 Py_CLEAR(gen->gi_name);
145 Py_CLEAR(gen->gi_qualname);
Mark Shannonae3087c2017-10-22 22:41:51 +0100146 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000148}
149
150static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500151gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000152{
Antoine Pitrou93963562013-05-14 20:37:52 +0200153 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200155 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000156
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500157 if (gen->gi_running) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200158 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700159 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400160 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700161 }
162 else if (PyAsyncGen_CheckExact(gen)) {
163 msg = "async generator already executing";
164 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400165 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500166 return NULL;
167 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200168 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500169 if (PyCoro_CheckExact(gen) && !closing) {
170 /* `gen` is an exhausted coroutine: raise an error,
171 except when called from gen_close(), which should
172 always be a silent method. */
173 PyErr_SetString(
174 PyExc_RuntimeError,
175 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700176 }
177 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500178 /* `gen` is an exhausted generator:
179 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700180 if (PyAsyncGen_CheckExact(gen)) {
181 PyErr_SetNone(PyExc_StopAsyncIteration);
182 }
183 else {
184 PyErr_SetNone(PyExc_StopIteration);
185 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500186 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return NULL;
188 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000189
Antoine Pitrou93963562013-05-14 20:37:52 +0200190 if (f->f_lasti == -1) {
191 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200192 const char *msg = "can't send non-None value to a "
193 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700194 if (PyCoro_CheckExact(gen)) {
195 msg = NON_INIT_CORO_MSG;
196 }
197 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400198 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700199 "just-started async generator";
200 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400201 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200202 return NULL;
203 }
204 } else {
205 /* Push arg onto the frame's value stack */
206 result = arg ? arg : Py_None;
207 Py_INCREF(result);
208 *(f->f_stacktop++) = result;
209 }
210
211 /* Generators always return to their most recent caller, not
212 * necessarily their creator. */
213 Py_XINCREF(tstate->frame);
214 assert(f->f_back == NULL);
215 f->f_back = tstate->frame;
216
217 gen->gi_running = 1;
Mark Shannonae3087c2017-10-22 22:41:51 +0100218 gen->gi_exc_state.previous_item = tstate->exc_info;
219 tstate->exc_info = &gen->gi_exc_state;
Victor Stinner59a73272016-12-09 18:51:13 +0100220 result = PyEval_EvalFrameEx(f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100221 tstate->exc_info = gen->gi_exc_state.previous_item;
222 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200223 gen->gi_running = 0;
224
225 /* Don't keep the reference to f_back any longer than necessary. It
226 * may keep a chain of frames alive or it could create a reference
227 * cycle. */
228 assert(f->f_back == tstate->frame);
229 Py_CLEAR(f->f_back);
230
231 /* If the generator just returned (as opposed to yielding), signal
232 * that the generator is exhausted. */
233 if (result && f->f_stacktop == NULL) {
234 if (result == Py_None) {
235 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700236 if (PyAsyncGen_CheckExact(gen)) {
237 PyErr_SetNone(PyExc_StopAsyncIteration);
238 }
239 else {
240 PyErr_SetNone(PyExc_StopIteration);
241 }
242 }
243 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700244 /* Async generators cannot return anything but None */
245 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200246 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200247 }
248 Py_CLEAR(result);
249 }
Yury Selivanov68333392015-05-22 11:16:47 -0400250 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400251 /* Check for __future__ generator_stop and conditionally turn
252 * a leaking StopIteration into RuntimeError (with its cause
253 * set appropriately). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700254
255 const int check_stop_iter_error_flags = CO_FUTURE_GENERATOR_STOP |
256 CO_COROUTINE |
257 CO_ITERABLE_COROUTINE |
258 CO_ASYNC_GENERATOR;
259
260 if (gen->gi_code != NULL &&
261 ((PyCodeObject *)gen->gi_code)->co_flags &
262 check_stop_iter_error_flags)
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400263 {
Yury Selivanoveb636452016-09-08 22:01:51 -0700264 /* `gen` is either:
265 * a generator with CO_FUTURE_GENERATOR_STOP flag;
266 * a coroutine;
267 * a generator with CO_ITERABLE_COROUTINE flag
268 (decorated with types.coroutine decorator);
269 * an async generator.
270 */
271 const char *msg = "generator raised StopIteration";
272 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400273 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700274 }
275 else if PyAsyncGen_CheckExact(gen) {
276 msg = "async generator raised StopIteration";
277 }
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300278 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400279 }
Yury Selivanov68333392015-05-22 11:16:47 -0400280 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700281 /* `gen` is an ordinary generator without
282 CO_FUTURE_GENERATOR_STOP flag.
283 */
284
Yury Selivanov68333392015-05-22 11:16:47 -0400285 PyObject *exc, *val, *tb;
286
287 /* Pop the exception before issuing a warning. */
288 PyErr_Fetch(&exc, &val, &tb);
289
Martin Panter7e3a91a2016-02-10 04:40:48 +0000290 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Yury Selivanov68333392015-05-22 11:16:47 -0400291 "generator '%.50S' raised StopIteration",
292 gen->gi_qualname)) {
293 /* Warning was converted to an error. */
294 Py_XDECREF(exc);
295 Py_XDECREF(val);
296 Py_XDECREF(tb);
297 }
298 else {
299 PyErr_Restore(exc, val, tb);
300 }
301 }
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400302 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700303 else if (PyAsyncGen_CheckExact(gen) && !result &&
304 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
305 {
306 /* code in `gen` raised a StopAsyncIteration error:
307 raise a RuntimeError.
308 */
309 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300310 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700311 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200312
313 if (!result || f->f_stacktop == NULL) {
314 /* generator can't be rerun, so release the frame */
315 /* first clean reference cycle through stored exception traceback */
Mark Shannonae3087c2017-10-22 22:41:51 +0100316 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200317 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200318 gen->gi_frame = NULL;
319 Py_DECREF(f);
320 }
321
322 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000323}
324
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000325PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326"send(arg) -> send 'arg' into generator,\n\
327return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000328
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500329PyObject *
330_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000331{
Yury Selivanov77c96812016-02-13 17:59:05 -0500332 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000333}
334
335PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400336"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000337
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000338/*
339 * This helper function is used by gen_close and gen_throw to
340 * close a subiterator being delegated to by yield-from.
341 */
342
Antoine Pitrou93963562013-05-14 20:37:52 +0200343static int
344gen_close_iter(PyObject *yf)
345{
346 PyObject *retval = NULL;
347 _Py_IDENTIFIER(close);
348
Yury Selivanoveb636452016-09-08 22:01:51 -0700349 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200350 retval = gen_close((PyGenObject *)yf, NULL);
351 if (retval == NULL)
352 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700353 }
354 else {
Antoine Pitrou93963562013-05-14 20:37:52 +0200355 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
356 if (meth == NULL) {
357 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
358 PyErr_WriteUnraisable(yf);
359 PyErr_Clear();
Yury Selivanoveb636452016-09-08 22:01:51 -0700360 }
361 else {
Victor Stinner3466bde2016-09-05 18:16:01 -0700362 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200363 Py_DECREF(meth);
364 if (retval == NULL)
365 return -1;
366 }
367 }
368 Py_XDECREF(retval);
369 return 0;
370}
371
Yury Selivanovc724bae2016-03-02 11:30:46 -0500372PyObject *
373_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500374{
Antoine Pitrou93963562013-05-14 20:37:52 +0200375 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500376 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200377
378 if (f && f->f_stacktop) {
379 PyObject *bytecode = f->f_code->co_code;
380 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
381
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100382 if (f->f_lasti < 0) {
383 /* Return immediately if the frame didn't start yet. YIELD_FROM
384 always come after LOAD_CONST: a code object should not start
385 with YIELD_FROM */
386 assert(code[0] != YIELD_FROM);
387 return NULL;
388 }
389
Serhiy Storchakaab874002016-09-11 13:48:15 +0300390 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200391 return NULL;
392 yf = f->f_stacktop[-1];
393 Py_INCREF(yf);
394 }
395
396 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500397}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000398
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000399static PyObject *
400gen_close(PyGenObject *gen, PyObject *args)
401{
Antoine Pitrou93963562013-05-14 20:37:52 +0200402 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500403 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200404 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000405
Antoine Pitrou93963562013-05-14 20:37:52 +0200406 if (yf) {
407 gen->gi_running = 1;
408 err = gen_close_iter(yf);
409 gen->gi_running = 0;
410 Py_DECREF(yf);
411 }
412 if (err == 0)
413 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500414 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200415 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200416 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700417 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400418 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700419 } else if (PyAsyncGen_CheckExact(gen)) {
420 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
421 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200422 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400423 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 return NULL;
425 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200426 if (PyErr_ExceptionMatches(PyExc_StopIteration)
427 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
428 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200429 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200430 }
431 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000432}
433
Antoine Pitrou93963562013-05-14 20:37:52 +0200434
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000435PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000436"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
437return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000438
439static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700440_gen_throw(PyGenObject *gen, int close_on_genexit,
441 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000442{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500443 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000444 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000445
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000446 if (yf) {
447 PyObject *ret;
448 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700449 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
450 close_on_genexit
451 ) {
452 /* Asynchronous generators *should not* be closed right away.
453 We have to allow some awaits to work it through, hence the
454 `close_on_genexit` parameter here.
455 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500456 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200457 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500458 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000459 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000460 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500461 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000462 goto throw_here;
463 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700464 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
465 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500466 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700467 /* Close the generator that we are currently iterating with
468 'yield from' or awaiting on with 'await'. */
469 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
470 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500471 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000472 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700473 /* `yf` is an iterator or a coroutine-like object. */
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000474 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000475 if (meth == NULL) {
476 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
477 Py_DECREF(yf);
478 return NULL;
479 }
480 PyErr_Clear();
481 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000482 goto throw_here;
483 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500484 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700485 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500486 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000487 Py_DECREF(meth);
488 }
489 Py_DECREF(yf);
490 if (!ret) {
491 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500492 /* Pop subiterator from stack */
493 ret = *(--gen->gi_frame->f_stacktop);
494 assert(ret == yf);
495 Py_DECREF(ret);
496 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100497 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300498 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000499 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500500 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000501 Py_DECREF(val);
502 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500503 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000504 }
505 }
506 return ret;
507 }
508
509throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* First, check the traceback argument, replacing None with
511 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400512 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 else if (tb != NULL && !PyTraceBack_Check(tb)) {
516 PyErr_SetString(PyExc_TypeError,
517 "throw() third argument must be a traceback object");
518 return NULL;
519 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 Py_INCREF(typ);
522 Py_XINCREF(val);
523 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000524
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400525 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 else if (PyExceptionInstance_Check(typ)) {
529 /* Raising an instance. The value should be a dummy. */
530 if (val && val != Py_None) {
531 PyErr_SetString(PyExc_TypeError,
532 "instance exception may not have a separate value");
533 goto failed_throw;
534 }
535 else {
536 /* Normalize to raise <class>, <instance> */
537 Py_XDECREF(val);
538 val = typ;
539 typ = PyExceptionInstance_Class(typ);
540 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200541
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400542 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200543 /* Returns NULL if there's no traceback */
544 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 }
546 }
547 else {
548 /* Not something you can raise. throw() fails. */
549 PyErr_Format(PyExc_TypeError,
550 "exceptions must be classes or instances "
551 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000552 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 goto failed_throw;
554 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500557 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000558
559failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* Didn't use our arguments, so restore their original refcounts */
561 Py_DECREF(typ);
562 Py_XDECREF(val);
563 Py_XDECREF(tb);
564 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000565}
566
567
568static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700569gen_throw(PyGenObject *gen, PyObject *args)
570{
571 PyObject *typ;
572 PyObject *tb = NULL;
573 PyObject *val = NULL;
574
575 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
576 return NULL;
577 }
578
579 return _gen_throw(gen, 1, typ, val, tb);
580}
581
582
583static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000584gen_iternext(PyGenObject *gen)
585{
Yury Selivanov77c96812016-02-13 17:59:05 -0500586 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000587}
588
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000589/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200590 * Set StopIteration with specified value. Value can be arbitrary object
591 * or NULL.
592 *
593 * Returns 0 if StopIteration is set and -1 if any other exception is set.
594 */
595int
596_PyGen_SetStopIterationValue(PyObject *value)
597{
598 PyObject *e;
599
600 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400601 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200602 {
603 /* Delay exception instantiation if we can */
604 PyErr_SetObject(PyExc_StopIteration, value);
605 return 0;
606 }
607 /* Construct an exception instance manually with
608 * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject.
609 *
610 * We do this to handle a situation when "value" is a tuple, in which
611 * case PyErr_SetObject would set the value of StopIteration to
612 * the first element of the tuple.
613 *
614 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
615 */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100616 e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200617 if (e == NULL) {
618 return -1;
619 }
620 PyErr_SetObject(PyExc_StopIteration, e);
621 Py_DECREF(e);
622 return 0;
623}
624
625/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000626 * If StopIteration exception is set, fetches its 'value'
627 * attribute if any, otherwise sets pvalue to None.
628 *
629 * Returns 0 if no exception or StopIteration is set.
630 * If any other exception is set, returns -1 and leaves
631 * pvalue unchanged.
632 */
633
634int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200635_PyGen_FetchStopIterationValue(PyObject **pvalue)
636{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000637 PyObject *et, *ev, *tb;
638 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500639
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000640 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
641 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200642 if (ev) {
643 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300644 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200645 value = ((PyStopIterationObject *)ev)->value;
646 Py_INCREF(value);
647 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200648 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
649 /* Avoid normalisation and take ev as value.
650 *
651 * Normalization is required if the value is a tuple, in
652 * that case the value of StopIteration would be set to
653 * the first element of the tuple.
654 *
655 * (See _PyErr_CreateException code for details.)
656 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200657 value = ev;
658 } else {
659 /* normalisation required */
660 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300661 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200662 PyErr_Restore(et, ev, tb);
663 return -1;
664 }
665 value = ((PyStopIterationObject *)ev)->value;
666 Py_INCREF(value);
667 Py_DECREF(ev);
668 }
669 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000670 Py_XDECREF(et);
671 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000672 } else if (PyErr_Occurred()) {
673 return -1;
674 }
675 if (value == NULL) {
676 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100677 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000678 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000679 *pvalue = value;
680 return 0;
681}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000682
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000683static PyObject *
684gen_repr(PyGenObject *gen)
685{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400686 return PyUnicode_FromFormat("<generator object %S at %p>",
687 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000688}
689
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000690static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200691gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000692{
Victor Stinner40ee3012014-06-16 15:59:28 +0200693 Py_INCREF(op->gi_name);
694 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000695}
696
Victor Stinner40ee3012014-06-16 15:59:28 +0200697static int
698gen_set_name(PyGenObject *op, PyObject *value)
699{
Victor Stinner40ee3012014-06-16 15:59:28 +0200700 /* Not legal to del gen.gi_name or to set it to anything
701 * other than a string object. */
702 if (value == NULL || !PyUnicode_Check(value)) {
703 PyErr_SetString(PyExc_TypeError,
704 "__name__ must be set to a string object");
705 return -1;
706 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200707 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300708 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200709 return 0;
710}
711
712static PyObject *
713gen_get_qualname(PyGenObject *op)
714{
715 Py_INCREF(op->gi_qualname);
716 return op->gi_qualname;
717}
718
719static int
720gen_set_qualname(PyGenObject *op, PyObject *value)
721{
Victor Stinner40ee3012014-06-16 15:59:28 +0200722 /* Not legal to del gen.__qualname__ or to set it to anything
723 * other than a string object. */
724 if (value == NULL || !PyUnicode_Check(value)) {
725 PyErr_SetString(PyExc_TypeError,
726 "__qualname__ must be set to a string object");
727 return -1;
728 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200729 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300730 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200731 return 0;
732}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000733
Yury Selivanove13f8f32015-07-03 00:23:30 -0400734static PyObject *
735gen_getyieldfrom(PyGenObject *gen)
736{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500737 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400738 if (yf == NULL)
739 Py_RETURN_NONE;
740 return yf;
741}
742
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000743static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200744 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
745 PyDoc_STR("name of the generator")},
746 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
747 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400748 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
749 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200750 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000751};
752
Martin v. Löwise440e472004-06-01 15:22:42 +0000753static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200754 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
755 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
756 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000758};
759
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000760static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500761 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
763 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
764 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000765};
766
Martin v. Löwise440e472004-06-01 15:22:42 +0000767PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 PyVarObject_HEAD_INIT(&PyType_Type, 0)
769 "generator", /* tp_name */
770 sizeof(PyGenObject), /* tp_basicsize */
771 0, /* tp_itemsize */
772 /* methods */
773 (destructor)gen_dealloc, /* tp_dealloc */
774 0, /* tp_print */
775 0, /* tp_getattr */
776 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400777 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 (reprfunc)gen_repr, /* tp_repr */
779 0, /* tp_as_number */
780 0, /* tp_as_sequence */
781 0, /* tp_as_mapping */
782 0, /* tp_hash */
783 0, /* tp_call */
784 0, /* tp_str */
785 PyObject_GenericGetAttr, /* tp_getattro */
786 0, /* tp_setattro */
787 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200788 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
789 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 0, /* tp_doc */
791 (traverseproc)gen_traverse, /* tp_traverse */
792 0, /* tp_clear */
793 0, /* tp_richcompare */
794 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400795 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 (iternextfunc)gen_iternext, /* tp_iternext */
797 gen_methods, /* tp_methods */
798 gen_memberlist, /* tp_members */
799 gen_getsetlist, /* tp_getset */
800 0, /* tp_base */
801 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 0, /* tp_descr_get */
804 0, /* tp_descr_set */
805 0, /* tp_dictoffset */
806 0, /* tp_init */
807 0, /* tp_alloc */
808 0, /* tp_new */
809 0, /* tp_free */
810 0, /* tp_is_gc */
811 0, /* tp_bases */
812 0, /* tp_mro */
813 0, /* tp_cache */
814 0, /* tp_subclasses */
815 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200816 0, /* tp_del */
817 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200818 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000819};
820
Yury Selivanov5376ba92015-06-22 12:19:30 -0400821static PyObject *
822gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
823 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000824{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400825 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (gen == NULL) {
827 Py_DECREF(f);
828 return NULL;
829 }
830 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200831 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 Py_INCREF(f->f_code);
833 gen->gi_code = (PyObject *)(f->f_code);
834 gen->gi_running = 0;
835 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100836 gen->gi_exc_state.exc_type = NULL;
837 gen->gi_exc_state.exc_value = NULL;
838 gen->gi_exc_state.exc_traceback = NULL;
839 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200840 if (name != NULL)
841 gen->gi_name = name;
842 else
843 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
844 Py_INCREF(gen->gi_name);
845 if (qualname != NULL)
846 gen->gi_qualname = qualname;
847 else
848 gen->gi_qualname = gen->gi_name;
849 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 _PyObject_GC_TRACK(gen);
851 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000852}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000853
Victor Stinner40ee3012014-06-16 15:59:28 +0200854PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400855PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
856{
857 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
858}
859
860PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200861PyGen_New(PyFrameObject *f)
862{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400863 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200864}
865
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000866int
867PyGen_NeedsFinalizing(PyGenObject *gen)
868{
Antoine Pitrou93963562013-05-14 20:37:52 +0200869 int i;
870 PyFrameObject *f = gen->gi_frame;
871
872 if (f == NULL || f->f_stacktop == NULL)
873 return 0; /* no frame or empty blockstack == no finalization */
874
875 /* Any block type besides a loop requires cleanup. */
876 for (i = 0; i < f->f_iblock; i++)
877 if (f->f_blockstack[i].b_type != SETUP_LOOP)
878 return 1;
879
880 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000882}
Yury Selivanov75445082015-05-11 22:57:16 -0400883
Yury Selivanov5376ba92015-06-22 12:19:30 -0400884/* Coroutine Object */
885
886typedef struct {
887 PyObject_HEAD
888 PyCoroObject *cw_coroutine;
889} PyCoroWrapper;
890
891static int
892gen_is_coroutine(PyObject *o)
893{
894 if (PyGen_CheckExact(o)) {
895 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
896 if (code->co_flags & CO_ITERABLE_COROUTINE) {
897 return 1;
898 }
899 }
900 return 0;
901}
902
Yury Selivanov75445082015-05-11 22:57:16 -0400903/*
904 * This helper function returns an awaitable for `o`:
905 * - `o` if `o` is a coroutine-object;
906 * - `type(o)->tp_as_async->am_await(o)`
907 *
908 * Raises a TypeError if it's not possible to return
909 * an awaitable and returns NULL.
910 */
911PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400912_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400913{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400914 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400915 PyTypeObject *ot;
916
Yury Selivanov5376ba92015-06-22 12:19:30 -0400917 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
918 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400919 Py_INCREF(o);
920 return o;
921 }
922
923 ot = Py_TYPE(o);
924 if (ot->tp_as_async != NULL) {
925 getter = ot->tp_as_async->am_await;
926 }
927 if (getter != NULL) {
928 PyObject *res = (*getter)(o);
929 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400930 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
931 /* __await__ must return an *iterator*, not
932 a coroutine or another awaitable (see PEP 492) */
933 PyErr_SetString(PyExc_TypeError,
934 "__await__() returned a coroutine");
935 Py_CLEAR(res);
936 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400937 PyErr_Format(PyExc_TypeError,
938 "__await__() returned non-iterator "
939 "of type '%.100s'",
940 Py_TYPE(res)->tp_name);
941 Py_CLEAR(res);
942 }
Yury Selivanov75445082015-05-11 22:57:16 -0400943 }
944 return res;
945 }
946
947 PyErr_Format(PyExc_TypeError,
948 "object %.100s can't be used in 'await' expression",
949 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400950 return NULL;
951}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400952
953static PyObject *
954coro_repr(PyCoroObject *coro)
955{
956 return PyUnicode_FromFormat("<coroutine object %S at %p>",
957 coro->cr_qualname, coro);
958}
959
960static PyObject *
961coro_await(PyCoroObject *coro)
962{
963 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
964 if (cw == NULL) {
965 return NULL;
966 }
967 Py_INCREF(coro);
968 cw->cw_coroutine = coro;
969 _PyObject_GC_TRACK(cw);
970 return (PyObject *)cw;
971}
972
Yury Selivanove13f8f32015-07-03 00:23:30 -0400973static PyObject *
974coro_get_cr_await(PyCoroObject *coro)
975{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500976 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400977 if (yf == NULL)
978 Py_RETURN_NONE;
979 return yf;
980}
981
Yury Selivanov5376ba92015-06-22 12:19:30 -0400982static PyGetSetDef coro_getsetlist[] = {
983 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
984 PyDoc_STR("name of the coroutine")},
985 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
986 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400987 {"cr_await", (getter)coro_get_cr_await, NULL,
988 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400989 {NULL} /* Sentinel */
990};
991
992static PyMemberDef coro_memberlist[] = {
993 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
994 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
995 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800996 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400997 {NULL} /* Sentinel */
998};
999
1000PyDoc_STRVAR(coro_send_doc,
1001"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001002return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001003
1004PyDoc_STRVAR(coro_throw_doc,
1005"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001006return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001007
1008PyDoc_STRVAR(coro_close_doc,
1009"close() -> raise GeneratorExit inside coroutine.");
1010
1011static PyMethodDef coro_methods[] = {
1012 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
1013 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1014 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1015 {NULL, NULL} /* Sentinel */
1016};
1017
1018static PyAsyncMethods coro_as_async = {
1019 (unaryfunc)coro_await, /* am_await */
1020 0, /* am_aiter */
1021 0 /* am_anext */
1022};
1023
1024PyTypeObject PyCoro_Type = {
1025 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1026 "coroutine", /* tp_name */
1027 sizeof(PyCoroObject), /* tp_basicsize */
1028 0, /* tp_itemsize */
1029 /* methods */
1030 (destructor)gen_dealloc, /* tp_dealloc */
1031 0, /* tp_print */
1032 0, /* tp_getattr */
1033 0, /* tp_setattr */
1034 &coro_as_async, /* tp_as_async */
1035 (reprfunc)coro_repr, /* tp_repr */
1036 0, /* tp_as_number */
1037 0, /* tp_as_sequence */
1038 0, /* tp_as_mapping */
1039 0, /* tp_hash */
1040 0, /* tp_call */
1041 0, /* tp_str */
1042 PyObject_GenericGetAttr, /* tp_getattro */
1043 0, /* tp_setattro */
1044 0, /* tp_as_buffer */
1045 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1046 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1047 0, /* tp_doc */
1048 (traverseproc)gen_traverse, /* tp_traverse */
1049 0, /* tp_clear */
1050 0, /* tp_richcompare */
1051 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1052 0, /* tp_iter */
1053 0, /* tp_iternext */
1054 coro_methods, /* tp_methods */
1055 coro_memberlist, /* tp_members */
1056 coro_getsetlist, /* tp_getset */
1057 0, /* tp_base */
1058 0, /* tp_dict */
1059 0, /* tp_descr_get */
1060 0, /* tp_descr_set */
1061 0, /* tp_dictoffset */
1062 0, /* tp_init */
1063 0, /* tp_alloc */
1064 0, /* tp_new */
1065 0, /* tp_free */
1066 0, /* tp_is_gc */
1067 0, /* tp_bases */
1068 0, /* tp_mro */
1069 0, /* tp_cache */
1070 0, /* tp_subclasses */
1071 0, /* tp_weaklist */
1072 0, /* tp_del */
1073 0, /* tp_version_tag */
1074 _PyGen_Finalize, /* tp_finalize */
1075};
1076
1077static void
1078coro_wrapper_dealloc(PyCoroWrapper *cw)
1079{
1080 _PyObject_GC_UNTRACK((PyObject *)cw);
1081 Py_CLEAR(cw->cw_coroutine);
1082 PyObject_GC_Del(cw);
1083}
1084
1085static PyObject *
1086coro_wrapper_iternext(PyCoroWrapper *cw)
1087{
Yury Selivanov77c96812016-02-13 17:59:05 -05001088 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001089}
1090
1091static PyObject *
1092coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1093{
Yury Selivanov77c96812016-02-13 17:59:05 -05001094 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001095}
1096
1097static PyObject *
1098coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1099{
1100 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1101}
1102
1103static PyObject *
1104coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1105{
1106 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1107}
1108
1109static int
1110coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1111{
1112 Py_VISIT((PyObject *)cw->cw_coroutine);
1113 return 0;
1114}
1115
1116static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001117 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1118 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1119 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001120 {NULL, NULL} /* Sentinel */
1121};
1122
1123PyTypeObject _PyCoroWrapper_Type = {
1124 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1125 "coroutine_wrapper",
1126 sizeof(PyCoroWrapper), /* tp_basicsize */
1127 0, /* tp_itemsize */
1128 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
1129 0, /* tp_print */
1130 0, /* tp_getattr */
1131 0, /* tp_setattr */
1132 0, /* tp_as_async */
1133 0, /* tp_repr */
1134 0, /* tp_as_number */
1135 0, /* tp_as_sequence */
1136 0, /* tp_as_mapping */
1137 0, /* tp_hash */
1138 0, /* tp_call */
1139 0, /* tp_str */
1140 PyObject_GenericGetAttr, /* tp_getattro */
1141 0, /* tp_setattro */
1142 0, /* tp_as_buffer */
1143 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1144 "A wrapper object implementing __await__ for coroutines.",
1145 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1146 0, /* tp_clear */
1147 0, /* tp_richcompare */
1148 0, /* tp_weaklistoffset */
1149 PyObject_SelfIter, /* tp_iter */
1150 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1151 coro_wrapper_methods, /* tp_methods */
1152 0, /* tp_members */
1153 0, /* tp_getset */
1154 0, /* tp_base */
1155 0, /* tp_dict */
1156 0, /* tp_descr_get */
1157 0, /* tp_descr_set */
1158 0, /* tp_dictoffset */
1159 0, /* tp_init */
1160 0, /* tp_alloc */
1161 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001162 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001163};
1164
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001165static PyObject *
1166compute_cr_origin(int origin_depth)
1167{
1168 PyFrameObject *frame = PyEval_GetFrame();
1169 /* First count how many frames we have */
1170 int frame_count = 0;
1171 for (; frame && frame_count < origin_depth; ++frame_count) {
1172 frame = frame->f_back;
1173 }
1174
1175 /* Now collect them */
1176 PyObject *cr_origin = PyTuple_New(frame_count);
1177 frame = PyEval_GetFrame();
1178 for (int i = 0; i < frame_count; ++i) {
1179 PyObject *frameinfo = Py_BuildValue(
1180 "OiO",
1181 frame->f_code->co_filename,
1182 PyFrame_GetLineNumber(frame),
1183 frame->f_code->co_name);
1184 if (!frameinfo) {
1185 Py_DECREF(cr_origin);
1186 return NULL;
1187 }
1188 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1189 frame = frame->f_back;
1190 }
1191
1192 return cr_origin;
1193}
1194
Yury Selivanov5376ba92015-06-22 12:19:30 -04001195PyObject *
1196PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1197{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001198 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1199 if (!coro) {
1200 return NULL;
1201 }
1202
1203 PyThreadState *tstate = PyThreadState_GET();
1204 int origin_depth = tstate->coroutine_origin_tracking_depth;
1205
1206 if (origin_depth == 0) {
1207 ((PyCoroObject *)coro)->cr_origin = NULL;
1208 } else {
1209 PyObject *cr_origin = compute_cr_origin(origin_depth);
1210 if (!cr_origin) {
1211 Py_DECREF(coro);
1212 return NULL;
1213 }
1214 ((PyCoroObject *)coro)->cr_origin = cr_origin;
1215 }
1216
1217 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001218}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001219
1220
Yury Selivanoveb636452016-09-08 22:01:51 -07001221/* ========= Asynchronous Generators ========= */
1222
1223
1224typedef enum {
1225 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1226 AWAITABLE_STATE_ITER, /* being iterated */
1227 AWAITABLE_STATE_CLOSED, /* closed */
1228} AwaitableState;
1229
1230
1231typedef struct {
1232 PyObject_HEAD
1233 PyAsyncGenObject *ags_gen;
1234
1235 /* Can be NULL, when in the __anext__() mode
1236 (equivalent of "asend(None)") */
1237 PyObject *ags_sendval;
1238
1239 AwaitableState ags_state;
1240} PyAsyncGenASend;
1241
1242
1243typedef struct {
1244 PyObject_HEAD
1245 PyAsyncGenObject *agt_gen;
1246
1247 /* Can be NULL, when in the "aclose()" mode
1248 (equivalent of "athrow(GeneratorExit)") */
1249 PyObject *agt_args;
1250
1251 AwaitableState agt_state;
1252} PyAsyncGenAThrow;
1253
1254
1255typedef struct {
1256 PyObject_HEAD
1257 PyObject *agw_val;
1258} _PyAsyncGenWrappedValue;
1259
1260
1261#ifndef _PyAsyncGen_MAXFREELIST
1262#define _PyAsyncGen_MAXFREELIST 80
1263#endif
1264
1265/* Freelists boost performance 6-10%; they also reduce memory
1266 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1267 are short-living objects that are instantiated for every
1268 __anext__ call.
1269*/
1270
1271static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1272static int ag_value_freelist_free = 0;
1273
1274static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1275static int ag_asend_freelist_free = 0;
1276
1277#define _PyAsyncGenWrappedValue_CheckExact(o) \
1278 (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type)
1279
1280#define PyAsyncGenASend_CheckExact(o) \
1281 (Py_TYPE(o) == &_PyAsyncGenASend_Type)
1282
1283
1284static int
1285async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1286{
1287 Py_VISIT(gen->ag_finalizer);
1288 return gen_traverse((PyGenObject*)gen, visit, arg);
1289}
1290
1291
1292static PyObject *
1293async_gen_repr(PyAsyncGenObject *o)
1294{
1295 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1296 o->ag_qualname, o);
1297}
1298
1299
1300static int
1301async_gen_init_hooks(PyAsyncGenObject *o)
1302{
1303 PyThreadState *tstate;
1304 PyObject *finalizer;
1305 PyObject *firstiter;
1306
1307 if (o->ag_hooks_inited) {
1308 return 0;
1309 }
1310
1311 o->ag_hooks_inited = 1;
1312
1313 tstate = PyThreadState_GET();
1314
1315 finalizer = tstate->async_gen_finalizer;
1316 if (finalizer) {
1317 Py_INCREF(finalizer);
1318 o->ag_finalizer = finalizer;
1319 }
1320
1321 firstiter = tstate->async_gen_firstiter;
1322 if (firstiter) {
1323 PyObject *res;
1324
1325 Py_INCREF(firstiter);
Victor Stinner7bfb42d2016-12-05 17:04:32 +01001326 res = PyObject_CallFunctionObjArgs(firstiter, o, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -07001327 Py_DECREF(firstiter);
1328 if (res == NULL) {
1329 return 1;
1330 }
1331 Py_DECREF(res);
1332 }
1333
1334 return 0;
1335}
1336
1337
1338static PyObject *
1339async_gen_anext(PyAsyncGenObject *o)
1340{
1341 if (async_gen_init_hooks(o)) {
1342 return NULL;
1343 }
1344 return async_gen_asend_new(o, NULL);
1345}
1346
1347
1348static PyObject *
1349async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1350{
1351 if (async_gen_init_hooks(o)) {
1352 return NULL;
1353 }
1354 return async_gen_asend_new(o, arg);
1355}
1356
1357
1358static PyObject *
1359async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1360{
1361 if (async_gen_init_hooks(o)) {
1362 return NULL;
1363 }
1364 return async_gen_athrow_new(o, NULL);
1365}
1366
1367static PyObject *
1368async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1369{
1370 if (async_gen_init_hooks(o)) {
1371 return NULL;
1372 }
1373 return async_gen_athrow_new(o, args);
1374}
1375
1376
1377static PyGetSetDef async_gen_getsetlist[] = {
1378 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1379 PyDoc_STR("name of the async generator")},
1380 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1381 PyDoc_STR("qualified name of the async generator")},
1382 {"ag_await", (getter)coro_get_cr_await, NULL,
1383 PyDoc_STR("object being awaited on, or None")},
1384 {NULL} /* Sentinel */
1385};
1386
1387static PyMemberDef async_gen_memberlist[] = {
1388 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
1389 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY},
1390 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1391 {NULL} /* Sentinel */
1392};
1393
1394PyDoc_STRVAR(async_aclose_doc,
1395"aclose() -> raise GeneratorExit inside generator.");
1396
1397PyDoc_STRVAR(async_asend_doc,
1398"asend(v) -> send 'v' in generator.");
1399
1400PyDoc_STRVAR(async_athrow_doc,
1401"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1402
1403static PyMethodDef async_gen_methods[] = {
1404 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1405 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1406 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
1407 {NULL, NULL} /* Sentinel */
1408};
1409
1410
1411static PyAsyncMethods async_gen_as_async = {
1412 0, /* am_await */
1413 PyObject_SelfIter, /* am_aiter */
1414 (unaryfunc)async_gen_anext /* am_anext */
1415};
1416
1417
1418PyTypeObject PyAsyncGen_Type = {
1419 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1420 "async_generator", /* tp_name */
1421 sizeof(PyAsyncGenObject), /* tp_basicsize */
1422 0, /* tp_itemsize */
1423 /* methods */
1424 (destructor)gen_dealloc, /* tp_dealloc */
1425 0, /* tp_print */
1426 0, /* tp_getattr */
1427 0, /* tp_setattr */
1428 &async_gen_as_async, /* tp_as_async */
1429 (reprfunc)async_gen_repr, /* tp_repr */
1430 0, /* tp_as_number */
1431 0, /* tp_as_sequence */
1432 0, /* tp_as_mapping */
1433 0, /* tp_hash */
1434 0, /* tp_call */
1435 0, /* tp_str */
1436 PyObject_GenericGetAttr, /* tp_getattro */
1437 0, /* tp_setattro */
1438 0, /* tp_as_buffer */
1439 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1440 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1441 0, /* tp_doc */
1442 (traverseproc)async_gen_traverse, /* tp_traverse */
1443 0, /* tp_clear */
1444 0, /* tp_richcompare */
1445 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1446 0, /* tp_iter */
1447 0, /* tp_iternext */
1448 async_gen_methods, /* tp_methods */
1449 async_gen_memberlist, /* tp_members */
1450 async_gen_getsetlist, /* tp_getset */
1451 0, /* tp_base */
1452 0, /* tp_dict */
1453 0, /* tp_descr_get */
1454 0, /* tp_descr_set */
1455 0, /* tp_dictoffset */
1456 0, /* tp_init */
1457 0, /* tp_alloc */
1458 0, /* tp_new */
1459 0, /* tp_free */
1460 0, /* tp_is_gc */
1461 0, /* tp_bases */
1462 0, /* tp_mro */
1463 0, /* tp_cache */
1464 0, /* tp_subclasses */
1465 0, /* tp_weaklist */
1466 0, /* tp_del */
1467 0, /* tp_version_tag */
1468 _PyGen_Finalize, /* tp_finalize */
1469};
1470
1471
1472PyObject *
1473PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1474{
1475 PyAsyncGenObject *o;
1476 o = (PyAsyncGenObject *)gen_new_with_qualname(
1477 &PyAsyncGen_Type, f, name, qualname);
1478 if (o == NULL) {
1479 return NULL;
1480 }
1481 o->ag_finalizer = NULL;
1482 o->ag_closed = 0;
1483 o->ag_hooks_inited = 0;
1484 return (PyObject*)o;
1485}
1486
1487
1488int
1489PyAsyncGen_ClearFreeLists(void)
1490{
1491 int ret = ag_value_freelist_free + ag_asend_freelist_free;
1492
1493 while (ag_value_freelist_free) {
1494 _PyAsyncGenWrappedValue *o;
1495 o = ag_value_freelist[--ag_value_freelist_free];
1496 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001497 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001498 }
1499
1500 while (ag_asend_freelist_free) {
1501 PyAsyncGenASend *o;
1502 o = ag_asend_freelist[--ag_asend_freelist_free];
1503 assert(Py_TYPE(o) == &_PyAsyncGenASend_Type);
Yury Selivanov29310c42016-11-08 19:46:22 -05001504 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001505 }
1506
1507 return ret;
1508}
1509
1510void
1511PyAsyncGen_Fini(void)
1512{
1513 PyAsyncGen_ClearFreeLists();
1514}
1515
1516
1517static PyObject *
1518async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1519{
1520 if (result == NULL) {
1521 if (!PyErr_Occurred()) {
1522 PyErr_SetNone(PyExc_StopAsyncIteration);
1523 }
1524
1525 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1526 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1527 ) {
1528 gen->ag_closed = 1;
1529 }
1530
1531 return NULL;
1532 }
1533
1534 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1535 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001536 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001537 Py_DECREF(result);
Yury Selivanoveb636452016-09-08 22:01:51 -07001538 return NULL;
1539 }
1540
1541 return result;
1542}
1543
1544
1545/* ---------- Async Generator ASend Awaitable ------------ */
1546
1547
1548static void
1549async_gen_asend_dealloc(PyAsyncGenASend *o)
1550{
Yury Selivanov29310c42016-11-08 19:46:22 -05001551 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001552 Py_CLEAR(o->ags_gen);
1553 Py_CLEAR(o->ags_sendval);
1554 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1555 assert(PyAsyncGenASend_CheckExact(o));
1556 ag_asend_freelist[ag_asend_freelist_free++] = o;
1557 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001558 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001559 }
1560}
1561
Yury Selivanov29310c42016-11-08 19:46:22 -05001562static int
1563async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1564{
1565 Py_VISIT(o->ags_gen);
1566 Py_VISIT(o->ags_sendval);
1567 return 0;
1568}
1569
Yury Selivanoveb636452016-09-08 22:01:51 -07001570
1571static PyObject *
1572async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1573{
1574 PyObject *result;
1575
1576 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1577 PyErr_SetNone(PyExc_StopIteration);
1578 return NULL;
1579 }
1580
1581 if (o->ags_state == AWAITABLE_STATE_INIT) {
1582 if (arg == NULL || arg == Py_None) {
1583 arg = o->ags_sendval;
1584 }
1585 o->ags_state = AWAITABLE_STATE_ITER;
1586 }
1587
1588 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1589 result = async_gen_unwrap_value(o->ags_gen, result);
1590
1591 if (result == NULL) {
1592 o->ags_state = AWAITABLE_STATE_CLOSED;
1593 }
1594
1595 return result;
1596}
1597
1598
1599static PyObject *
1600async_gen_asend_iternext(PyAsyncGenASend *o)
1601{
1602 return async_gen_asend_send(o, NULL);
1603}
1604
1605
1606static PyObject *
1607async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1608{
1609 PyObject *result;
1610
1611 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1612 PyErr_SetNone(PyExc_StopIteration);
1613 return NULL;
1614 }
1615
1616 result = gen_throw((PyGenObject*)o->ags_gen, args);
1617 result = async_gen_unwrap_value(o->ags_gen, result);
1618
1619 if (result == NULL) {
1620 o->ags_state = AWAITABLE_STATE_CLOSED;
1621 }
1622
1623 return result;
1624}
1625
1626
1627static PyObject *
1628async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1629{
1630 o->ags_state = AWAITABLE_STATE_CLOSED;
1631 Py_RETURN_NONE;
1632}
1633
1634
1635static PyMethodDef async_gen_asend_methods[] = {
1636 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1637 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1638 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1639 {NULL, NULL} /* Sentinel */
1640};
1641
1642
1643static PyAsyncMethods async_gen_asend_as_async = {
1644 PyObject_SelfIter, /* am_await */
1645 0, /* am_aiter */
1646 0 /* am_anext */
1647};
1648
1649
1650PyTypeObject _PyAsyncGenASend_Type = {
1651 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1652 "async_generator_asend", /* tp_name */
1653 sizeof(PyAsyncGenASend), /* tp_basicsize */
1654 0, /* tp_itemsize */
1655 /* methods */
1656 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
1657 0, /* tp_print */
1658 0, /* tp_getattr */
1659 0, /* tp_setattr */
1660 &async_gen_asend_as_async, /* tp_as_async */
1661 0, /* tp_repr */
1662 0, /* tp_as_number */
1663 0, /* tp_as_sequence */
1664 0, /* tp_as_mapping */
1665 0, /* tp_hash */
1666 0, /* tp_call */
1667 0, /* tp_str */
1668 PyObject_GenericGetAttr, /* tp_getattro */
1669 0, /* tp_setattro */
1670 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001671 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001672 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001673 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001674 0, /* tp_clear */
1675 0, /* tp_richcompare */
1676 0, /* tp_weaklistoffset */
1677 PyObject_SelfIter, /* tp_iter */
1678 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1679 async_gen_asend_methods, /* tp_methods */
1680 0, /* tp_members */
1681 0, /* tp_getset */
1682 0, /* tp_base */
1683 0, /* tp_dict */
1684 0, /* tp_descr_get */
1685 0, /* tp_descr_set */
1686 0, /* tp_dictoffset */
1687 0, /* tp_init */
1688 0, /* tp_alloc */
1689 0, /* tp_new */
1690};
1691
1692
1693static PyObject *
1694async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1695{
1696 PyAsyncGenASend *o;
1697 if (ag_asend_freelist_free) {
1698 ag_asend_freelist_free--;
1699 o = ag_asend_freelist[ag_asend_freelist_free];
1700 _Py_NewReference((PyObject *)o);
1701 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001702 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001703 if (o == NULL) {
1704 return NULL;
1705 }
1706 }
1707
1708 Py_INCREF(gen);
1709 o->ags_gen = gen;
1710
1711 Py_XINCREF(sendval);
1712 o->ags_sendval = sendval;
1713
1714 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001715
1716 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001717 return (PyObject*)o;
1718}
1719
1720
1721/* ---------- Async Generator Value Wrapper ------------ */
1722
1723
1724static void
1725async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1726{
Yury Selivanov29310c42016-11-08 19:46:22 -05001727 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001728 Py_CLEAR(o->agw_val);
1729 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1730 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1731 ag_value_freelist[ag_value_freelist_free++] = o;
1732 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001733 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001734 }
1735}
1736
1737
Yury Selivanov29310c42016-11-08 19:46:22 -05001738static int
1739async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1740 visitproc visit, void *arg)
1741{
1742 Py_VISIT(o->agw_val);
1743 return 0;
1744}
1745
1746
Yury Selivanoveb636452016-09-08 22:01:51 -07001747PyTypeObject _PyAsyncGenWrappedValue_Type = {
1748 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1749 "async_generator_wrapped_value", /* tp_name */
1750 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1751 0, /* tp_itemsize */
1752 /* methods */
1753 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
1754 0, /* tp_print */
1755 0, /* tp_getattr */
1756 0, /* tp_setattr */
1757 0, /* tp_as_async */
1758 0, /* tp_repr */
1759 0, /* tp_as_number */
1760 0, /* tp_as_sequence */
1761 0, /* tp_as_mapping */
1762 0, /* tp_hash */
1763 0, /* tp_call */
1764 0, /* tp_str */
1765 PyObject_GenericGetAttr, /* tp_getattro */
1766 0, /* tp_setattro */
1767 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001768 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001769 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001770 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001771 0, /* tp_clear */
1772 0, /* tp_richcompare */
1773 0, /* tp_weaklistoffset */
1774 0, /* tp_iter */
1775 0, /* tp_iternext */
1776 0, /* tp_methods */
1777 0, /* tp_members */
1778 0, /* tp_getset */
1779 0, /* tp_base */
1780 0, /* tp_dict */
1781 0, /* tp_descr_get */
1782 0, /* tp_descr_set */
1783 0, /* tp_dictoffset */
1784 0, /* tp_init */
1785 0, /* tp_alloc */
1786 0, /* tp_new */
1787};
1788
1789
1790PyObject *
1791_PyAsyncGenValueWrapperNew(PyObject *val)
1792{
1793 _PyAsyncGenWrappedValue *o;
1794 assert(val);
1795
1796 if (ag_value_freelist_free) {
1797 ag_value_freelist_free--;
1798 o = ag_value_freelist[ag_value_freelist_free];
1799 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1800 _Py_NewReference((PyObject*)o);
1801 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001802 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1803 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001804 if (o == NULL) {
1805 return NULL;
1806 }
1807 }
1808 o->agw_val = val;
1809 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001810 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001811 return (PyObject*)o;
1812}
1813
1814
1815/* ---------- Async Generator AThrow awaitable ------------ */
1816
1817
1818static void
1819async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1820{
Yury Selivanov29310c42016-11-08 19:46:22 -05001821 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001822 Py_CLEAR(o->agt_gen);
1823 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001824 PyObject_GC_Del(o);
1825}
1826
1827
1828static int
1829async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1830{
1831 Py_VISIT(o->agt_gen);
1832 Py_VISIT(o->agt_args);
1833 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001834}
1835
1836
1837static PyObject *
1838async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1839{
1840 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1841 PyFrameObject *f = gen->gi_frame;
1842 PyObject *retval;
1843
1844 if (f == NULL || f->f_stacktop == NULL ||
1845 o->agt_state == AWAITABLE_STATE_CLOSED) {
1846 PyErr_SetNone(PyExc_StopIteration);
1847 return NULL;
1848 }
1849
1850 if (o->agt_state == AWAITABLE_STATE_INIT) {
1851 if (o->agt_gen->ag_closed) {
1852 PyErr_SetNone(PyExc_StopIteration);
1853 return NULL;
1854 }
1855
1856 if (arg != Py_None) {
1857 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1858 return NULL;
1859 }
1860
1861 o->agt_state = AWAITABLE_STATE_ITER;
1862
1863 if (o->agt_args == NULL) {
1864 /* aclose() mode */
1865 o->agt_gen->ag_closed = 1;
1866
1867 retval = _gen_throw((PyGenObject *)gen,
1868 0, /* Do not close generator when
1869 PyExc_GeneratorExit is passed */
1870 PyExc_GeneratorExit, NULL, NULL);
1871
1872 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1873 Py_DECREF(retval);
1874 goto yield_close;
1875 }
1876 } else {
1877 PyObject *typ;
1878 PyObject *tb = NULL;
1879 PyObject *val = NULL;
1880
1881 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1882 &typ, &val, &tb)) {
1883 return NULL;
1884 }
1885
1886 retval = _gen_throw((PyGenObject *)gen,
1887 0, /* Do not close generator when
1888 PyExc_GeneratorExit is passed */
1889 typ, val, tb);
1890 retval = async_gen_unwrap_value(o->agt_gen, retval);
1891 }
1892 if (retval == NULL) {
1893 goto check_error;
1894 }
1895 return retval;
1896 }
1897
1898 assert(o->agt_state == AWAITABLE_STATE_ITER);
1899
1900 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1901 if (o->agt_args) {
1902 return async_gen_unwrap_value(o->agt_gen, retval);
1903 } else {
1904 /* aclose() mode */
1905 if (retval) {
1906 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1907 Py_DECREF(retval);
1908 goto yield_close;
1909 }
1910 else {
1911 return retval;
1912 }
1913 }
1914 else {
1915 goto check_error;
1916 }
1917 }
1918
1919yield_close:
1920 PyErr_SetString(
1921 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1922 return NULL;
1923
1924check_error:
Yury Selivanov41782e42016-11-16 18:16:17 -05001925 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
1926 o->agt_state = AWAITABLE_STATE_CLOSED;
1927 if (o->agt_args == NULL) {
1928 /* when aclose() is called we don't want to propagate
1929 StopAsyncIteration; just raise StopIteration, signalling
1930 that 'aclose()' is done. */
1931 PyErr_Clear();
1932 PyErr_SetNone(PyExc_StopIteration);
1933 }
1934 }
1935 else if (PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001936 o->agt_state = AWAITABLE_STATE_CLOSED;
1937 PyErr_Clear(); /* ignore these errors */
1938 PyErr_SetNone(PyExc_StopIteration);
1939 }
1940 return NULL;
1941}
1942
1943
1944static PyObject *
1945async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1946{
1947 PyObject *retval;
1948
1949 if (o->agt_state == AWAITABLE_STATE_INIT) {
1950 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1951 return NULL;
1952 }
1953
1954 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
1955 PyErr_SetNone(PyExc_StopIteration);
1956 return NULL;
1957 }
1958
1959 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1960 if (o->agt_args) {
1961 return async_gen_unwrap_value(o->agt_gen, retval);
1962 } else {
1963 /* aclose() mode */
1964 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1965 Py_DECREF(retval);
1966 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1967 return NULL;
1968 }
1969 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 */
2011 0, /* tp_print */
2012 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}