blob: 00a882379fcabe5c97c782fb0a7661e42d1a0b75 [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);
Mark Shannonae3087c2017-10-22 22:41:51 +010035 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000036}
37
Antoine Pitrou58720d62013-08-05 23:26:40 +020038void
39_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020040{
41 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070042 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020043 PyObject *error_type, *error_value, *error_traceback;
44
45 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
46 /* Generator isn't paused, so no need to close */
47 return;
48
Yury Selivanoveb636452016-09-08 22:01:51 -070049 if (PyAsyncGen_CheckExact(self)) {
50 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
51 PyObject *finalizer = agen->ag_finalizer;
52 if (finalizer && !agen->ag_closed) {
53 /* Save the current exception, if any. */
54 PyErr_Fetch(&error_type, &error_value, &error_traceback);
55
Victor Stinnerde4ae3d2016-12-04 22:59:09 +010056 res = PyObject_CallFunctionObjArgs(finalizer, self, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -070057
58 if (res == NULL) {
59 PyErr_WriteUnraisable(self);
60 } else {
61 Py_DECREF(res);
62 }
63 /* Restore the saved exception. */
64 PyErr_Restore(error_type, error_value, error_traceback);
65 return;
66 }
67 }
68
Antoine Pitrou796564c2013-07-30 19:59:21 +020069 /* Save the current exception, if any. */
70 PyErr_Fetch(&error_type, &error_value, &error_traceback);
71
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070072 /* If `gen` is a coroutine, and if it was never awaited on,
73 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070074 if (gen->gi_code != NULL &&
75 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
76 gen->gi_frame->f_lasti == -1) {
77 if (!error_value) {
78 PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
79 "coroutine '%.50S' was never awaited",
80 gen->gi_qualname);
81 }
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 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200141 Py_CLEAR(gen->gi_name);
142 Py_CLEAR(gen->gi_qualname);
Mark Shannonae3087c2017-10-22 22:41:51 +0100143 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000145}
146
147static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500148gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000149{
Antoine Pitrou93963562013-05-14 20:37:52 +0200150 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200152 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000153
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500154 if (gen->gi_running) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200155 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700156 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400157 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700158 }
159 else if (PyAsyncGen_CheckExact(gen)) {
160 msg = "async generator already executing";
161 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400162 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500163 return NULL;
164 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200165 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500166 if (PyCoro_CheckExact(gen) && !closing) {
167 /* `gen` is an exhausted coroutine: raise an error,
168 except when called from gen_close(), which should
169 always be a silent method. */
170 PyErr_SetString(
171 PyExc_RuntimeError,
172 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700173 }
174 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500175 /* `gen` is an exhausted generator:
176 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700177 if (PyAsyncGen_CheckExact(gen)) {
178 PyErr_SetNone(PyExc_StopAsyncIteration);
179 }
180 else {
181 PyErr_SetNone(PyExc_StopIteration);
182 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500183 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 return NULL;
185 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000186
Antoine Pitrou93963562013-05-14 20:37:52 +0200187 if (f->f_lasti == -1) {
188 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200189 const char *msg = "can't send non-None value to a "
190 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700191 if (PyCoro_CheckExact(gen)) {
192 msg = NON_INIT_CORO_MSG;
193 }
194 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400195 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700196 "just-started async generator";
197 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400198 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200199 return NULL;
200 }
201 } else {
202 /* Push arg onto the frame's value stack */
203 result = arg ? arg : Py_None;
204 Py_INCREF(result);
205 *(f->f_stacktop++) = result;
206 }
207
208 /* Generators always return to their most recent caller, not
209 * necessarily their creator. */
210 Py_XINCREF(tstate->frame);
211 assert(f->f_back == NULL);
212 f->f_back = tstate->frame;
213
214 gen->gi_running = 1;
Mark Shannonae3087c2017-10-22 22:41:51 +0100215 gen->gi_exc_state.previous_item = tstate->exc_info;
216 tstate->exc_info = &gen->gi_exc_state;
Victor Stinner59a73272016-12-09 18:51:13 +0100217 result = PyEval_EvalFrameEx(f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100218 tstate->exc_info = gen->gi_exc_state.previous_item;
219 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200220 gen->gi_running = 0;
221
222 /* Don't keep the reference to f_back any longer than necessary. It
223 * may keep a chain of frames alive or it could create a reference
224 * cycle. */
225 assert(f->f_back == tstate->frame);
226 Py_CLEAR(f->f_back);
227
228 /* If the generator just returned (as opposed to yielding), signal
229 * that the generator is exhausted. */
230 if (result && f->f_stacktop == NULL) {
231 if (result == Py_None) {
232 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700233 if (PyAsyncGen_CheckExact(gen)) {
234 PyErr_SetNone(PyExc_StopAsyncIteration);
235 }
236 else {
237 PyErr_SetNone(PyExc_StopIteration);
238 }
239 }
240 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700241 /* Async generators cannot return anything but None */
242 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200243 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200244 }
245 Py_CLEAR(result);
246 }
Yury Selivanov68333392015-05-22 11:16:47 -0400247 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400248 /* Check for __future__ generator_stop and conditionally turn
249 * a leaking StopIteration into RuntimeError (with its cause
250 * set appropriately). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700251
252 const int check_stop_iter_error_flags = CO_FUTURE_GENERATOR_STOP |
253 CO_COROUTINE |
254 CO_ITERABLE_COROUTINE |
255 CO_ASYNC_GENERATOR;
256
257 if (gen->gi_code != NULL &&
258 ((PyCodeObject *)gen->gi_code)->co_flags &
259 check_stop_iter_error_flags)
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400260 {
Yury Selivanoveb636452016-09-08 22:01:51 -0700261 /* `gen` is either:
262 * a generator with CO_FUTURE_GENERATOR_STOP flag;
263 * a coroutine;
264 * a generator with CO_ITERABLE_COROUTINE flag
265 (decorated with types.coroutine decorator);
266 * an async generator.
267 */
268 const char *msg = "generator raised StopIteration";
269 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400270 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700271 }
272 else if PyAsyncGen_CheckExact(gen) {
273 msg = "async generator raised StopIteration";
274 }
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300275 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400276 }
Yury Selivanov68333392015-05-22 11:16:47 -0400277 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700278 /* `gen` is an ordinary generator without
279 CO_FUTURE_GENERATOR_STOP flag.
280 */
281
Yury Selivanov68333392015-05-22 11:16:47 -0400282 PyObject *exc, *val, *tb;
283
284 /* Pop the exception before issuing a warning. */
285 PyErr_Fetch(&exc, &val, &tb);
286
Martin Panter7e3a91a2016-02-10 04:40:48 +0000287 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Yury Selivanov68333392015-05-22 11:16:47 -0400288 "generator '%.50S' raised StopIteration",
289 gen->gi_qualname)) {
290 /* Warning was converted to an error. */
291 Py_XDECREF(exc);
292 Py_XDECREF(val);
293 Py_XDECREF(tb);
294 }
295 else {
296 PyErr_Restore(exc, val, tb);
297 }
298 }
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400299 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700300 else if (PyAsyncGen_CheckExact(gen) && !result &&
301 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
302 {
303 /* code in `gen` raised a StopAsyncIteration error:
304 raise a RuntimeError.
305 */
306 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300307 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700308 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200309
310 if (!result || f->f_stacktop == NULL) {
311 /* generator can't be rerun, so release the frame */
312 /* first clean reference cycle through stored exception traceback */
Mark Shannonae3087c2017-10-22 22:41:51 +0100313 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200314 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200315 gen->gi_frame = NULL;
316 Py_DECREF(f);
317 }
318
319 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000320}
321
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000322PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000323"send(arg) -> send 'arg' into generator,\n\
324return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000325
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500326PyObject *
327_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000328{
Yury Selivanov77c96812016-02-13 17:59:05 -0500329 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000330}
331
332PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400333"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000334
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000335/*
336 * This helper function is used by gen_close and gen_throw to
337 * close a subiterator being delegated to by yield-from.
338 */
339
Antoine Pitrou93963562013-05-14 20:37:52 +0200340static int
341gen_close_iter(PyObject *yf)
342{
343 PyObject *retval = NULL;
344 _Py_IDENTIFIER(close);
345
Yury Selivanoveb636452016-09-08 22:01:51 -0700346 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200347 retval = gen_close((PyGenObject *)yf, NULL);
348 if (retval == NULL)
349 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700350 }
351 else {
Antoine Pitrou93963562013-05-14 20:37:52 +0200352 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
353 if (meth == NULL) {
354 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
355 PyErr_WriteUnraisable(yf);
356 PyErr_Clear();
Yury Selivanoveb636452016-09-08 22:01:51 -0700357 }
358 else {
Victor Stinner3466bde2016-09-05 18:16:01 -0700359 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200360 Py_DECREF(meth);
361 if (retval == NULL)
362 return -1;
363 }
364 }
365 Py_XDECREF(retval);
366 return 0;
367}
368
Yury Selivanovc724bae2016-03-02 11:30:46 -0500369PyObject *
370_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500371{
Antoine Pitrou93963562013-05-14 20:37:52 +0200372 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500373 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200374
375 if (f && f->f_stacktop) {
376 PyObject *bytecode = f->f_code->co_code;
377 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
378
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100379 if (f->f_lasti < 0) {
380 /* Return immediately if the frame didn't start yet. YIELD_FROM
381 always come after LOAD_CONST: a code object should not start
382 with YIELD_FROM */
383 assert(code[0] != YIELD_FROM);
384 return NULL;
385 }
386
Serhiy Storchakaab874002016-09-11 13:48:15 +0300387 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200388 return NULL;
389 yf = f->f_stacktop[-1];
390 Py_INCREF(yf);
391 }
392
393 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500394}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000395
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000396static PyObject *
397gen_close(PyGenObject *gen, PyObject *args)
398{
Antoine Pitrou93963562013-05-14 20:37:52 +0200399 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500400 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200401 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000402
Antoine Pitrou93963562013-05-14 20:37:52 +0200403 if (yf) {
404 gen->gi_running = 1;
405 err = gen_close_iter(yf);
406 gen->gi_running = 0;
407 Py_DECREF(yf);
408 }
409 if (err == 0)
410 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500411 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200412 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200413 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700414 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400415 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700416 } else if (PyAsyncGen_CheckExact(gen)) {
417 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
418 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200419 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400420 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return NULL;
422 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200423 if (PyErr_ExceptionMatches(PyExc_StopIteration)
424 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
425 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200426 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200427 }
428 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000429}
430
Antoine Pitrou93963562013-05-14 20:37:52 +0200431
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000432PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000433"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
434return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000435
436static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700437_gen_throw(PyGenObject *gen, int close_on_genexit,
438 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000439{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500440 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000441 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000442
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000443 if (yf) {
444 PyObject *ret;
445 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700446 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
447 close_on_genexit
448 ) {
449 /* Asynchronous generators *should not* be closed right away.
450 We have to allow some awaits to work it through, hence the
451 `close_on_genexit` parameter here.
452 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500453 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200454 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500455 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000456 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000457 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500458 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000459 goto throw_here;
460 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700461 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
462 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500463 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700464 /* Close the generator that we are currently iterating with
465 'yield from' or awaiting on with 'await'. */
466 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
467 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500468 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000469 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700470 /* `yf` is an iterator or a coroutine-like object. */
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000471 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000472 if (meth == NULL) {
473 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
474 Py_DECREF(yf);
475 return NULL;
476 }
477 PyErr_Clear();
478 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000479 goto throw_here;
480 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500481 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700482 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500483 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000484 Py_DECREF(meth);
485 }
486 Py_DECREF(yf);
487 if (!ret) {
488 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500489 /* Pop subiterator from stack */
490 ret = *(--gen->gi_frame->f_stacktop);
491 assert(ret == yf);
492 Py_DECREF(ret);
493 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100494 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300495 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000496 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500497 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000498 Py_DECREF(val);
499 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500500 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000501 }
502 }
503 return ret;
504 }
505
506throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* First, check the traceback argument, replacing None with
508 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400509 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400511 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 else if (tb != NULL && !PyTraceBack_Check(tb)) {
513 PyErr_SetString(PyExc_TypeError,
514 "throw() third argument must be a traceback object");
515 return NULL;
516 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Py_INCREF(typ);
519 Py_XINCREF(val);
520 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000521
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400522 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 else if (PyExceptionInstance_Check(typ)) {
526 /* Raising an instance. The value should be a dummy. */
527 if (val && val != Py_None) {
528 PyErr_SetString(PyExc_TypeError,
529 "instance exception may not have a separate value");
530 goto failed_throw;
531 }
532 else {
533 /* Normalize to raise <class>, <instance> */
534 Py_XDECREF(val);
535 val = typ;
536 typ = PyExceptionInstance_Class(typ);
537 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200538
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400539 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200540 /* Returns NULL if there's no traceback */
541 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 }
543 }
544 else {
545 /* Not something you can raise. throw() fails. */
546 PyErr_Format(PyExc_TypeError,
547 "exceptions must be classes or instances "
548 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000549 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 goto failed_throw;
551 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500554 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000555
556failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 /* Didn't use our arguments, so restore their original refcounts */
558 Py_DECREF(typ);
559 Py_XDECREF(val);
560 Py_XDECREF(tb);
561 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000562}
563
564
565static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700566gen_throw(PyGenObject *gen, PyObject *args)
567{
568 PyObject *typ;
569 PyObject *tb = NULL;
570 PyObject *val = NULL;
571
572 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
573 return NULL;
574 }
575
576 return _gen_throw(gen, 1, typ, val, tb);
577}
578
579
580static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000581gen_iternext(PyGenObject *gen)
582{
Yury Selivanov77c96812016-02-13 17:59:05 -0500583 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000584}
585
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000586/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200587 * Set StopIteration with specified value. Value can be arbitrary object
588 * or NULL.
589 *
590 * Returns 0 if StopIteration is set and -1 if any other exception is set.
591 */
592int
593_PyGen_SetStopIterationValue(PyObject *value)
594{
595 PyObject *e;
596
597 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400598 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200599 {
600 /* Delay exception instantiation if we can */
601 PyErr_SetObject(PyExc_StopIteration, value);
602 return 0;
603 }
604 /* Construct an exception instance manually with
605 * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject.
606 *
607 * We do this to handle a situation when "value" is a tuple, in which
608 * case PyErr_SetObject would set the value of StopIteration to
609 * the first element of the tuple.
610 *
611 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
612 */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100613 e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200614 if (e == NULL) {
615 return -1;
616 }
617 PyErr_SetObject(PyExc_StopIteration, e);
618 Py_DECREF(e);
619 return 0;
620}
621
622/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000623 * If StopIteration exception is set, fetches its 'value'
624 * attribute if any, otherwise sets pvalue to None.
625 *
626 * Returns 0 if no exception or StopIteration is set.
627 * If any other exception is set, returns -1 and leaves
628 * pvalue unchanged.
629 */
630
631int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200632_PyGen_FetchStopIterationValue(PyObject **pvalue)
633{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000634 PyObject *et, *ev, *tb;
635 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500636
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000637 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
638 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200639 if (ev) {
640 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300641 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200642 value = ((PyStopIterationObject *)ev)->value;
643 Py_INCREF(value);
644 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200645 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
646 /* Avoid normalisation and take ev as value.
647 *
648 * Normalization is required if the value is a tuple, in
649 * that case the value of StopIteration would be set to
650 * the first element of the tuple.
651 *
652 * (See _PyErr_CreateException code for details.)
653 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200654 value = ev;
655 } else {
656 /* normalisation required */
657 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300658 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200659 PyErr_Restore(et, ev, tb);
660 return -1;
661 }
662 value = ((PyStopIterationObject *)ev)->value;
663 Py_INCREF(value);
664 Py_DECREF(ev);
665 }
666 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000667 Py_XDECREF(et);
668 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000669 } else if (PyErr_Occurred()) {
670 return -1;
671 }
672 if (value == NULL) {
673 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100674 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000675 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000676 *pvalue = value;
677 return 0;
678}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000679
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000680static PyObject *
681gen_repr(PyGenObject *gen)
682{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400683 return PyUnicode_FromFormat("<generator object %S at %p>",
684 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000685}
686
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000687static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200688gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000689{
Victor Stinner40ee3012014-06-16 15:59:28 +0200690 Py_INCREF(op->gi_name);
691 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000692}
693
Victor Stinner40ee3012014-06-16 15:59:28 +0200694static int
695gen_set_name(PyGenObject *op, PyObject *value)
696{
Victor Stinner40ee3012014-06-16 15:59:28 +0200697 /* Not legal to del gen.gi_name or to set it to anything
698 * other than a string object. */
699 if (value == NULL || !PyUnicode_Check(value)) {
700 PyErr_SetString(PyExc_TypeError,
701 "__name__ must be set to a string object");
702 return -1;
703 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200704 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300705 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200706 return 0;
707}
708
709static PyObject *
710gen_get_qualname(PyGenObject *op)
711{
712 Py_INCREF(op->gi_qualname);
713 return op->gi_qualname;
714}
715
716static int
717gen_set_qualname(PyGenObject *op, PyObject *value)
718{
Victor Stinner40ee3012014-06-16 15:59:28 +0200719 /* Not legal to del gen.__qualname__ or to set it to anything
720 * other than a string object. */
721 if (value == NULL || !PyUnicode_Check(value)) {
722 PyErr_SetString(PyExc_TypeError,
723 "__qualname__ must be set to a string object");
724 return -1;
725 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200726 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300727 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200728 return 0;
729}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000730
Yury Selivanove13f8f32015-07-03 00:23:30 -0400731static PyObject *
732gen_getyieldfrom(PyGenObject *gen)
733{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500734 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400735 if (yf == NULL)
736 Py_RETURN_NONE;
737 return yf;
738}
739
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000740static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200741 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
742 PyDoc_STR("name of the generator")},
743 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
744 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400745 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
746 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200747 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000748};
749
Martin v. Löwise440e472004-06-01 15:22:42 +0000750static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200751 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
752 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
753 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000755};
756
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000757static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500758 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
760 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
761 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000762};
763
Martin v. Löwise440e472004-06-01 15:22:42 +0000764PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyVarObject_HEAD_INIT(&PyType_Type, 0)
766 "generator", /* tp_name */
767 sizeof(PyGenObject), /* tp_basicsize */
768 0, /* tp_itemsize */
769 /* methods */
770 (destructor)gen_dealloc, /* tp_dealloc */
771 0, /* tp_print */
772 0, /* tp_getattr */
773 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400774 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 (reprfunc)gen_repr, /* tp_repr */
776 0, /* tp_as_number */
777 0, /* tp_as_sequence */
778 0, /* tp_as_mapping */
779 0, /* tp_hash */
780 0, /* tp_call */
781 0, /* tp_str */
782 PyObject_GenericGetAttr, /* tp_getattro */
783 0, /* tp_setattro */
784 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200785 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
786 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 0, /* tp_doc */
788 (traverseproc)gen_traverse, /* tp_traverse */
789 0, /* tp_clear */
790 0, /* tp_richcompare */
791 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400792 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 (iternextfunc)gen_iternext, /* tp_iternext */
794 gen_methods, /* tp_methods */
795 gen_memberlist, /* tp_members */
796 gen_getsetlist, /* tp_getset */
797 0, /* tp_base */
798 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 0, /* tp_descr_get */
801 0, /* tp_descr_set */
802 0, /* tp_dictoffset */
803 0, /* tp_init */
804 0, /* tp_alloc */
805 0, /* tp_new */
806 0, /* tp_free */
807 0, /* tp_is_gc */
808 0, /* tp_bases */
809 0, /* tp_mro */
810 0, /* tp_cache */
811 0, /* tp_subclasses */
812 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200813 0, /* tp_del */
814 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200815 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000816};
817
Yury Selivanov5376ba92015-06-22 12:19:30 -0400818static PyObject *
819gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
820 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000821{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400822 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (gen == NULL) {
824 Py_DECREF(f);
825 return NULL;
826 }
827 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200828 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_INCREF(f->f_code);
830 gen->gi_code = (PyObject *)(f->f_code);
831 gen->gi_running = 0;
832 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100833 gen->gi_exc_state.exc_type = NULL;
834 gen->gi_exc_state.exc_value = NULL;
835 gen->gi_exc_state.exc_traceback = NULL;
836 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200837 if (name != NULL)
838 gen->gi_name = name;
839 else
840 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
841 Py_INCREF(gen->gi_name);
842 if (qualname != NULL)
843 gen->gi_qualname = qualname;
844 else
845 gen->gi_qualname = gen->gi_name;
846 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 _PyObject_GC_TRACK(gen);
848 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000849}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000850
Victor Stinner40ee3012014-06-16 15:59:28 +0200851PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400852PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
853{
854 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
855}
856
857PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200858PyGen_New(PyFrameObject *f)
859{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400860 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200861}
862
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000863int
864PyGen_NeedsFinalizing(PyGenObject *gen)
865{
Antoine Pitrou93963562013-05-14 20:37:52 +0200866 int i;
867 PyFrameObject *f = gen->gi_frame;
868
869 if (f == NULL || f->f_stacktop == NULL)
870 return 0; /* no frame or empty blockstack == no finalization */
871
872 /* Any block type besides a loop requires cleanup. */
873 for (i = 0; i < f->f_iblock; i++)
874 if (f->f_blockstack[i].b_type != SETUP_LOOP)
875 return 1;
876
877 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000879}
Yury Selivanov75445082015-05-11 22:57:16 -0400880
Yury Selivanov5376ba92015-06-22 12:19:30 -0400881/* Coroutine Object */
882
883typedef struct {
884 PyObject_HEAD
885 PyCoroObject *cw_coroutine;
886} PyCoroWrapper;
887
888static int
889gen_is_coroutine(PyObject *o)
890{
891 if (PyGen_CheckExact(o)) {
892 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
893 if (code->co_flags & CO_ITERABLE_COROUTINE) {
894 return 1;
895 }
896 }
897 return 0;
898}
899
Yury Selivanov75445082015-05-11 22:57:16 -0400900/*
901 * This helper function returns an awaitable for `o`:
902 * - `o` if `o` is a coroutine-object;
903 * - `type(o)->tp_as_async->am_await(o)`
904 *
905 * Raises a TypeError if it's not possible to return
906 * an awaitable and returns NULL.
907 */
908PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400909_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400910{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400911 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400912 PyTypeObject *ot;
913
Yury Selivanov5376ba92015-06-22 12:19:30 -0400914 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
915 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400916 Py_INCREF(o);
917 return o;
918 }
919
920 ot = Py_TYPE(o);
921 if (ot->tp_as_async != NULL) {
922 getter = ot->tp_as_async->am_await;
923 }
924 if (getter != NULL) {
925 PyObject *res = (*getter)(o);
926 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400927 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
928 /* __await__ must return an *iterator*, not
929 a coroutine or another awaitable (see PEP 492) */
930 PyErr_SetString(PyExc_TypeError,
931 "__await__() returned a coroutine");
932 Py_CLEAR(res);
933 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400934 PyErr_Format(PyExc_TypeError,
935 "__await__() returned non-iterator "
936 "of type '%.100s'",
937 Py_TYPE(res)->tp_name);
938 Py_CLEAR(res);
939 }
Yury Selivanov75445082015-05-11 22:57:16 -0400940 }
941 return res;
942 }
943
944 PyErr_Format(PyExc_TypeError,
945 "object %.100s can't be used in 'await' expression",
946 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400947 return NULL;
948}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400949
950static PyObject *
951coro_repr(PyCoroObject *coro)
952{
953 return PyUnicode_FromFormat("<coroutine object %S at %p>",
954 coro->cr_qualname, coro);
955}
956
957static PyObject *
958coro_await(PyCoroObject *coro)
959{
960 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
961 if (cw == NULL) {
962 return NULL;
963 }
964 Py_INCREF(coro);
965 cw->cw_coroutine = coro;
966 _PyObject_GC_TRACK(cw);
967 return (PyObject *)cw;
968}
969
Yury Selivanove13f8f32015-07-03 00:23:30 -0400970static PyObject *
971coro_get_cr_await(PyCoroObject *coro)
972{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500973 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400974 if (yf == NULL)
975 Py_RETURN_NONE;
976 return yf;
977}
978
Yury Selivanov5376ba92015-06-22 12:19:30 -0400979static PyGetSetDef coro_getsetlist[] = {
980 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
981 PyDoc_STR("name of the coroutine")},
982 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
983 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400984 {"cr_await", (getter)coro_get_cr_await, NULL,
985 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400986 {NULL} /* Sentinel */
987};
988
989static PyMemberDef coro_memberlist[] = {
990 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
991 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
992 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
993 {NULL} /* Sentinel */
994};
995
996PyDoc_STRVAR(coro_send_doc,
997"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400998return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400999
1000PyDoc_STRVAR(coro_throw_doc,
1001"throw(typ[,val[,tb]]) -> raise exception in 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_close_doc,
1005"close() -> raise GeneratorExit inside coroutine.");
1006
1007static PyMethodDef coro_methods[] = {
1008 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
1009 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1010 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1011 {NULL, NULL} /* Sentinel */
1012};
1013
1014static PyAsyncMethods coro_as_async = {
1015 (unaryfunc)coro_await, /* am_await */
1016 0, /* am_aiter */
1017 0 /* am_anext */
1018};
1019
1020PyTypeObject PyCoro_Type = {
1021 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1022 "coroutine", /* tp_name */
1023 sizeof(PyCoroObject), /* tp_basicsize */
1024 0, /* tp_itemsize */
1025 /* methods */
1026 (destructor)gen_dealloc, /* tp_dealloc */
1027 0, /* tp_print */
1028 0, /* tp_getattr */
1029 0, /* tp_setattr */
1030 &coro_as_async, /* tp_as_async */
1031 (reprfunc)coro_repr, /* tp_repr */
1032 0, /* tp_as_number */
1033 0, /* tp_as_sequence */
1034 0, /* tp_as_mapping */
1035 0, /* tp_hash */
1036 0, /* tp_call */
1037 0, /* tp_str */
1038 PyObject_GenericGetAttr, /* tp_getattro */
1039 0, /* tp_setattro */
1040 0, /* tp_as_buffer */
1041 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1042 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1043 0, /* tp_doc */
1044 (traverseproc)gen_traverse, /* tp_traverse */
1045 0, /* tp_clear */
1046 0, /* tp_richcompare */
1047 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1048 0, /* tp_iter */
1049 0, /* tp_iternext */
1050 coro_methods, /* tp_methods */
1051 coro_memberlist, /* tp_members */
1052 coro_getsetlist, /* tp_getset */
1053 0, /* tp_base */
1054 0, /* tp_dict */
1055 0, /* tp_descr_get */
1056 0, /* tp_descr_set */
1057 0, /* tp_dictoffset */
1058 0, /* tp_init */
1059 0, /* tp_alloc */
1060 0, /* tp_new */
1061 0, /* tp_free */
1062 0, /* tp_is_gc */
1063 0, /* tp_bases */
1064 0, /* tp_mro */
1065 0, /* tp_cache */
1066 0, /* tp_subclasses */
1067 0, /* tp_weaklist */
1068 0, /* tp_del */
1069 0, /* tp_version_tag */
1070 _PyGen_Finalize, /* tp_finalize */
1071};
1072
1073static void
1074coro_wrapper_dealloc(PyCoroWrapper *cw)
1075{
1076 _PyObject_GC_UNTRACK((PyObject *)cw);
1077 Py_CLEAR(cw->cw_coroutine);
1078 PyObject_GC_Del(cw);
1079}
1080
1081static PyObject *
1082coro_wrapper_iternext(PyCoroWrapper *cw)
1083{
Yury Selivanov77c96812016-02-13 17:59:05 -05001084 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001085}
1086
1087static PyObject *
1088coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1089{
Yury Selivanov77c96812016-02-13 17:59:05 -05001090 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001091}
1092
1093static PyObject *
1094coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1095{
1096 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1097}
1098
1099static PyObject *
1100coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1101{
1102 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1103}
1104
1105static int
1106coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1107{
1108 Py_VISIT((PyObject *)cw->cw_coroutine);
1109 return 0;
1110}
1111
1112static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001113 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1114 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1115 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001116 {NULL, NULL} /* Sentinel */
1117};
1118
1119PyTypeObject _PyCoroWrapper_Type = {
1120 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1121 "coroutine_wrapper",
1122 sizeof(PyCoroWrapper), /* tp_basicsize */
1123 0, /* tp_itemsize */
1124 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
1125 0, /* tp_print */
1126 0, /* tp_getattr */
1127 0, /* tp_setattr */
1128 0, /* tp_as_async */
1129 0, /* tp_repr */
1130 0, /* tp_as_number */
1131 0, /* tp_as_sequence */
1132 0, /* tp_as_mapping */
1133 0, /* tp_hash */
1134 0, /* tp_call */
1135 0, /* tp_str */
1136 PyObject_GenericGetAttr, /* tp_getattro */
1137 0, /* tp_setattro */
1138 0, /* tp_as_buffer */
1139 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1140 "A wrapper object implementing __await__ for coroutines.",
1141 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1142 0, /* tp_clear */
1143 0, /* tp_richcompare */
1144 0, /* tp_weaklistoffset */
1145 PyObject_SelfIter, /* tp_iter */
1146 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1147 coro_wrapper_methods, /* tp_methods */
1148 0, /* tp_members */
1149 0, /* tp_getset */
1150 0, /* tp_base */
1151 0, /* tp_dict */
1152 0, /* tp_descr_get */
1153 0, /* tp_descr_set */
1154 0, /* tp_dictoffset */
1155 0, /* tp_init */
1156 0, /* tp_alloc */
1157 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001158 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001159};
1160
1161PyObject *
1162PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1163{
1164 return gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1165}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001166
1167
Yury Selivanoveb636452016-09-08 22:01:51 -07001168/* ========= Asynchronous Generators ========= */
1169
1170
1171typedef enum {
1172 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1173 AWAITABLE_STATE_ITER, /* being iterated */
1174 AWAITABLE_STATE_CLOSED, /* closed */
1175} AwaitableState;
1176
1177
1178typedef struct {
1179 PyObject_HEAD
1180 PyAsyncGenObject *ags_gen;
1181
1182 /* Can be NULL, when in the __anext__() mode
1183 (equivalent of "asend(None)") */
1184 PyObject *ags_sendval;
1185
1186 AwaitableState ags_state;
1187} PyAsyncGenASend;
1188
1189
1190typedef struct {
1191 PyObject_HEAD
1192 PyAsyncGenObject *agt_gen;
1193
1194 /* Can be NULL, when in the "aclose()" mode
1195 (equivalent of "athrow(GeneratorExit)") */
1196 PyObject *agt_args;
1197
1198 AwaitableState agt_state;
1199} PyAsyncGenAThrow;
1200
1201
1202typedef struct {
1203 PyObject_HEAD
1204 PyObject *agw_val;
1205} _PyAsyncGenWrappedValue;
1206
1207
1208#ifndef _PyAsyncGen_MAXFREELIST
1209#define _PyAsyncGen_MAXFREELIST 80
1210#endif
1211
1212/* Freelists boost performance 6-10%; they also reduce memory
1213 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1214 are short-living objects that are instantiated for every
1215 __anext__ call.
1216*/
1217
1218static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1219static int ag_value_freelist_free = 0;
1220
1221static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1222static int ag_asend_freelist_free = 0;
1223
1224#define _PyAsyncGenWrappedValue_CheckExact(o) \
1225 (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type)
1226
1227#define PyAsyncGenASend_CheckExact(o) \
1228 (Py_TYPE(o) == &_PyAsyncGenASend_Type)
1229
1230
1231static int
1232async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1233{
1234 Py_VISIT(gen->ag_finalizer);
1235 return gen_traverse((PyGenObject*)gen, visit, arg);
1236}
1237
1238
1239static PyObject *
1240async_gen_repr(PyAsyncGenObject *o)
1241{
1242 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1243 o->ag_qualname, o);
1244}
1245
1246
1247static int
1248async_gen_init_hooks(PyAsyncGenObject *o)
1249{
1250 PyThreadState *tstate;
1251 PyObject *finalizer;
1252 PyObject *firstiter;
1253
1254 if (o->ag_hooks_inited) {
1255 return 0;
1256 }
1257
1258 o->ag_hooks_inited = 1;
1259
1260 tstate = PyThreadState_GET();
1261
1262 finalizer = tstate->async_gen_finalizer;
1263 if (finalizer) {
1264 Py_INCREF(finalizer);
1265 o->ag_finalizer = finalizer;
1266 }
1267
1268 firstiter = tstate->async_gen_firstiter;
1269 if (firstiter) {
1270 PyObject *res;
1271
1272 Py_INCREF(firstiter);
Victor Stinner7bfb42d2016-12-05 17:04:32 +01001273 res = PyObject_CallFunctionObjArgs(firstiter, o, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -07001274 Py_DECREF(firstiter);
1275 if (res == NULL) {
1276 return 1;
1277 }
1278 Py_DECREF(res);
1279 }
1280
1281 return 0;
1282}
1283
1284
1285static PyObject *
1286async_gen_anext(PyAsyncGenObject *o)
1287{
1288 if (async_gen_init_hooks(o)) {
1289 return NULL;
1290 }
1291 return async_gen_asend_new(o, NULL);
1292}
1293
1294
1295static PyObject *
1296async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1297{
1298 if (async_gen_init_hooks(o)) {
1299 return NULL;
1300 }
1301 return async_gen_asend_new(o, arg);
1302}
1303
1304
1305static PyObject *
1306async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1307{
1308 if (async_gen_init_hooks(o)) {
1309 return NULL;
1310 }
1311 return async_gen_athrow_new(o, NULL);
1312}
1313
1314static PyObject *
1315async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1316{
1317 if (async_gen_init_hooks(o)) {
1318 return NULL;
1319 }
1320 return async_gen_athrow_new(o, args);
1321}
1322
1323
1324static PyGetSetDef async_gen_getsetlist[] = {
1325 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1326 PyDoc_STR("name of the async generator")},
1327 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1328 PyDoc_STR("qualified name of the async generator")},
1329 {"ag_await", (getter)coro_get_cr_await, NULL,
1330 PyDoc_STR("object being awaited on, or None")},
1331 {NULL} /* Sentinel */
1332};
1333
1334static PyMemberDef async_gen_memberlist[] = {
1335 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
1336 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY},
1337 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1338 {NULL} /* Sentinel */
1339};
1340
1341PyDoc_STRVAR(async_aclose_doc,
1342"aclose() -> raise GeneratorExit inside generator.");
1343
1344PyDoc_STRVAR(async_asend_doc,
1345"asend(v) -> send 'v' in generator.");
1346
1347PyDoc_STRVAR(async_athrow_doc,
1348"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1349
1350static PyMethodDef async_gen_methods[] = {
1351 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1352 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1353 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
1354 {NULL, NULL} /* Sentinel */
1355};
1356
1357
1358static PyAsyncMethods async_gen_as_async = {
1359 0, /* am_await */
1360 PyObject_SelfIter, /* am_aiter */
1361 (unaryfunc)async_gen_anext /* am_anext */
1362};
1363
1364
1365PyTypeObject PyAsyncGen_Type = {
1366 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1367 "async_generator", /* tp_name */
1368 sizeof(PyAsyncGenObject), /* tp_basicsize */
1369 0, /* tp_itemsize */
1370 /* methods */
1371 (destructor)gen_dealloc, /* tp_dealloc */
1372 0, /* tp_print */
1373 0, /* tp_getattr */
1374 0, /* tp_setattr */
1375 &async_gen_as_async, /* tp_as_async */
1376 (reprfunc)async_gen_repr, /* tp_repr */
1377 0, /* tp_as_number */
1378 0, /* tp_as_sequence */
1379 0, /* tp_as_mapping */
1380 0, /* tp_hash */
1381 0, /* tp_call */
1382 0, /* tp_str */
1383 PyObject_GenericGetAttr, /* tp_getattro */
1384 0, /* tp_setattro */
1385 0, /* tp_as_buffer */
1386 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1387 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1388 0, /* tp_doc */
1389 (traverseproc)async_gen_traverse, /* tp_traverse */
1390 0, /* tp_clear */
1391 0, /* tp_richcompare */
1392 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1393 0, /* tp_iter */
1394 0, /* tp_iternext */
1395 async_gen_methods, /* tp_methods */
1396 async_gen_memberlist, /* tp_members */
1397 async_gen_getsetlist, /* tp_getset */
1398 0, /* tp_base */
1399 0, /* tp_dict */
1400 0, /* tp_descr_get */
1401 0, /* tp_descr_set */
1402 0, /* tp_dictoffset */
1403 0, /* tp_init */
1404 0, /* tp_alloc */
1405 0, /* tp_new */
1406 0, /* tp_free */
1407 0, /* tp_is_gc */
1408 0, /* tp_bases */
1409 0, /* tp_mro */
1410 0, /* tp_cache */
1411 0, /* tp_subclasses */
1412 0, /* tp_weaklist */
1413 0, /* tp_del */
1414 0, /* tp_version_tag */
1415 _PyGen_Finalize, /* tp_finalize */
1416};
1417
1418
1419PyObject *
1420PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1421{
1422 PyAsyncGenObject *o;
1423 o = (PyAsyncGenObject *)gen_new_with_qualname(
1424 &PyAsyncGen_Type, f, name, qualname);
1425 if (o == NULL) {
1426 return NULL;
1427 }
1428 o->ag_finalizer = NULL;
1429 o->ag_closed = 0;
1430 o->ag_hooks_inited = 0;
1431 return (PyObject*)o;
1432}
1433
1434
1435int
1436PyAsyncGen_ClearFreeLists(void)
1437{
1438 int ret = ag_value_freelist_free + ag_asend_freelist_free;
1439
1440 while (ag_value_freelist_free) {
1441 _PyAsyncGenWrappedValue *o;
1442 o = ag_value_freelist[--ag_value_freelist_free];
1443 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001444 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001445 }
1446
1447 while (ag_asend_freelist_free) {
1448 PyAsyncGenASend *o;
1449 o = ag_asend_freelist[--ag_asend_freelist_free];
1450 assert(Py_TYPE(o) == &_PyAsyncGenASend_Type);
Yury Selivanov29310c42016-11-08 19:46:22 -05001451 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001452 }
1453
1454 return ret;
1455}
1456
1457void
1458PyAsyncGen_Fini(void)
1459{
1460 PyAsyncGen_ClearFreeLists();
1461}
1462
1463
1464static PyObject *
1465async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1466{
1467 if (result == NULL) {
1468 if (!PyErr_Occurred()) {
1469 PyErr_SetNone(PyExc_StopAsyncIteration);
1470 }
1471
1472 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1473 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1474 ) {
1475 gen->ag_closed = 1;
1476 }
1477
1478 return NULL;
1479 }
1480
1481 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1482 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001483 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001484 Py_DECREF(result);
Yury Selivanoveb636452016-09-08 22:01:51 -07001485 return NULL;
1486 }
1487
1488 return result;
1489}
1490
1491
1492/* ---------- Async Generator ASend Awaitable ------------ */
1493
1494
1495static void
1496async_gen_asend_dealloc(PyAsyncGenASend *o)
1497{
Yury Selivanov29310c42016-11-08 19:46:22 -05001498 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001499 Py_CLEAR(o->ags_gen);
1500 Py_CLEAR(o->ags_sendval);
1501 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1502 assert(PyAsyncGenASend_CheckExact(o));
1503 ag_asend_freelist[ag_asend_freelist_free++] = o;
1504 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001505 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001506 }
1507}
1508
Yury Selivanov29310c42016-11-08 19:46:22 -05001509static int
1510async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1511{
1512 Py_VISIT(o->ags_gen);
1513 Py_VISIT(o->ags_sendval);
1514 return 0;
1515}
1516
Yury Selivanoveb636452016-09-08 22:01:51 -07001517
1518static PyObject *
1519async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1520{
1521 PyObject *result;
1522
1523 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1524 PyErr_SetNone(PyExc_StopIteration);
1525 return NULL;
1526 }
1527
1528 if (o->ags_state == AWAITABLE_STATE_INIT) {
1529 if (arg == NULL || arg == Py_None) {
1530 arg = o->ags_sendval;
1531 }
1532 o->ags_state = AWAITABLE_STATE_ITER;
1533 }
1534
1535 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1536 result = async_gen_unwrap_value(o->ags_gen, result);
1537
1538 if (result == NULL) {
1539 o->ags_state = AWAITABLE_STATE_CLOSED;
1540 }
1541
1542 return result;
1543}
1544
1545
1546static PyObject *
1547async_gen_asend_iternext(PyAsyncGenASend *o)
1548{
1549 return async_gen_asend_send(o, NULL);
1550}
1551
1552
1553static PyObject *
1554async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1555{
1556 PyObject *result;
1557
1558 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1559 PyErr_SetNone(PyExc_StopIteration);
1560 return NULL;
1561 }
1562
1563 result = gen_throw((PyGenObject*)o->ags_gen, args);
1564 result = async_gen_unwrap_value(o->ags_gen, result);
1565
1566 if (result == NULL) {
1567 o->ags_state = AWAITABLE_STATE_CLOSED;
1568 }
1569
1570 return result;
1571}
1572
1573
1574static PyObject *
1575async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1576{
1577 o->ags_state = AWAITABLE_STATE_CLOSED;
1578 Py_RETURN_NONE;
1579}
1580
1581
1582static PyMethodDef async_gen_asend_methods[] = {
1583 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1584 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1585 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1586 {NULL, NULL} /* Sentinel */
1587};
1588
1589
1590static PyAsyncMethods async_gen_asend_as_async = {
1591 PyObject_SelfIter, /* am_await */
1592 0, /* am_aiter */
1593 0 /* am_anext */
1594};
1595
1596
1597PyTypeObject _PyAsyncGenASend_Type = {
1598 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1599 "async_generator_asend", /* tp_name */
1600 sizeof(PyAsyncGenASend), /* tp_basicsize */
1601 0, /* tp_itemsize */
1602 /* methods */
1603 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
1604 0, /* tp_print */
1605 0, /* tp_getattr */
1606 0, /* tp_setattr */
1607 &async_gen_asend_as_async, /* tp_as_async */
1608 0, /* tp_repr */
1609 0, /* tp_as_number */
1610 0, /* tp_as_sequence */
1611 0, /* tp_as_mapping */
1612 0, /* tp_hash */
1613 0, /* tp_call */
1614 0, /* tp_str */
1615 PyObject_GenericGetAttr, /* tp_getattro */
1616 0, /* tp_setattro */
1617 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001618 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001619 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001620 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001621 0, /* tp_clear */
1622 0, /* tp_richcompare */
1623 0, /* tp_weaklistoffset */
1624 PyObject_SelfIter, /* tp_iter */
1625 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1626 async_gen_asend_methods, /* tp_methods */
1627 0, /* tp_members */
1628 0, /* tp_getset */
1629 0, /* tp_base */
1630 0, /* tp_dict */
1631 0, /* tp_descr_get */
1632 0, /* tp_descr_set */
1633 0, /* tp_dictoffset */
1634 0, /* tp_init */
1635 0, /* tp_alloc */
1636 0, /* tp_new */
1637};
1638
1639
1640static PyObject *
1641async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1642{
1643 PyAsyncGenASend *o;
1644 if (ag_asend_freelist_free) {
1645 ag_asend_freelist_free--;
1646 o = ag_asend_freelist[ag_asend_freelist_free];
1647 _Py_NewReference((PyObject *)o);
1648 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001649 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001650 if (o == NULL) {
1651 return NULL;
1652 }
1653 }
1654
1655 Py_INCREF(gen);
1656 o->ags_gen = gen;
1657
1658 Py_XINCREF(sendval);
1659 o->ags_sendval = sendval;
1660
1661 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001662
1663 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001664 return (PyObject*)o;
1665}
1666
1667
1668/* ---------- Async Generator Value Wrapper ------------ */
1669
1670
1671static void
1672async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1673{
Yury Selivanov29310c42016-11-08 19:46:22 -05001674 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001675 Py_CLEAR(o->agw_val);
1676 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1677 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1678 ag_value_freelist[ag_value_freelist_free++] = o;
1679 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001680 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001681 }
1682}
1683
1684
Yury Selivanov29310c42016-11-08 19:46:22 -05001685static int
1686async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1687 visitproc visit, void *arg)
1688{
1689 Py_VISIT(o->agw_val);
1690 return 0;
1691}
1692
1693
Yury Selivanoveb636452016-09-08 22:01:51 -07001694PyTypeObject _PyAsyncGenWrappedValue_Type = {
1695 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1696 "async_generator_wrapped_value", /* tp_name */
1697 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1698 0, /* tp_itemsize */
1699 /* methods */
1700 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
1701 0, /* tp_print */
1702 0, /* tp_getattr */
1703 0, /* tp_setattr */
1704 0, /* tp_as_async */
1705 0, /* tp_repr */
1706 0, /* tp_as_number */
1707 0, /* tp_as_sequence */
1708 0, /* tp_as_mapping */
1709 0, /* tp_hash */
1710 0, /* tp_call */
1711 0, /* tp_str */
1712 PyObject_GenericGetAttr, /* tp_getattro */
1713 0, /* tp_setattro */
1714 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001715 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001716 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001717 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001718 0, /* tp_clear */
1719 0, /* tp_richcompare */
1720 0, /* tp_weaklistoffset */
1721 0, /* tp_iter */
1722 0, /* tp_iternext */
1723 0, /* tp_methods */
1724 0, /* tp_members */
1725 0, /* tp_getset */
1726 0, /* tp_base */
1727 0, /* tp_dict */
1728 0, /* tp_descr_get */
1729 0, /* tp_descr_set */
1730 0, /* tp_dictoffset */
1731 0, /* tp_init */
1732 0, /* tp_alloc */
1733 0, /* tp_new */
1734};
1735
1736
1737PyObject *
1738_PyAsyncGenValueWrapperNew(PyObject *val)
1739{
1740 _PyAsyncGenWrappedValue *o;
1741 assert(val);
1742
1743 if (ag_value_freelist_free) {
1744 ag_value_freelist_free--;
1745 o = ag_value_freelist[ag_value_freelist_free];
1746 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1747 _Py_NewReference((PyObject*)o);
1748 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001749 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1750 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001751 if (o == NULL) {
1752 return NULL;
1753 }
1754 }
1755 o->agw_val = val;
1756 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001757 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001758 return (PyObject*)o;
1759}
1760
1761
1762/* ---------- Async Generator AThrow awaitable ------------ */
1763
1764
1765static void
1766async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1767{
Yury Selivanov29310c42016-11-08 19:46:22 -05001768 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001769 Py_CLEAR(o->agt_gen);
1770 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001771 PyObject_GC_Del(o);
1772}
1773
1774
1775static int
1776async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1777{
1778 Py_VISIT(o->agt_gen);
1779 Py_VISIT(o->agt_args);
1780 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001781}
1782
1783
1784static PyObject *
1785async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1786{
1787 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1788 PyFrameObject *f = gen->gi_frame;
1789 PyObject *retval;
1790
1791 if (f == NULL || f->f_stacktop == NULL ||
1792 o->agt_state == AWAITABLE_STATE_CLOSED) {
1793 PyErr_SetNone(PyExc_StopIteration);
1794 return NULL;
1795 }
1796
1797 if (o->agt_state == AWAITABLE_STATE_INIT) {
1798 if (o->agt_gen->ag_closed) {
1799 PyErr_SetNone(PyExc_StopIteration);
1800 return NULL;
1801 }
1802
1803 if (arg != Py_None) {
1804 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1805 return NULL;
1806 }
1807
1808 o->agt_state = AWAITABLE_STATE_ITER;
1809
1810 if (o->agt_args == NULL) {
1811 /* aclose() mode */
1812 o->agt_gen->ag_closed = 1;
1813
1814 retval = _gen_throw((PyGenObject *)gen,
1815 0, /* Do not close generator when
1816 PyExc_GeneratorExit is passed */
1817 PyExc_GeneratorExit, NULL, NULL);
1818
1819 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1820 Py_DECREF(retval);
1821 goto yield_close;
1822 }
1823 } else {
1824 PyObject *typ;
1825 PyObject *tb = NULL;
1826 PyObject *val = NULL;
1827
1828 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1829 &typ, &val, &tb)) {
1830 return NULL;
1831 }
1832
1833 retval = _gen_throw((PyGenObject *)gen,
1834 0, /* Do not close generator when
1835 PyExc_GeneratorExit is passed */
1836 typ, val, tb);
1837 retval = async_gen_unwrap_value(o->agt_gen, retval);
1838 }
1839 if (retval == NULL) {
1840 goto check_error;
1841 }
1842 return retval;
1843 }
1844
1845 assert(o->agt_state == AWAITABLE_STATE_ITER);
1846
1847 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1848 if (o->agt_args) {
1849 return async_gen_unwrap_value(o->agt_gen, retval);
1850 } else {
1851 /* aclose() mode */
1852 if (retval) {
1853 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1854 Py_DECREF(retval);
1855 goto yield_close;
1856 }
1857 else {
1858 return retval;
1859 }
1860 }
1861 else {
1862 goto check_error;
1863 }
1864 }
1865
1866yield_close:
1867 PyErr_SetString(
1868 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1869 return NULL;
1870
1871check_error:
Yury Selivanov41782e42016-11-16 18:16:17 -05001872 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
1873 o->agt_state = AWAITABLE_STATE_CLOSED;
1874 if (o->agt_args == NULL) {
1875 /* when aclose() is called we don't want to propagate
1876 StopAsyncIteration; just raise StopIteration, signalling
1877 that 'aclose()' is done. */
1878 PyErr_Clear();
1879 PyErr_SetNone(PyExc_StopIteration);
1880 }
1881 }
1882 else if (PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001883 o->agt_state = AWAITABLE_STATE_CLOSED;
1884 PyErr_Clear(); /* ignore these errors */
1885 PyErr_SetNone(PyExc_StopIteration);
1886 }
1887 return NULL;
1888}
1889
1890
1891static PyObject *
1892async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1893{
1894 PyObject *retval;
1895
1896 if (o->agt_state == AWAITABLE_STATE_INIT) {
1897 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1898 return NULL;
1899 }
1900
1901 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
1902 PyErr_SetNone(PyExc_StopIteration);
1903 return NULL;
1904 }
1905
1906 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1907 if (o->agt_args) {
1908 return async_gen_unwrap_value(o->agt_gen, retval);
1909 } else {
1910 /* aclose() mode */
1911 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1912 Py_DECREF(retval);
1913 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1914 return NULL;
1915 }
1916 return retval;
1917 }
1918}
1919
1920
1921static PyObject *
1922async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1923{
1924 return async_gen_athrow_send(o, Py_None);
1925}
1926
1927
1928static PyObject *
1929async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1930{
1931 o->agt_state = AWAITABLE_STATE_CLOSED;
1932 Py_RETURN_NONE;
1933}
1934
1935
1936static PyMethodDef async_gen_athrow_methods[] = {
1937 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1938 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1939 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1940 {NULL, NULL} /* Sentinel */
1941};
1942
1943
1944static PyAsyncMethods async_gen_athrow_as_async = {
1945 PyObject_SelfIter, /* am_await */
1946 0, /* am_aiter */
1947 0 /* am_anext */
1948};
1949
1950
1951PyTypeObject _PyAsyncGenAThrow_Type = {
1952 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1953 "async_generator_athrow", /* tp_name */
1954 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1955 0, /* tp_itemsize */
1956 /* methods */
1957 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
1958 0, /* tp_print */
1959 0, /* tp_getattr */
1960 0, /* tp_setattr */
1961 &async_gen_athrow_as_async, /* tp_as_async */
1962 0, /* tp_repr */
1963 0, /* tp_as_number */
1964 0, /* tp_as_sequence */
1965 0, /* tp_as_mapping */
1966 0, /* tp_hash */
1967 0, /* tp_call */
1968 0, /* tp_str */
1969 PyObject_GenericGetAttr, /* tp_getattro */
1970 0, /* tp_setattro */
1971 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001972 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001973 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001974 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001975 0, /* tp_clear */
1976 0, /* tp_richcompare */
1977 0, /* tp_weaklistoffset */
1978 PyObject_SelfIter, /* tp_iter */
1979 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
1980 async_gen_athrow_methods, /* tp_methods */
1981 0, /* tp_members */
1982 0, /* tp_getset */
1983 0, /* tp_base */
1984 0, /* tp_dict */
1985 0, /* tp_descr_get */
1986 0, /* tp_descr_set */
1987 0, /* tp_dictoffset */
1988 0, /* tp_init */
1989 0, /* tp_alloc */
1990 0, /* tp_new */
1991};
1992
1993
1994static PyObject *
1995async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
1996{
1997 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05001998 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001999 if (o == NULL) {
2000 return NULL;
2001 }
2002 o->agt_gen = gen;
2003 o->agt_args = args;
2004 o->agt_state = AWAITABLE_STATE_INIT;
2005 Py_INCREF(gen);
2006 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002007 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002008 return (PyObject*)o;
2009}