blob: 70d6e1492a4e42141dc0757e2f8c04dcbad85856 [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
4#include "frameobject.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00005#include "structmember.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00007
Yury Selivanoveb636452016-09-08 22:01:51 -07008static PyObject *gen_close(PyGenObject *, PyObject *);
9static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
10static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
11
12static char *NON_INIT_CORO_MSG = "can't send non-None value to a "
13 "just-started coroutine";
14
15static char *ASYNC_GEN_IGNORED_EXIT_MSG =
16 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100017
Martin v. Löwise440e472004-06-01 15:22:42 +000018static int
19gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
20{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 Py_VISIT((PyObject *)gen->gi_frame);
22 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020023 Py_VISIT(gen->gi_name);
24 Py_VISIT(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000026}
27
Antoine Pitrou58720d62013-08-05 23:26:40 +020028void
29_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020030{
31 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070032 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020033 PyObject *error_type, *error_value, *error_traceback;
34
35 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
36 /* Generator isn't paused, so no need to close */
37 return;
38
Yury Selivanoveb636452016-09-08 22:01:51 -070039 if (PyAsyncGen_CheckExact(self)) {
40 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
41 PyObject *finalizer = agen->ag_finalizer;
42 if (finalizer && !agen->ag_closed) {
43 /* Save the current exception, if any. */
44 PyErr_Fetch(&error_type, &error_value, &error_traceback);
45
46 res = PyObject_CallFunctionObjArgs(finalizer, self, NULL);
47
48 if (res == NULL) {
49 PyErr_WriteUnraisable(self);
50 } else {
51 Py_DECREF(res);
52 }
53 /* Restore the saved exception. */
54 PyErr_Restore(error_type, error_value, error_traceback);
55 return;
56 }
57 }
58
Antoine Pitrou796564c2013-07-30 19:59:21 +020059 /* Save the current exception, if any. */
60 PyErr_Fetch(&error_type, &error_value, &error_traceback);
61
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070062 /* If `gen` is a coroutine, and if it was never awaited on,
63 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070064 if (gen->gi_code != NULL &&
65 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
66 gen->gi_frame->f_lasti == -1) {
67 if (!error_value) {
68 PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
69 "coroutine '%.50S' was never awaited",
70 gen->gi_qualname);
71 }
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070072 }
73 else {
74 res = gen_close(gen, NULL);
75 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020076
Benjamin Petersonb88db872016-09-07 08:46:59 -070077 if (res == NULL) {
78 if (PyErr_Occurred())
79 PyErr_WriteUnraisable(self);
80 }
81 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020082 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070083 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020084
85 /* Restore the saved exception. */
86 PyErr_Restore(error_type, error_value, error_traceback);
87}
88
89static void
Martin v. Löwise440e472004-06-01 15:22:42 +000090gen_dealloc(PyGenObject *gen)
91{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (gen->gi_weakreflist != NULL)
97 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000098
Antoine Pitrou93963562013-05-14 20:37:52 +020099 _PyObject_GC_TRACK(self);
100
Antoine Pitrou796564c2013-07-30 19:59:21 +0200101 if (PyObject_CallFinalizerFromDealloc(self))
102 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200103
104 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700105 if (PyAsyncGen_CheckExact(gen)) {
106 /* We have to handle this case for asynchronous generators
107 right here, because this code has to be between UNTRACK
108 and GC_Del. */
109 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
110 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700111 if (gen->gi_frame != NULL) {
112 gen->gi_frame->f_gen = NULL;
113 Py_CLEAR(gen->gi_frame);
114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200116 Py_CLEAR(gen->gi_name);
117 Py_CLEAR(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000119}
120
121static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500122gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000123{
Antoine Pitrou93963562013-05-14 20:37:52 +0200124 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200126 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000127
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500128 if (gen->gi_running) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400129 char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700130 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400131 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700132 }
133 else if (PyAsyncGen_CheckExact(gen)) {
134 msg = "async generator already executing";
135 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400136 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500137 return NULL;
138 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200139 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500140 if (PyCoro_CheckExact(gen) && !closing) {
141 /* `gen` is an exhausted coroutine: raise an error,
142 except when called from gen_close(), which should
143 always be a silent method. */
144 PyErr_SetString(
145 PyExc_RuntimeError,
146 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700147 }
148 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500149 /* `gen` is an exhausted generator:
150 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700151 if (PyAsyncGen_CheckExact(gen)) {
152 PyErr_SetNone(PyExc_StopAsyncIteration);
153 }
154 else {
155 PyErr_SetNone(PyExc_StopIteration);
156 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500157 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 return NULL;
159 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000160
Antoine Pitrou93963562013-05-14 20:37:52 +0200161 if (f->f_lasti == -1) {
162 if (arg && arg != Py_None) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400163 char *msg = "can't send non-None value to a "
164 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700165 if (PyCoro_CheckExact(gen)) {
166 msg = NON_INIT_CORO_MSG;
167 }
168 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400169 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700170 "just-started async generator";
171 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400172 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200173 return NULL;
174 }
175 } else {
176 /* Push arg onto the frame's value stack */
177 result = arg ? arg : Py_None;
178 Py_INCREF(result);
179 *(f->f_stacktop++) = result;
180 }
181
182 /* Generators always return to their most recent caller, not
183 * necessarily their creator. */
184 Py_XINCREF(tstate->frame);
185 assert(f->f_back == NULL);
186 f->f_back = tstate->frame;
187
188 gen->gi_running = 1;
189 result = PyEval_EvalFrameEx(f, exc);
190 gen->gi_running = 0;
191
192 /* Don't keep the reference to f_back any longer than necessary. It
193 * may keep a chain of frames alive or it could create a reference
194 * cycle. */
195 assert(f->f_back == tstate->frame);
196 Py_CLEAR(f->f_back);
197
198 /* If the generator just returned (as opposed to yielding), signal
199 * that the generator is exhausted. */
200 if (result && f->f_stacktop == NULL) {
201 if (result == Py_None) {
202 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700203 if (PyAsyncGen_CheckExact(gen)) {
204 PyErr_SetNone(PyExc_StopAsyncIteration);
205 }
206 else {
207 PyErr_SetNone(PyExc_StopIteration);
208 }
209 }
210 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700211 /* Async generators cannot return anything but None */
212 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200213 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200214 }
215 Py_CLEAR(result);
216 }
Yury Selivanov68333392015-05-22 11:16:47 -0400217 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400218 /* Check for __future__ generator_stop and conditionally turn
219 * a leaking StopIteration into RuntimeError (with its cause
220 * set appropriately). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700221
222 const int check_stop_iter_error_flags = CO_FUTURE_GENERATOR_STOP |
223 CO_COROUTINE |
224 CO_ITERABLE_COROUTINE |
225 CO_ASYNC_GENERATOR;
226
227 if (gen->gi_code != NULL &&
228 ((PyCodeObject *)gen->gi_code)->co_flags &
229 check_stop_iter_error_flags)
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400230 {
Yury Selivanoveb636452016-09-08 22:01:51 -0700231 /* `gen` is either:
232 * a generator with CO_FUTURE_GENERATOR_STOP flag;
233 * a coroutine;
234 * a generator with CO_ITERABLE_COROUTINE flag
235 (decorated with types.coroutine decorator);
236 * an async generator.
237 */
238 const char *msg = "generator raised StopIteration";
239 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400240 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700241 }
242 else if PyAsyncGen_CheckExact(gen) {
243 msg = "async generator raised StopIteration";
244 }
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300245 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400246 }
Yury Selivanov68333392015-05-22 11:16:47 -0400247 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700248 /* `gen` is an ordinary generator without
249 CO_FUTURE_GENERATOR_STOP flag.
250 */
251
Yury Selivanov68333392015-05-22 11:16:47 -0400252 PyObject *exc, *val, *tb;
253
254 /* Pop the exception before issuing a warning. */
255 PyErr_Fetch(&exc, &val, &tb);
256
Martin Panter7e3a91a2016-02-10 04:40:48 +0000257 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Yury Selivanov68333392015-05-22 11:16:47 -0400258 "generator '%.50S' raised StopIteration",
259 gen->gi_qualname)) {
260 /* Warning was converted to an error. */
261 Py_XDECREF(exc);
262 Py_XDECREF(val);
263 Py_XDECREF(tb);
264 }
265 else {
266 PyErr_Restore(exc, val, tb);
267 }
268 }
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400269 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700270 else if (PyAsyncGen_CheckExact(gen) && !result &&
271 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
272 {
273 /* code in `gen` raised a StopAsyncIteration error:
274 raise a RuntimeError.
275 */
276 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300277 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700278 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200279
280 if (!result || f->f_stacktop == NULL) {
281 /* generator can't be rerun, so release the frame */
282 /* first clean reference cycle through stored exception traceback */
283 PyObject *t, *v, *tb;
284 t = f->f_exc_type;
285 v = f->f_exc_value;
286 tb = f->f_exc_traceback;
287 f->f_exc_type = NULL;
288 f->f_exc_value = NULL;
289 f->f_exc_traceback = NULL;
290 Py_XDECREF(t);
291 Py_XDECREF(v);
292 Py_XDECREF(tb);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200293 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200294 gen->gi_frame = NULL;
295 Py_DECREF(f);
296 }
297
298 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000299}
300
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000301PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000302"send(arg) -> send 'arg' into generator,\n\
303return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000304
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500305PyObject *
306_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000307{
Yury Selivanov77c96812016-02-13 17:59:05 -0500308 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000309}
310
311PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400312"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000313
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000314/*
315 * This helper function is used by gen_close and gen_throw to
316 * close a subiterator being delegated to by yield-from.
317 */
318
Antoine Pitrou93963562013-05-14 20:37:52 +0200319static int
320gen_close_iter(PyObject *yf)
321{
322 PyObject *retval = NULL;
323 _Py_IDENTIFIER(close);
324
Yury Selivanoveb636452016-09-08 22:01:51 -0700325 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200326 retval = gen_close((PyGenObject *)yf, NULL);
327 if (retval == NULL)
328 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700329 }
330 else {
Antoine Pitrou93963562013-05-14 20:37:52 +0200331 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
332 if (meth == NULL) {
333 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
334 PyErr_WriteUnraisable(yf);
335 PyErr_Clear();
Yury Selivanoveb636452016-09-08 22:01:51 -0700336 }
337 else {
Victor Stinner3466bde2016-09-05 18:16:01 -0700338 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200339 Py_DECREF(meth);
340 if (retval == NULL)
341 return -1;
342 }
343 }
344 Py_XDECREF(retval);
345 return 0;
346}
347
Yury Selivanovc724bae2016-03-02 11:30:46 -0500348PyObject *
349_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500350{
Antoine Pitrou93963562013-05-14 20:37:52 +0200351 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500352 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200353
354 if (f && f->f_stacktop) {
355 PyObject *bytecode = f->f_code->co_code;
356 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
357
Serhiy Storchakaab874002016-09-11 13:48:15 +0300358 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200359 return NULL;
360 yf = f->f_stacktop[-1];
361 Py_INCREF(yf);
362 }
363
364 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500365}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000366
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000367static PyObject *
368gen_close(PyGenObject *gen, PyObject *args)
369{
Antoine Pitrou93963562013-05-14 20:37:52 +0200370 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500371 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200372 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000373
Antoine Pitrou93963562013-05-14 20:37:52 +0200374 if (yf) {
375 gen->gi_running = 1;
376 err = gen_close_iter(yf);
377 gen->gi_running = 0;
378 Py_DECREF(yf);
379 }
380 if (err == 0)
381 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500382 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200383 if (retval) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400384 char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700385 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400386 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700387 } else if (PyAsyncGen_CheckExact(gen)) {
388 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
389 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200390 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400391 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 return NULL;
393 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200394 if (PyErr_ExceptionMatches(PyExc_StopIteration)
395 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
396 PyErr_Clear(); /* ignore these errors */
397 Py_INCREF(Py_None);
398 return Py_None;
399 }
400 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000401}
402
Antoine Pitrou93963562013-05-14 20:37:52 +0200403
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000404PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000405"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
406return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000407
408static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700409_gen_throw(PyGenObject *gen, int close_on_genexit,
410 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000411{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500412 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000413 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000414
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000415 if (yf) {
416 PyObject *ret;
417 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700418 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
419 close_on_genexit
420 ) {
421 /* Asynchronous generators *should not* be closed right away.
422 We have to allow some awaits to work it through, hence the
423 `close_on_genexit` parameter here.
424 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500425 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200426 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500427 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000428 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000429 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500430 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000431 goto throw_here;
432 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700433 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
434 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500435 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700436 /* Close the generator that we are currently iterating with
437 'yield from' or awaiting on with 'await'. */
438 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
439 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500440 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000441 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700442 /* `yf` is an iterator or a coroutine-like object. */
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000443 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000444 if (meth == NULL) {
445 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
446 Py_DECREF(yf);
447 return NULL;
448 }
449 PyErr_Clear();
450 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000451 goto throw_here;
452 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500453 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700454 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500455 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000456 Py_DECREF(meth);
457 }
458 Py_DECREF(yf);
459 if (!ret) {
460 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500461 /* Pop subiterator from stack */
462 ret = *(--gen->gi_frame->f_stacktop);
463 assert(ret == yf);
464 Py_DECREF(ret);
465 /* Termination repetition of YIELD_FROM */
Serhiy Storchakaab874002016-09-11 13:48:15 +0300466 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000467 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500468 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000469 Py_DECREF(val);
470 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500471 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000472 }
473 }
474 return ret;
475 }
476
477throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* First, check the traceback argument, replacing None with
479 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400480 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400482 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 else if (tb != NULL && !PyTraceBack_Check(tb)) {
484 PyErr_SetString(PyExc_TypeError,
485 "throw() third argument must be a traceback object");
486 return NULL;
487 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_INCREF(typ);
490 Py_XINCREF(val);
491 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000492
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400493 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 else if (PyExceptionInstance_Check(typ)) {
497 /* Raising an instance. The value should be a dummy. */
498 if (val && val != Py_None) {
499 PyErr_SetString(PyExc_TypeError,
500 "instance exception may not have a separate value");
501 goto failed_throw;
502 }
503 else {
504 /* Normalize to raise <class>, <instance> */
505 Py_XDECREF(val);
506 val = typ;
507 typ = PyExceptionInstance_Class(typ);
508 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200509
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400510 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200511 /* Returns NULL if there's no traceback */
512 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 }
514 }
515 else {
516 /* Not something you can raise. throw() fails. */
517 PyErr_Format(PyExc_TypeError,
518 "exceptions must be classes or instances "
519 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000520 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 goto failed_throw;
522 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500525 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000526
527failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* Didn't use our arguments, so restore their original refcounts */
529 Py_DECREF(typ);
530 Py_XDECREF(val);
531 Py_XDECREF(tb);
532 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000533}
534
535
536static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700537gen_throw(PyGenObject *gen, PyObject *args)
538{
539 PyObject *typ;
540 PyObject *tb = NULL;
541 PyObject *val = NULL;
542
543 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
544 return NULL;
545 }
546
547 return _gen_throw(gen, 1, typ, val, tb);
548}
549
550
551static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000552gen_iternext(PyGenObject *gen)
553{
Yury Selivanov77c96812016-02-13 17:59:05 -0500554 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000555}
556
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000557/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200558 * Set StopIteration with specified value. Value can be arbitrary object
559 * or NULL.
560 *
561 * Returns 0 if StopIteration is set and -1 if any other exception is set.
562 */
563int
564_PyGen_SetStopIterationValue(PyObject *value)
565{
566 PyObject *e;
567
568 if (value == NULL ||
569 (!PyTuple_Check(value) &&
570 !PyObject_TypeCheck(value, (PyTypeObject *) PyExc_StopIteration)))
571 {
572 /* Delay exception instantiation if we can */
573 PyErr_SetObject(PyExc_StopIteration, value);
574 return 0;
575 }
576 /* Construct an exception instance manually with
577 * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject.
578 *
579 * We do this to handle a situation when "value" is a tuple, in which
580 * case PyErr_SetObject would set the value of StopIteration to
581 * the first element of the tuple.
582 *
583 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
584 */
585 e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL);
586 if (e == NULL) {
587 return -1;
588 }
589 PyErr_SetObject(PyExc_StopIteration, e);
590 Py_DECREF(e);
591 return 0;
592}
593
594/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000595 * If StopIteration exception is set, fetches its 'value'
596 * attribute if any, otherwise sets pvalue to None.
597 *
598 * Returns 0 if no exception or StopIteration is set.
599 * If any other exception is set, returns -1 and leaves
600 * pvalue unchanged.
601 */
602
603int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200604_PyGen_FetchStopIterationValue(PyObject **pvalue)
605{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000606 PyObject *et, *ev, *tb;
607 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500608
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000609 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
610 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200611 if (ev) {
612 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300613 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200614 value = ((PyStopIterationObject *)ev)->value;
615 Py_INCREF(value);
616 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200617 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
618 /* Avoid normalisation and take ev as value.
619 *
620 * Normalization is required if the value is a tuple, in
621 * that case the value of StopIteration would be set to
622 * the first element of the tuple.
623 *
624 * (See _PyErr_CreateException code for details.)
625 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200626 value = ev;
627 } else {
628 /* normalisation required */
629 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300630 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200631 PyErr_Restore(et, ev, tb);
632 return -1;
633 }
634 value = ((PyStopIterationObject *)ev)->value;
635 Py_INCREF(value);
636 Py_DECREF(ev);
637 }
638 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000639 Py_XDECREF(et);
640 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000641 } else if (PyErr_Occurred()) {
642 return -1;
643 }
644 if (value == NULL) {
645 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100646 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000647 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000648 *pvalue = value;
649 return 0;
650}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000651
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000652static PyObject *
653gen_repr(PyGenObject *gen)
654{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400655 return PyUnicode_FromFormat("<generator object %S at %p>",
656 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000657}
658
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000659static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200660gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000661{
Victor Stinner40ee3012014-06-16 15:59:28 +0200662 Py_INCREF(op->gi_name);
663 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000664}
665
Victor Stinner40ee3012014-06-16 15:59:28 +0200666static int
667gen_set_name(PyGenObject *op, PyObject *value)
668{
Victor Stinner40ee3012014-06-16 15:59:28 +0200669 /* Not legal to del gen.gi_name or to set it to anything
670 * other than a string object. */
671 if (value == NULL || !PyUnicode_Check(value)) {
672 PyErr_SetString(PyExc_TypeError,
673 "__name__ must be set to a string object");
674 return -1;
675 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200676 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300677 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200678 return 0;
679}
680
681static PyObject *
682gen_get_qualname(PyGenObject *op)
683{
684 Py_INCREF(op->gi_qualname);
685 return op->gi_qualname;
686}
687
688static int
689gen_set_qualname(PyGenObject *op, PyObject *value)
690{
Victor Stinner40ee3012014-06-16 15:59:28 +0200691 /* Not legal to del gen.__qualname__ or to set it to anything
692 * other than a string object. */
693 if (value == NULL || !PyUnicode_Check(value)) {
694 PyErr_SetString(PyExc_TypeError,
695 "__qualname__ must be set to a string object");
696 return -1;
697 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200698 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300699 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200700 return 0;
701}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000702
Yury Selivanove13f8f32015-07-03 00:23:30 -0400703static PyObject *
704gen_getyieldfrom(PyGenObject *gen)
705{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500706 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400707 if (yf == NULL)
708 Py_RETURN_NONE;
709 return yf;
710}
711
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000712static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200713 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
714 PyDoc_STR("name of the generator")},
715 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
716 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400717 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
718 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200719 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000720};
721
Martin v. Löwise440e472004-06-01 15:22:42 +0000722static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200723 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
724 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
725 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000727};
728
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000729static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500730 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
732 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
733 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000734};
735
Martin v. Löwise440e472004-06-01 15:22:42 +0000736PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyVarObject_HEAD_INIT(&PyType_Type, 0)
738 "generator", /* tp_name */
739 sizeof(PyGenObject), /* tp_basicsize */
740 0, /* tp_itemsize */
741 /* methods */
742 (destructor)gen_dealloc, /* tp_dealloc */
743 0, /* tp_print */
744 0, /* tp_getattr */
745 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400746 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 (reprfunc)gen_repr, /* tp_repr */
748 0, /* tp_as_number */
749 0, /* tp_as_sequence */
750 0, /* tp_as_mapping */
751 0, /* tp_hash */
752 0, /* tp_call */
753 0, /* tp_str */
754 PyObject_GenericGetAttr, /* tp_getattro */
755 0, /* tp_setattro */
756 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200757 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
758 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 0, /* tp_doc */
760 (traverseproc)gen_traverse, /* tp_traverse */
761 0, /* tp_clear */
762 0, /* tp_richcompare */
763 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400764 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 (iternextfunc)gen_iternext, /* tp_iternext */
766 gen_methods, /* tp_methods */
767 gen_memberlist, /* tp_members */
768 gen_getsetlist, /* tp_getset */
769 0, /* tp_base */
770 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 0, /* tp_descr_get */
773 0, /* tp_descr_set */
774 0, /* tp_dictoffset */
775 0, /* tp_init */
776 0, /* tp_alloc */
777 0, /* tp_new */
778 0, /* tp_free */
779 0, /* tp_is_gc */
780 0, /* tp_bases */
781 0, /* tp_mro */
782 0, /* tp_cache */
783 0, /* tp_subclasses */
784 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200785 0, /* tp_del */
786 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200787 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000788};
789
Yury Selivanov5376ba92015-06-22 12:19:30 -0400790static PyObject *
791gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
792 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000793{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400794 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (gen == NULL) {
796 Py_DECREF(f);
797 return NULL;
798 }
799 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200800 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 Py_INCREF(f->f_code);
802 gen->gi_code = (PyObject *)(f->f_code);
803 gen->gi_running = 0;
804 gen->gi_weakreflist = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200805 if (name != NULL)
806 gen->gi_name = name;
807 else
808 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
809 Py_INCREF(gen->gi_name);
810 if (qualname != NULL)
811 gen->gi_qualname = qualname;
812 else
813 gen->gi_qualname = gen->gi_name;
814 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 _PyObject_GC_TRACK(gen);
816 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000817}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000818
Victor Stinner40ee3012014-06-16 15:59:28 +0200819PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400820PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
821{
822 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
823}
824
825PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200826PyGen_New(PyFrameObject *f)
827{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400828 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200829}
830
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831int
832PyGen_NeedsFinalizing(PyGenObject *gen)
833{
Antoine Pitrou93963562013-05-14 20:37:52 +0200834 int i;
835 PyFrameObject *f = gen->gi_frame;
836
837 if (f == NULL || f->f_stacktop == NULL)
838 return 0; /* no frame or empty blockstack == no finalization */
839
840 /* Any block type besides a loop requires cleanup. */
841 for (i = 0; i < f->f_iblock; i++)
842 if (f->f_blockstack[i].b_type != SETUP_LOOP)
843 return 1;
844
845 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000847}
Yury Selivanov75445082015-05-11 22:57:16 -0400848
Yury Selivanov5376ba92015-06-22 12:19:30 -0400849/* Coroutine Object */
850
851typedef struct {
852 PyObject_HEAD
853 PyCoroObject *cw_coroutine;
854} PyCoroWrapper;
855
856static int
857gen_is_coroutine(PyObject *o)
858{
859 if (PyGen_CheckExact(o)) {
860 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
861 if (code->co_flags & CO_ITERABLE_COROUTINE) {
862 return 1;
863 }
864 }
865 return 0;
866}
867
Yury Selivanov75445082015-05-11 22:57:16 -0400868/*
869 * This helper function returns an awaitable for `o`:
870 * - `o` if `o` is a coroutine-object;
871 * - `type(o)->tp_as_async->am_await(o)`
872 *
873 * Raises a TypeError if it's not possible to return
874 * an awaitable and returns NULL.
875 */
876PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400877_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400878{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400879 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400880 PyTypeObject *ot;
881
Yury Selivanov5376ba92015-06-22 12:19:30 -0400882 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
883 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400884 Py_INCREF(o);
885 return o;
886 }
887
888 ot = Py_TYPE(o);
889 if (ot->tp_as_async != NULL) {
890 getter = ot->tp_as_async->am_await;
891 }
892 if (getter != NULL) {
893 PyObject *res = (*getter)(o);
894 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400895 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
896 /* __await__ must return an *iterator*, not
897 a coroutine or another awaitable (see PEP 492) */
898 PyErr_SetString(PyExc_TypeError,
899 "__await__() returned a coroutine");
900 Py_CLEAR(res);
901 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400902 PyErr_Format(PyExc_TypeError,
903 "__await__() returned non-iterator "
904 "of type '%.100s'",
905 Py_TYPE(res)->tp_name);
906 Py_CLEAR(res);
907 }
Yury Selivanov75445082015-05-11 22:57:16 -0400908 }
909 return res;
910 }
911
912 PyErr_Format(PyExc_TypeError,
913 "object %.100s can't be used in 'await' expression",
914 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400915 return NULL;
916}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400917
918static PyObject *
919coro_repr(PyCoroObject *coro)
920{
921 return PyUnicode_FromFormat("<coroutine object %S at %p>",
922 coro->cr_qualname, coro);
923}
924
925static PyObject *
926coro_await(PyCoroObject *coro)
927{
928 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
929 if (cw == NULL) {
930 return NULL;
931 }
932 Py_INCREF(coro);
933 cw->cw_coroutine = coro;
934 _PyObject_GC_TRACK(cw);
935 return (PyObject *)cw;
936}
937
Yury Selivanove13f8f32015-07-03 00:23:30 -0400938static PyObject *
939coro_get_cr_await(PyCoroObject *coro)
940{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500941 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400942 if (yf == NULL)
943 Py_RETURN_NONE;
944 return yf;
945}
946
Yury Selivanov5376ba92015-06-22 12:19:30 -0400947static PyGetSetDef coro_getsetlist[] = {
948 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
949 PyDoc_STR("name of the coroutine")},
950 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
951 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400952 {"cr_await", (getter)coro_get_cr_await, NULL,
953 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400954 {NULL} /* Sentinel */
955};
956
957static PyMemberDef coro_memberlist[] = {
958 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
959 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
960 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
961 {NULL} /* Sentinel */
962};
963
964PyDoc_STRVAR(coro_send_doc,
965"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400966return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400967
968PyDoc_STRVAR(coro_throw_doc,
969"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400970return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400971
972PyDoc_STRVAR(coro_close_doc,
973"close() -> raise GeneratorExit inside coroutine.");
974
975static PyMethodDef coro_methods[] = {
976 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
977 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
978 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
979 {NULL, NULL} /* Sentinel */
980};
981
982static PyAsyncMethods coro_as_async = {
983 (unaryfunc)coro_await, /* am_await */
984 0, /* am_aiter */
985 0 /* am_anext */
986};
987
988PyTypeObject PyCoro_Type = {
989 PyVarObject_HEAD_INIT(&PyType_Type, 0)
990 "coroutine", /* tp_name */
991 sizeof(PyCoroObject), /* tp_basicsize */
992 0, /* tp_itemsize */
993 /* methods */
994 (destructor)gen_dealloc, /* tp_dealloc */
995 0, /* tp_print */
996 0, /* tp_getattr */
997 0, /* tp_setattr */
998 &coro_as_async, /* tp_as_async */
999 (reprfunc)coro_repr, /* tp_repr */
1000 0, /* tp_as_number */
1001 0, /* tp_as_sequence */
1002 0, /* tp_as_mapping */
1003 0, /* tp_hash */
1004 0, /* tp_call */
1005 0, /* tp_str */
1006 PyObject_GenericGetAttr, /* tp_getattro */
1007 0, /* tp_setattro */
1008 0, /* tp_as_buffer */
1009 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1010 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1011 0, /* tp_doc */
1012 (traverseproc)gen_traverse, /* tp_traverse */
1013 0, /* tp_clear */
1014 0, /* tp_richcompare */
1015 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1016 0, /* tp_iter */
1017 0, /* tp_iternext */
1018 coro_methods, /* tp_methods */
1019 coro_memberlist, /* tp_members */
1020 coro_getsetlist, /* tp_getset */
1021 0, /* tp_base */
1022 0, /* tp_dict */
1023 0, /* tp_descr_get */
1024 0, /* tp_descr_set */
1025 0, /* tp_dictoffset */
1026 0, /* tp_init */
1027 0, /* tp_alloc */
1028 0, /* tp_new */
1029 0, /* tp_free */
1030 0, /* tp_is_gc */
1031 0, /* tp_bases */
1032 0, /* tp_mro */
1033 0, /* tp_cache */
1034 0, /* tp_subclasses */
1035 0, /* tp_weaklist */
1036 0, /* tp_del */
1037 0, /* tp_version_tag */
1038 _PyGen_Finalize, /* tp_finalize */
1039};
1040
1041static void
1042coro_wrapper_dealloc(PyCoroWrapper *cw)
1043{
1044 _PyObject_GC_UNTRACK((PyObject *)cw);
1045 Py_CLEAR(cw->cw_coroutine);
1046 PyObject_GC_Del(cw);
1047}
1048
1049static PyObject *
1050coro_wrapper_iternext(PyCoroWrapper *cw)
1051{
Yury Selivanov77c96812016-02-13 17:59:05 -05001052 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001053}
1054
1055static PyObject *
1056coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1057{
Yury Selivanov77c96812016-02-13 17:59:05 -05001058 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001059}
1060
1061static PyObject *
1062coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1063{
1064 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1065}
1066
1067static PyObject *
1068coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1069{
1070 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1071}
1072
1073static int
1074coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1075{
1076 Py_VISIT((PyObject *)cw->cw_coroutine);
1077 return 0;
1078}
1079
1080static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001081 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1082 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1083 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001084 {NULL, NULL} /* Sentinel */
1085};
1086
1087PyTypeObject _PyCoroWrapper_Type = {
1088 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1089 "coroutine_wrapper",
1090 sizeof(PyCoroWrapper), /* tp_basicsize */
1091 0, /* tp_itemsize */
1092 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
1093 0, /* tp_print */
1094 0, /* tp_getattr */
1095 0, /* tp_setattr */
1096 0, /* tp_as_async */
1097 0, /* tp_repr */
1098 0, /* tp_as_number */
1099 0, /* tp_as_sequence */
1100 0, /* tp_as_mapping */
1101 0, /* tp_hash */
1102 0, /* tp_call */
1103 0, /* tp_str */
1104 PyObject_GenericGetAttr, /* tp_getattro */
1105 0, /* tp_setattro */
1106 0, /* tp_as_buffer */
1107 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1108 "A wrapper object implementing __await__ for coroutines.",
1109 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1110 0, /* tp_clear */
1111 0, /* tp_richcompare */
1112 0, /* tp_weaklistoffset */
1113 PyObject_SelfIter, /* tp_iter */
1114 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1115 coro_wrapper_methods, /* tp_methods */
1116 0, /* tp_members */
1117 0, /* tp_getset */
1118 0, /* tp_base */
1119 0, /* tp_dict */
1120 0, /* tp_descr_get */
1121 0, /* tp_descr_set */
1122 0, /* tp_dictoffset */
1123 0, /* tp_init */
1124 0, /* tp_alloc */
1125 0, /* tp_new */
1126 PyObject_Del, /* tp_free */
1127};
1128
1129PyObject *
1130PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1131{
1132 return gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1133}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001134
1135
1136/* __aiter__ wrapper; see http://bugs.python.org/issue27243 for details. */
1137
1138typedef struct {
1139 PyObject_HEAD
Yury Selivanoveb636452016-09-08 22:01:51 -07001140 PyObject *ags_aiter;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001141} PyAIterWrapper;
1142
1143
1144static PyObject *
1145aiter_wrapper_iternext(PyAIterWrapper *aw)
1146{
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001147 _PyGen_SetStopIterationValue(aw->ags_aiter);
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001148 return NULL;
1149}
1150
1151static int
1152aiter_wrapper_traverse(PyAIterWrapper *aw, visitproc visit, void *arg)
1153{
Yury Selivanoveb636452016-09-08 22:01:51 -07001154 Py_VISIT((PyObject *)aw->ags_aiter);
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001155 return 0;
1156}
1157
1158static void
1159aiter_wrapper_dealloc(PyAIterWrapper *aw)
1160{
1161 _PyObject_GC_UNTRACK((PyObject *)aw);
Yury Selivanoveb636452016-09-08 22:01:51 -07001162 Py_CLEAR(aw->ags_aiter);
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001163 PyObject_GC_Del(aw);
1164}
1165
1166static PyAsyncMethods aiter_wrapper_as_async = {
1167 PyObject_SelfIter, /* am_await */
1168 0, /* am_aiter */
1169 0 /* am_anext */
1170};
1171
1172PyTypeObject _PyAIterWrapper_Type = {
1173 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1174 "aiter_wrapper",
1175 sizeof(PyAIterWrapper), /* tp_basicsize */
1176 0, /* tp_itemsize */
1177 (destructor)aiter_wrapper_dealloc, /* destructor tp_dealloc */
1178 0, /* tp_print */
1179 0, /* tp_getattr */
1180 0, /* tp_setattr */
1181 &aiter_wrapper_as_async, /* tp_as_async */
1182 0, /* tp_repr */
1183 0, /* tp_as_number */
1184 0, /* tp_as_sequence */
1185 0, /* tp_as_mapping */
1186 0, /* tp_hash */
1187 0, /* tp_call */
1188 0, /* tp_str */
1189 PyObject_GenericGetAttr, /* tp_getattro */
1190 0, /* tp_setattro */
1191 0, /* tp_as_buffer */
1192 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1193 "A wrapper object for __aiter__ bakwards compatibility.",
1194 (traverseproc)aiter_wrapper_traverse, /* tp_traverse */
1195 0, /* tp_clear */
1196 0, /* tp_richcompare */
1197 0, /* tp_weaklistoffset */
1198 PyObject_SelfIter, /* tp_iter */
1199 (iternextfunc)aiter_wrapper_iternext, /* tp_iternext */
1200 0, /* tp_methods */
1201 0, /* tp_members */
1202 0, /* tp_getset */
1203 0, /* tp_base */
1204 0, /* tp_dict */
1205 0, /* tp_descr_get */
1206 0, /* tp_descr_set */
1207 0, /* tp_dictoffset */
1208 0, /* tp_init */
1209 0, /* tp_alloc */
1210 0, /* tp_new */
1211 PyObject_Del, /* tp_free */
1212};
1213
1214
1215PyObject *
1216_PyAIterWrapper_New(PyObject *aiter)
1217{
1218 PyAIterWrapper *aw = PyObject_GC_New(PyAIterWrapper,
1219 &_PyAIterWrapper_Type);
1220 if (aw == NULL) {
1221 return NULL;
1222 }
1223 Py_INCREF(aiter);
Yury Selivanoveb636452016-09-08 22:01:51 -07001224 aw->ags_aiter = aiter;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001225 _PyObject_GC_TRACK(aw);
1226 return (PyObject *)aw;
1227}
Yury Selivanoveb636452016-09-08 22:01:51 -07001228
1229
1230/* ========= Asynchronous Generators ========= */
1231
1232
1233typedef enum {
1234 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1235 AWAITABLE_STATE_ITER, /* being iterated */
1236 AWAITABLE_STATE_CLOSED, /* closed */
1237} AwaitableState;
1238
1239
1240typedef struct {
1241 PyObject_HEAD
1242 PyAsyncGenObject *ags_gen;
1243
1244 /* Can be NULL, when in the __anext__() mode
1245 (equivalent of "asend(None)") */
1246 PyObject *ags_sendval;
1247
1248 AwaitableState ags_state;
1249} PyAsyncGenASend;
1250
1251
1252typedef struct {
1253 PyObject_HEAD
1254 PyAsyncGenObject *agt_gen;
1255
1256 /* Can be NULL, when in the "aclose()" mode
1257 (equivalent of "athrow(GeneratorExit)") */
1258 PyObject *agt_args;
1259
1260 AwaitableState agt_state;
1261} PyAsyncGenAThrow;
1262
1263
1264typedef struct {
1265 PyObject_HEAD
1266 PyObject *agw_val;
1267} _PyAsyncGenWrappedValue;
1268
1269
1270#ifndef _PyAsyncGen_MAXFREELIST
1271#define _PyAsyncGen_MAXFREELIST 80
1272#endif
1273
1274/* Freelists boost performance 6-10%; they also reduce memory
1275 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1276 are short-living objects that are instantiated for every
1277 __anext__ call.
1278*/
1279
1280static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1281static int ag_value_freelist_free = 0;
1282
1283static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1284static int ag_asend_freelist_free = 0;
1285
1286#define _PyAsyncGenWrappedValue_CheckExact(o) \
1287 (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type)
1288
1289#define PyAsyncGenASend_CheckExact(o) \
1290 (Py_TYPE(o) == &_PyAsyncGenASend_Type)
1291
1292
1293static int
1294async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1295{
1296 Py_VISIT(gen->ag_finalizer);
1297 return gen_traverse((PyGenObject*)gen, visit, arg);
1298}
1299
1300
1301static PyObject *
1302async_gen_repr(PyAsyncGenObject *o)
1303{
1304 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1305 o->ag_qualname, o);
1306}
1307
1308
1309static int
1310async_gen_init_hooks(PyAsyncGenObject *o)
1311{
1312 PyThreadState *tstate;
1313 PyObject *finalizer;
1314 PyObject *firstiter;
1315
1316 if (o->ag_hooks_inited) {
1317 return 0;
1318 }
1319
1320 o->ag_hooks_inited = 1;
1321
1322 tstate = PyThreadState_GET();
1323
1324 finalizer = tstate->async_gen_finalizer;
1325 if (finalizer) {
1326 Py_INCREF(finalizer);
1327 o->ag_finalizer = finalizer;
1328 }
1329
1330 firstiter = tstate->async_gen_firstiter;
1331 if (firstiter) {
1332 PyObject *res;
1333
1334 Py_INCREF(firstiter);
1335 res = PyObject_CallFunction(firstiter, "O", o);
1336 Py_DECREF(firstiter);
1337 if (res == NULL) {
1338 return 1;
1339 }
1340 Py_DECREF(res);
1341 }
1342
1343 return 0;
1344}
1345
1346
1347static PyObject *
1348async_gen_anext(PyAsyncGenObject *o)
1349{
1350 if (async_gen_init_hooks(o)) {
1351 return NULL;
1352 }
1353 return async_gen_asend_new(o, NULL);
1354}
1355
1356
1357static PyObject *
1358async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1359{
1360 if (async_gen_init_hooks(o)) {
1361 return NULL;
1362 }
1363 return async_gen_asend_new(o, arg);
1364}
1365
1366
1367static PyObject *
1368async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1369{
1370 if (async_gen_init_hooks(o)) {
1371 return NULL;
1372 }
1373 return async_gen_athrow_new(o, NULL);
1374}
1375
1376static PyObject *
1377async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1378{
1379 if (async_gen_init_hooks(o)) {
1380 return NULL;
1381 }
1382 return async_gen_athrow_new(o, args);
1383}
1384
1385
1386static PyGetSetDef async_gen_getsetlist[] = {
1387 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1388 PyDoc_STR("name of the async generator")},
1389 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1390 PyDoc_STR("qualified name of the async generator")},
1391 {"ag_await", (getter)coro_get_cr_await, NULL,
1392 PyDoc_STR("object being awaited on, or None")},
1393 {NULL} /* Sentinel */
1394};
1395
1396static PyMemberDef async_gen_memberlist[] = {
1397 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
1398 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY},
1399 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1400 {NULL} /* Sentinel */
1401};
1402
1403PyDoc_STRVAR(async_aclose_doc,
1404"aclose() -> raise GeneratorExit inside generator.");
1405
1406PyDoc_STRVAR(async_asend_doc,
1407"asend(v) -> send 'v' in generator.");
1408
1409PyDoc_STRVAR(async_athrow_doc,
1410"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1411
1412static PyMethodDef async_gen_methods[] = {
1413 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1414 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1415 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
1416 {NULL, NULL} /* Sentinel */
1417};
1418
1419
1420static PyAsyncMethods async_gen_as_async = {
1421 0, /* am_await */
1422 PyObject_SelfIter, /* am_aiter */
1423 (unaryfunc)async_gen_anext /* am_anext */
1424};
1425
1426
1427PyTypeObject PyAsyncGen_Type = {
1428 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1429 "async_generator", /* tp_name */
1430 sizeof(PyAsyncGenObject), /* tp_basicsize */
1431 0, /* tp_itemsize */
1432 /* methods */
1433 (destructor)gen_dealloc, /* tp_dealloc */
1434 0, /* tp_print */
1435 0, /* tp_getattr */
1436 0, /* tp_setattr */
1437 &async_gen_as_async, /* tp_as_async */
1438 (reprfunc)async_gen_repr, /* tp_repr */
1439 0, /* tp_as_number */
1440 0, /* tp_as_sequence */
1441 0, /* tp_as_mapping */
1442 0, /* tp_hash */
1443 0, /* tp_call */
1444 0, /* tp_str */
1445 PyObject_GenericGetAttr, /* tp_getattro */
1446 0, /* tp_setattro */
1447 0, /* tp_as_buffer */
1448 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1449 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1450 0, /* tp_doc */
1451 (traverseproc)async_gen_traverse, /* tp_traverse */
1452 0, /* tp_clear */
1453 0, /* tp_richcompare */
1454 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1455 0, /* tp_iter */
1456 0, /* tp_iternext */
1457 async_gen_methods, /* tp_methods */
1458 async_gen_memberlist, /* tp_members */
1459 async_gen_getsetlist, /* tp_getset */
1460 0, /* tp_base */
1461 0, /* tp_dict */
1462 0, /* tp_descr_get */
1463 0, /* tp_descr_set */
1464 0, /* tp_dictoffset */
1465 0, /* tp_init */
1466 0, /* tp_alloc */
1467 0, /* tp_new */
1468 0, /* tp_free */
1469 0, /* tp_is_gc */
1470 0, /* tp_bases */
1471 0, /* tp_mro */
1472 0, /* tp_cache */
1473 0, /* tp_subclasses */
1474 0, /* tp_weaklist */
1475 0, /* tp_del */
1476 0, /* tp_version_tag */
1477 _PyGen_Finalize, /* tp_finalize */
1478};
1479
1480
1481PyObject *
1482PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1483{
1484 PyAsyncGenObject *o;
1485 o = (PyAsyncGenObject *)gen_new_with_qualname(
1486 &PyAsyncGen_Type, f, name, qualname);
1487 if (o == NULL) {
1488 return NULL;
1489 }
1490 o->ag_finalizer = NULL;
1491 o->ag_closed = 0;
1492 o->ag_hooks_inited = 0;
1493 return (PyObject*)o;
1494}
1495
1496
1497int
1498PyAsyncGen_ClearFreeLists(void)
1499{
1500 int ret = ag_value_freelist_free + ag_asend_freelist_free;
1501
1502 while (ag_value_freelist_free) {
1503 _PyAsyncGenWrappedValue *o;
1504 o = ag_value_freelist[--ag_value_freelist_free];
1505 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1506 PyObject_Del(o);
1507 }
1508
1509 while (ag_asend_freelist_free) {
1510 PyAsyncGenASend *o;
1511 o = ag_asend_freelist[--ag_asend_freelist_free];
1512 assert(Py_TYPE(o) == &_PyAsyncGenASend_Type);
1513 PyObject_Del(o);
1514 }
1515
1516 return ret;
1517}
1518
1519void
1520PyAsyncGen_Fini(void)
1521{
1522 PyAsyncGen_ClearFreeLists();
1523}
1524
1525
1526static PyObject *
1527async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1528{
1529 if (result == NULL) {
1530 if (!PyErr_Occurred()) {
1531 PyErr_SetNone(PyExc_StopAsyncIteration);
1532 }
1533
1534 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1535 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1536 ) {
1537 gen->ag_closed = 1;
1538 }
1539
1540 return NULL;
1541 }
1542
1543 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1544 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001545 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001546 Py_DECREF(result);
Yury Selivanoveb636452016-09-08 22:01:51 -07001547 return NULL;
1548 }
1549
1550 return result;
1551}
1552
1553
1554/* ---------- Async Generator ASend Awaitable ------------ */
1555
1556
1557static void
1558async_gen_asend_dealloc(PyAsyncGenASend *o)
1559{
1560 Py_CLEAR(o->ags_gen);
1561 Py_CLEAR(o->ags_sendval);
1562 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1563 assert(PyAsyncGenASend_CheckExact(o));
1564 ag_asend_freelist[ag_asend_freelist_free++] = o;
1565 } else {
1566 PyObject_Del(o);
1567 }
1568}
1569
1570
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 */
1671 Py_TPFLAGS_DEFAULT, /* tp_flags */
1672 0, /* tp_doc */
1673 0, /* tp_traverse */
1674 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 {
1702 o = PyObject_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
1703 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;
1715 return (PyObject*)o;
1716}
1717
1718
1719/* ---------- Async Generator Value Wrapper ------------ */
1720
1721
1722static void
1723async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1724{
1725 Py_CLEAR(o->agw_val);
1726 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1727 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1728 ag_value_freelist[ag_value_freelist_free++] = o;
1729 } else {
1730 PyObject_Del(o);
1731 }
1732}
1733
1734
1735PyTypeObject _PyAsyncGenWrappedValue_Type = {
1736 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1737 "async_generator_wrapped_value", /* tp_name */
1738 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1739 0, /* tp_itemsize */
1740 /* methods */
1741 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
1742 0, /* tp_print */
1743 0, /* tp_getattr */
1744 0, /* tp_setattr */
1745 0, /* tp_as_async */
1746 0, /* tp_repr */
1747 0, /* tp_as_number */
1748 0, /* tp_as_sequence */
1749 0, /* tp_as_mapping */
1750 0, /* tp_hash */
1751 0, /* tp_call */
1752 0, /* tp_str */
1753 PyObject_GenericGetAttr, /* tp_getattro */
1754 0, /* tp_setattro */
1755 0, /* tp_as_buffer */
1756 Py_TPFLAGS_DEFAULT, /* tp_flags */
1757 0, /* tp_doc */
1758 0, /* tp_traverse */
1759 0, /* tp_clear */
1760 0, /* tp_richcompare */
1761 0, /* tp_weaklistoffset */
1762 0, /* tp_iter */
1763 0, /* tp_iternext */
1764 0, /* tp_methods */
1765 0, /* tp_members */
1766 0, /* tp_getset */
1767 0, /* tp_base */
1768 0, /* tp_dict */
1769 0, /* tp_descr_get */
1770 0, /* tp_descr_set */
1771 0, /* tp_dictoffset */
1772 0, /* tp_init */
1773 0, /* tp_alloc */
1774 0, /* tp_new */
1775};
1776
1777
1778PyObject *
1779_PyAsyncGenValueWrapperNew(PyObject *val)
1780{
1781 _PyAsyncGenWrappedValue *o;
1782 assert(val);
1783
1784 if (ag_value_freelist_free) {
1785 ag_value_freelist_free--;
1786 o = ag_value_freelist[ag_value_freelist_free];
1787 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1788 _Py_NewReference((PyObject*)o);
1789 } else {
1790 o = PyObject_New(_PyAsyncGenWrappedValue, &_PyAsyncGenWrappedValue_Type);
1791 if (o == NULL) {
1792 return NULL;
1793 }
1794 }
1795 o->agw_val = val;
1796 Py_INCREF(val);
1797 return (PyObject*)o;
1798}
1799
1800
1801/* ---------- Async Generator AThrow awaitable ------------ */
1802
1803
1804static void
1805async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1806{
1807 Py_CLEAR(o->agt_gen);
1808 Py_CLEAR(o->agt_args);
1809 PyObject_Del(o);
1810}
1811
1812
1813static PyObject *
1814async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1815{
1816 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1817 PyFrameObject *f = gen->gi_frame;
1818 PyObject *retval;
1819
1820 if (f == NULL || f->f_stacktop == NULL ||
1821 o->agt_state == AWAITABLE_STATE_CLOSED) {
1822 PyErr_SetNone(PyExc_StopIteration);
1823 return NULL;
1824 }
1825
1826 if (o->agt_state == AWAITABLE_STATE_INIT) {
1827 if (o->agt_gen->ag_closed) {
1828 PyErr_SetNone(PyExc_StopIteration);
1829 return NULL;
1830 }
1831
1832 if (arg != Py_None) {
1833 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1834 return NULL;
1835 }
1836
1837 o->agt_state = AWAITABLE_STATE_ITER;
1838
1839 if (o->agt_args == NULL) {
1840 /* aclose() mode */
1841 o->agt_gen->ag_closed = 1;
1842
1843 retval = _gen_throw((PyGenObject *)gen,
1844 0, /* Do not close generator when
1845 PyExc_GeneratorExit is passed */
1846 PyExc_GeneratorExit, NULL, NULL);
1847
1848 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1849 Py_DECREF(retval);
1850 goto yield_close;
1851 }
1852 } else {
1853 PyObject *typ;
1854 PyObject *tb = NULL;
1855 PyObject *val = NULL;
1856
1857 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1858 &typ, &val, &tb)) {
1859 return NULL;
1860 }
1861
1862 retval = _gen_throw((PyGenObject *)gen,
1863 0, /* Do not close generator when
1864 PyExc_GeneratorExit is passed */
1865 typ, val, tb);
1866 retval = async_gen_unwrap_value(o->agt_gen, retval);
1867 }
1868 if (retval == NULL) {
1869 goto check_error;
1870 }
1871 return retval;
1872 }
1873
1874 assert(o->agt_state == AWAITABLE_STATE_ITER);
1875
1876 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1877 if (o->agt_args) {
1878 return async_gen_unwrap_value(o->agt_gen, retval);
1879 } else {
1880 /* aclose() mode */
1881 if (retval) {
1882 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1883 Py_DECREF(retval);
1884 goto yield_close;
1885 }
1886 else {
1887 return retval;
1888 }
1889 }
1890 else {
1891 goto check_error;
1892 }
1893 }
1894
1895yield_close:
1896 PyErr_SetString(
1897 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1898 return NULL;
1899
1900check_error:
1901 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1902 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1903 ) {
1904 o->agt_state = AWAITABLE_STATE_CLOSED;
1905 PyErr_Clear(); /* ignore these errors */
1906 PyErr_SetNone(PyExc_StopIteration);
1907 }
1908 return NULL;
1909}
1910
1911
1912static PyObject *
1913async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1914{
1915 PyObject *retval;
1916
1917 if (o->agt_state == AWAITABLE_STATE_INIT) {
1918 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1919 return NULL;
1920 }
1921
1922 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
1923 PyErr_SetNone(PyExc_StopIteration);
1924 return NULL;
1925 }
1926
1927 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1928 if (o->agt_args) {
1929 return async_gen_unwrap_value(o->agt_gen, retval);
1930 } else {
1931 /* aclose() mode */
1932 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1933 Py_DECREF(retval);
1934 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1935 return NULL;
1936 }
1937 return retval;
1938 }
1939}
1940
1941
1942static PyObject *
1943async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1944{
1945 return async_gen_athrow_send(o, Py_None);
1946}
1947
1948
1949static PyObject *
1950async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1951{
1952 o->agt_state = AWAITABLE_STATE_CLOSED;
1953 Py_RETURN_NONE;
1954}
1955
1956
1957static PyMethodDef async_gen_athrow_methods[] = {
1958 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1959 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1960 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1961 {NULL, NULL} /* Sentinel */
1962};
1963
1964
1965static PyAsyncMethods async_gen_athrow_as_async = {
1966 PyObject_SelfIter, /* am_await */
1967 0, /* am_aiter */
1968 0 /* am_anext */
1969};
1970
1971
1972PyTypeObject _PyAsyncGenAThrow_Type = {
1973 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1974 "async_generator_athrow", /* tp_name */
1975 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1976 0, /* tp_itemsize */
1977 /* methods */
1978 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
1979 0, /* tp_print */
1980 0, /* tp_getattr */
1981 0, /* tp_setattr */
1982 &async_gen_athrow_as_async, /* tp_as_async */
1983 0, /* tp_repr */
1984 0, /* tp_as_number */
1985 0, /* tp_as_sequence */
1986 0, /* tp_as_mapping */
1987 0, /* tp_hash */
1988 0, /* tp_call */
1989 0, /* tp_str */
1990 PyObject_GenericGetAttr, /* tp_getattro */
1991 0, /* tp_setattro */
1992 0, /* tp_as_buffer */
1993 Py_TPFLAGS_DEFAULT, /* tp_flags */
1994 0, /* tp_doc */
1995 0, /* tp_traverse */
1996 0, /* tp_clear */
1997 0, /* tp_richcompare */
1998 0, /* tp_weaklistoffset */
1999 PyObject_SelfIter, /* tp_iter */
2000 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2001 async_gen_athrow_methods, /* tp_methods */
2002 0, /* tp_members */
2003 0, /* tp_getset */
2004 0, /* tp_base */
2005 0, /* tp_dict */
2006 0, /* tp_descr_get */
2007 0, /* tp_descr_set */
2008 0, /* tp_dictoffset */
2009 0, /* tp_init */
2010 0, /* tp_alloc */
2011 0, /* tp_new */
2012};
2013
2014
2015static PyObject *
2016async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2017{
2018 PyAsyncGenAThrow *o;
2019 o = PyObject_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
2020 if (o == NULL) {
2021 return NULL;
2022 }
2023 o->agt_gen = gen;
2024 o->agt_args = args;
2025 o->agt_state = AWAITABLE_STATE_INIT;
2026 Py_INCREF(gen);
2027 Py_XINCREF(args);
2028 return (PyObject*)o;
2029}