blob: 82b629cfea85a12ebdc0436292f89d8b5ce6e60a [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
Nick Coghlan1f7ce622012-01-13 21:43:40 +10008static PyObject *gen_close(PyGenObject *gen, PyObject *args);
Nick Coghlan1f7ce622012-01-13 21:43:40 +10009
Martin v. Löwise440e472004-06-01 15:22:42 +000010static int
11gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
12{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013 Py_VISIT((PyObject *)gen->gi_frame);
14 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020015 Py_VISIT(gen->gi_name);
16 Py_VISIT(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000018}
19
Antoine Pitrou58720d62013-08-05 23:26:40 +020020void
21_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020022{
23 PyGenObject *gen = (PyGenObject *)self;
24 PyObject *res;
25 PyObject *error_type, *error_value, *error_traceback;
26
27 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
28 /* Generator isn't paused, so no need to close */
29 return;
30
31 /* Save the current exception, if any. */
32 PyErr_Fetch(&error_type, &error_value, &error_traceback);
33
34 res = gen_close(gen, NULL);
35
36 if (res == NULL)
37 PyErr_WriteUnraisable(self);
38 else
39 Py_DECREF(res);
40
41 /* Restore the saved exception. */
42 PyErr_Restore(error_type, error_value, error_traceback);
43}
44
45static void
Martin v. Löwise440e472004-06-01 15:22:42 +000046gen_dealloc(PyGenObject *gen)
47{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 if (gen->gi_weakreflist != NULL)
53 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000054
Antoine Pitrou93963562013-05-14 20:37:52 +020055 _PyObject_GC_TRACK(self);
56
Antoine Pitrou796564c2013-07-30 19:59:21 +020057 if (PyObject_CallFinalizerFromDealloc(self))
58 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +020059
60 _PyObject_GC_UNTRACK(self);
61 Py_CLEAR(gen->gi_frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020063 Py_CLEAR(gen->gi_name);
64 Py_CLEAR(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +000066}
67
68static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000069gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000070{
Antoine Pitrou93963562013-05-14 20:37:52 +020071 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +020073 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +000074
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -050075 if (gen->gi_running) {
76 PyErr_SetString(PyExc_ValueError,
77 "generator already executing");
78 return NULL;
79 }
Antoine Pitrou93963562013-05-14 20:37:52 +020080 if (f == NULL || f->f_stacktop == NULL) {
81 /* Only set exception if called from send() */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 if (arg && !exc)
83 PyErr_SetNone(PyExc_StopIteration);
84 return NULL;
85 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000086
Antoine Pitrou93963562013-05-14 20:37:52 +020087 if (f->f_lasti == -1) {
88 if (arg && arg != Py_None) {
89 PyErr_SetString(PyExc_TypeError,
90 "can't send non-None value to a "
91 "just-started generator");
92 return NULL;
93 }
94 } else {
95 /* Push arg onto the frame's value stack */
96 result = arg ? arg : Py_None;
97 Py_INCREF(result);
98 *(f->f_stacktop++) = result;
99 }
100
101 /* Generators always return to their most recent caller, not
102 * necessarily their creator. */
103 Py_XINCREF(tstate->frame);
104 assert(f->f_back == NULL);
105 f->f_back = tstate->frame;
106
107 gen->gi_running = 1;
108 result = PyEval_EvalFrameEx(f, exc);
109 gen->gi_running = 0;
110
111 /* Don't keep the reference to f_back any longer than necessary. It
112 * may keep a chain of frames alive or it could create a reference
113 * cycle. */
114 assert(f->f_back == tstate->frame);
115 Py_CLEAR(f->f_back);
116
117 /* If the generator just returned (as opposed to yielding), signal
118 * that the generator is exhausted. */
119 if (result && f->f_stacktop == NULL) {
120 if (result == Py_None) {
121 /* Delay exception instantiation if we can */
122 PyErr_SetNone(PyExc_StopIteration);
123 } else {
124 PyObject *e = PyObject_CallFunctionObjArgs(
125 PyExc_StopIteration, result, NULL);
126 if (e != NULL) {
127 PyErr_SetObject(PyExc_StopIteration, e);
128 Py_DECREF(e);
129 }
130 }
131 Py_CLEAR(result);
132 }
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400133 else if (!result) {
134 /* Check for __future__ generator_stop and conditionally turn
135 * a leaking StopIteration into RuntimeError (with its cause
136 * set appropriately). */
137 if ((((PyCodeObject *)gen->gi_code)->co_flags &
138 CO_FUTURE_GENERATOR_STOP)
139 && PyErr_ExceptionMatches(PyExc_StopIteration))
140 {
141 PyObject *exc, *val, *val2, *tb;
142 PyErr_Fetch(&exc, &val, &tb);
143 PyErr_NormalizeException(&exc, &val, &tb);
144 if (tb != NULL)
145 PyException_SetTraceback(val, tb);
146 Py_DECREF(exc);
147 Py_XDECREF(tb);
148 PyErr_SetString(PyExc_RuntimeError,
149 "generator raised StopIteration");
150 PyErr_Fetch(&exc, &val2, &tb);
151 PyErr_NormalizeException(&exc, &val2, &tb);
Yury Selivanov18c30a22015-05-10 15:09:46 -0400152 Py_INCREF(val);
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400153 PyException_SetCause(val2, val);
154 PyException_SetContext(val2, val);
155 PyErr_Restore(exc, val2, tb);
156 }
157 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200158
159 if (!result || f->f_stacktop == NULL) {
160 /* generator can't be rerun, so release the frame */
161 /* first clean reference cycle through stored exception traceback */
162 PyObject *t, *v, *tb;
163 t = f->f_exc_type;
164 v = f->f_exc_value;
165 tb = f->f_exc_traceback;
166 f->f_exc_type = NULL;
167 f->f_exc_value = NULL;
168 f->f_exc_traceback = NULL;
169 Py_XDECREF(t);
170 Py_XDECREF(v);
171 Py_XDECREF(tb);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200172 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200173 gen->gi_frame = NULL;
174 Py_DECREF(f);
175 }
176
177 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000178}
179
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000180PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181"send(arg) -> send 'arg' into generator,\n\
182return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000183
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500184PyObject *
185_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000186{
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500187 return gen_send_ex(gen, arg, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000188}
189
190PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400191"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000192
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000193/*
194 * This helper function is used by gen_close and gen_throw to
195 * close a subiterator being delegated to by yield-from.
196 */
197
Antoine Pitrou93963562013-05-14 20:37:52 +0200198static int
199gen_close_iter(PyObject *yf)
200{
201 PyObject *retval = NULL;
202 _Py_IDENTIFIER(close);
203
204 if (PyGen_CheckExact(yf)) {
205 retval = gen_close((PyGenObject *)yf, NULL);
206 if (retval == NULL)
207 return -1;
208 } else {
209 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
210 if (meth == NULL) {
211 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
212 PyErr_WriteUnraisable(yf);
213 PyErr_Clear();
214 } else {
215 retval = PyObject_CallFunction(meth, "");
216 Py_DECREF(meth);
217 if (retval == NULL)
218 return -1;
219 }
220 }
221 Py_XDECREF(retval);
222 return 0;
223}
224
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500225static PyObject *
226gen_yf(PyGenObject *gen)
227{
Antoine Pitrou93963562013-05-14 20:37:52 +0200228 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500229 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200230
231 if (f && f->f_stacktop) {
232 PyObject *bytecode = f->f_code->co_code;
233 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
234
235 if (code[f->f_lasti + 1] != YIELD_FROM)
236 return NULL;
237 yf = f->f_stacktop[-1];
238 Py_INCREF(yf);
239 }
240
241 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500242}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000243
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000244static PyObject *
245gen_close(PyGenObject *gen, PyObject *args)
246{
Antoine Pitrou93963562013-05-14 20:37:52 +0200247 PyObject *retval;
248 PyObject *yf = gen_yf(gen);
249 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000250
Antoine Pitrou93963562013-05-14 20:37:52 +0200251 if (yf) {
252 gen->gi_running = 1;
253 err = gen_close_iter(yf);
254 gen->gi_running = 0;
255 Py_DECREF(yf);
256 }
257 if (err == 0)
258 PyErr_SetNone(PyExc_GeneratorExit);
259 retval = gen_send_ex(gen, Py_None, 1);
260 if (retval) {
261 Py_DECREF(retval);
262 PyErr_SetString(PyExc_RuntimeError,
263 "generator ignored GeneratorExit");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 return NULL;
265 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200266 if (PyErr_ExceptionMatches(PyExc_StopIteration)
267 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
268 PyErr_Clear(); /* ignore these errors */
269 Py_INCREF(Py_None);
270 return Py_None;
271 }
272 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000273}
274
Antoine Pitrou93963562013-05-14 20:37:52 +0200275
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000276PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
278return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000279
280static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000281gen_throw(PyGenObject *gen, PyObject *args)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 PyObject *typ;
284 PyObject *tb = NULL;
285 PyObject *val = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500286 PyObject *yf = gen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000287 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
290 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000291
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000292 if (yf) {
293 PyObject *ret;
294 int err;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000295 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500296 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200297 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500298 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000299 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000300 if (err < 0)
301 return gen_send_ex(gen, Py_None, 1);
302 goto throw_here;
303 }
304 if (PyGen_CheckExact(yf)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500305 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000306 ret = gen_throw((PyGenObject *)yf, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500307 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000308 } else {
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000309 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000310 if (meth == NULL) {
311 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
312 Py_DECREF(yf);
313 return NULL;
314 }
315 PyErr_Clear();
316 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000317 goto throw_here;
318 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500319 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000320 ret = PyObject_CallObject(meth, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500321 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000322 Py_DECREF(meth);
323 }
324 Py_DECREF(yf);
325 if (!ret) {
326 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500327 /* Pop subiterator from stack */
328 ret = *(--gen->gi_frame->f_stacktop);
329 assert(ret == yf);
330 Py_DECREF(ret);
331 /* Termination repetition of YIELD_FROM */
332 gen->gi_frame->f_lasti++;
Nick Coghlanc40bc092012-06-17 15:15:49 +1000333 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000334 ret = gen_send_ex(gen, val, 0);
335 Py_DECREF(val);
336 } else {
337 ret = gen_send_ex(gen, Py_None, 1);
338 }
339 }
340 return ret;
341 }
342
343throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 /* First, check the traceback argument, replacing None with
345 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400346 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 else if (tb != NULL && !PyTraceBack_Check(tb)) {
350 PyErr_SetString(PyExc_TypeError,
351 "throw() third argument must be a traceback object");
352 return NULL;
353 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 Py_INCREF(typ);
356 Py_XINCREF(val);
357 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000358
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400359 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 else if (PyExceptionInstance_Check(typ)) {
363 /* Raising an instance. The value should be a dummy. */
364 if (val && val != Py_None) {
365 PyErr_SetString(PyExc_TypeError,
366 "instance exception may not have a separate value");
367 goto failed_throw;
368 }
369 else {
370 /* Normalize to raise <class>, <instance> */
371 Py_XDECREF(val);
372 val = typ;
373 typ = PyExceptionInstance_Class(typ);
374 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200375
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400376 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200377 /* Returns NULL if there's no traceback */
378 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 }
380 }
381 else {
382 /* Not something you can raise. throw() fails. */
383 PyErr_Format(PyExc_TypeError,
384 "exceptions must be classes or instances "
385 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000386 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 goto failed_throw;
388 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyErr_Restore(typ, val, tb);
391 return gen_send_ex(gen, Py_None, 1);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000392
393failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* Didn't use our arguments, so restore their original refcounts */
395 Py_DECREF(typ);
396 Py_XDECREF(val);
397 Py_XDECREF(tb);
398 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000399}
400
401
402static PyObject *
403gen_iternext(PyGenObject *gen)
404{
Antoine Pitrou667f5452014-07-08 18:43:23 -0400405 return gen_send_ex(gen, NULL, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000406}
407
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000408/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000409 * If StopIteration exception is set, fetches its 'value'
410 * attribute if any, otherwise sets pvalue to None.
411 *
412 * Returns 0 if no exception or StopIteration is set.
413 * If any other exception is set, returns -1 and leaves
414 * pvalue unchanged.
415 */
416
417int
Nick Coghlanc40bc092012-06-17 15:15:49 +1000418_PyGen_FetchStopIterationValue(PyObject **pvalue) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000419 PyObject *et, *ev, *tb;
420 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500421
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000422 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
423 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200424 if (ev) {
425 /* exception will usually be normalised already */
426 if (Py_TYPE(ev) == (PyTypeObject *) et
427 || PyObject_IsInstance(ev, PyExc_StopIteration)) {
428 value = ((PyStopIterationObject *)ev)->value;
429 Py_INCREF(value);
430 Py_DECREF(ev);
431 } else if (et == PyExc_StopIteration) {
432 /* avoid normalisation and take ev as value */
433 value = ev;
434 } else {
435 /* normalisation required */
436 PyErr_NormalizeException(&et, &ev, &tb);
437 if (!PyObject_IsInstance(ev, PyExc_StopIteration)) {
438 PyErr_Restore(et, ev, tb);
439 return -1;
440 }
441 value = ((PyStopIterationObject *)ev)->value;
442 Py_INCREF(value);
443 Py_DECREF(ev);
444 }
445 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000446 Py_XDECREF(et);
447 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000448 } else if (PyErr_Occurred()) {
449 return -1;
450 }
451 if (value == NULL) {
452 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100453 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000454 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000455 *pvalue = value;
456 return 0;
457}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000458
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000459static PyObject *
460gen_repr(PyGenObject *gen)
461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 return PyUnicode_FromFormat("<generator object %S at %p>",
Victor Stinner40ee3012014-06-16 15:59:28 +0200463 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000464}
465
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000466static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200467gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000468{
Victor Stinner40ee3012014-06-16 15:59:28 +0200469 Py_INCREF(op->gi_name);
470 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000471}
472
Victor Stinner40ee3012014-06-16 15:59:28 +0200473static int
474gen_set_name(PyGenObject *op, PyObject *value)
475{
476 PyObject *tmp;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000477
Victor Stinner40ee3012014-06-16 15:59:28 +0200478 /* Not legal to del gen.gi_name or to set it to anything
479 * other than a string object. */
480 if (value == NULL || !PyUnicode_Check(value)) {
481 PyErr_SetString(PyExc_TypeError,
482 "__name__ must be set to a string object");
483 return -1;
484 }
485 tmp = op->gi_name;
486 Py_INCREF(value);
487 op->gi_name = value;
488 Py_DECREF(tmp);
489 return 0;
490}
491
492static PyObject *
493gen_get_qualname(PyGenObject *op)
494{
495 Py_INCREF(op->gi_qualname);
496 return op->gi_qualname;
497}
498
499static int
500gen_set_qualname(PyGenObject *op, PyObject *value)
501{
502 PyObject *tmp;
503
504 /* Not legal to del gen.__qualname__ or to set it to anything
505 * other than a string object. */
506 if (value == NULL || !PyUnicode_Check(value)) {
507 PyErr_SetString(PyExc_TypeError,
508 "__qualname__ must be set to a string object");
509 return -1;
510 }
511 tmp = op->gi_qualname;
512 Py_INCREF(value);
513 op->gi_qualname = value;
514 Py_DECREF(tmp);
515 return 0;
516}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000517
518static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200519 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
520 PyDoc_STR("name of the generator")},
521 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
522 PyDoc_STR("qualified name of the generator")},
523 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000524};
525
Martin v. Löwise440e472004-06-01 15:22:42 +0000526static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200527 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
528 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
529 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000531};
532
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000533static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500534 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
536 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
537 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000538};
539
Martin v. Löwise440e472004-06-01 15:22:42 +0000540PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyVarObject_HEAD_INIT(&PyType_Type, 0)
542 "generator", /* tp_name */
543 sizeof(PyGenObject), /* tp_basicsize */
544 0, /* tp_itemsize */
545 /* methods */
546 (destructor)gen_dealloc, /* tp_dealloc */
547 0, /* tp_print */
548 0, /* tp_getattr */
549 0, /* tp_setattr */
550 0, /* tp_reserved */
551 (reprfunc)gen_repr, /* tp_repr */
552 0, /* tp_as_number */
553 0, /* tp_as_sequence */
554 0, /* tp_as_mapping */
555 0, /* tp_hash */
556 0, /* tp_call */
557 0, /* tp_str */
558 PyObject_GenericGetAttr, /* tp_getattro */
559 0, /* tp_setattro */
560 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200561 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
562 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 0, /* tp_doc */
564 (traverseproc)gen_traverse, /* tp_traverse */
565 0, /* tp_clear */
566 0, /* tp_richcompare */
567 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
568 PyObject_SelfIter, /* tp_iter */
569 (iternextfunc)gen_iternext, /* tp_iternext */
570 gen_methods, /* tp_methods */
571 gen_memberlist, /* tp_members */
572 gen_getsetlist, /* tp_getset */
573 0, /* tp_base */
574 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 0, /* tp_descr_get */
577 0, /* tp_descr_set */
578 0, /* tp_dictoffset */
579 0, /* tp_init */
580 0, /* tp_alloc */
581 0, /* tp_new */
582 0, /* tp_free */
583 0, /* tp_is_gc */
584 0, /* tp_bases */
585 0, /* tp_mro */
586 0, /* tp_cache */
587 0, /* tp_subclasses */
588 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200589 0, /* tp_del */
590 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200591 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000592};
593
594PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200595PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
598 if (gen == NULL) {
599 Py_DECREF(f);
600 return NULL;
601 }
602 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200603 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 Py_INCREF(f->f_code);
605 gen->gi_code = (PyObject *)(f->f_code);
606 gen->gi_running = 0;
607 gen->gi_weakreflist = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200608 if (name != NULL)
609 gen->gi_name = name;
610 else
611 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
612 Py_INCREF(gen->gi_name);
613 if (qualname != NULL)
614 gen->gi_qualname = qualname;
615 else
616 gen->gi_qualname = gen->gi_name;
617 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 _PyObject_GC_TRACK(gen);
619 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000620}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000621
Victor Stinner40ee3012014-06-16 15:59:28 +0200622PyObject *
623PyGen_New(PyFrameObject *f)
624{
625 return PyGen_NewWithQualName(f, NULL, NULL);
626}
627
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000628int
629PyGen_NeedsFinalizing(PyGenObject *gen)
630{
Antoine Pitrou93963562013-05-14 20:37:52 +0200631 int i;
632 PyFrameObject *f = gen->gi_frame;
633
634 if (f == NULL || f->f_stacktop == NULL)
635 return 0; /* no frame or empty blockstack == no finalization */
636
637 /* Any block type besides a loop requires cleanup. */
638 for (i = 0; i < f->f_iblock; i++)
639 if (f->f_blockstack[i].b_type != SETUP_LOOP)
640 return 1;
641
642 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000644}