blob: 016bfa297522c8fe71f0d2085b407124dffb0817 [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);
15 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000016}
17
18static void
19gen_dealloc(PyGenObject *gen)
20{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 if (gen->gi_weakreflist != NULL)
26 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000027
Antoine Pitrou93963562013-05-14 20:37:52 +020028 _PyObject_GC_TRACK(self);
29
30 if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) {
31 /* Generator is paused, so we need to close */
32 Py_TYPE(gen)->tp_del(self);
33 if (self->ob_refcnt > 0)
34 return; /* resurrected. :( */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 }
Antoine Pitrou93963562013-05-14 20:37:52 +020036
37 _PyObject_GC_UNTRACK(self);
38 Py_CLEAR(gen->gi_frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 Py_CLEAR(gen->gi_code);
40 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +000041}
42
Antoine Pitrou93963562013-05-14 20:37:52 +020043
Martin v. Löwise440e472004-06-01 15:22:42 +000044static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000045gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000046{
Antoine Pitrou93963562013-05-14 20:37:52 +020047 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +020049 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +000050
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -050051 if (gen->gi_running) {
52 PyErr_SetString(PyExc_ValueError,
53 "generator already executing");
54 return NULL;
55 }
Antoine Pitrou93963562013-05-14 20:37:52 +020056 if (f == NULL || f->f_stacktop == NULL) {
57 /* Only set exception if called from send() */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (arg && !exc)
59 PyErr_SetNone(PyExc_StopIteration);
60 return NULL;
61 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000062
Antoine Pitrou93963562013-05-14 20:37:52 +020063 if (f->f_lasti == -1) {
64 if (arg && arg != Py_None) {
65 PyErr_SetString(PyExc_TypeError,
66 "can't send non-None value to a "
67 "just-started generator");
68 return NULL;
69 }
70 } else {
71 /* Push arg onto the frame's value stack */
72 result = arg ? arg : Py_None;
73 Py_INCREF(result);
74 *(f->f_stacktop++) = result;
75 }
76
77 /* Generators always return to their most recent caller, not
78 * necessarily their creator. */
79 Py_XINCREF(tstate->frame);
80 assert(f->f_back == NULL);
81 f->f_back = tstate->frame;
82
83 gen->gi_running = 1;
84 result = PyEval_EvalFrameEx(f, exc);
85 gen->gi_running = 0;
86
87 /* Don't keep the reference to f_back any longer than necessary. It
88 * may keep a chain of frames alive or it could create a reference
89 * cycle. */
90 assert(f->f_back == tstate->frame);
91 Py_CLEAR(f->f_back);
92
93 /* If the generator just returned (as opposed to yielding), signal
94 * that the generator is exhausted. */
95 if (result && f->f_stacktop == NULL) {
96 if (result == Py_None) {
97 /* Delay exception instantiation if we can */
98 PyErr_SetNone(PyExc_StopIteration);
99 } else {
100 PyObject *e = PyObject_CallFunctionObjArgs(
101 PyExc_StopIteration, result, NULL);
102 if (e != NULL) {
103 PyErr_SetObject(PyExc_StopIteration, e);
104 Py_DECREF(e);
105 }
106 }
107 Py_CLEAR(result);
108 }
109
110 if (!result || f->f_stacktop == NULL) {
111 /* generator can't be rerun, so release the frame */
112 /* first clean reference cycle through stored exception traceback */
113 PyObject *t, *v, *tb;
114 t = f->f_exc_type;
115 v = f->f_exc_value;
116 tb = f->f_exc_traceback;
117 f->f_exc_type = NULL;
118 f->f_exc_value = NULL;
119 f->f_exc_traceback = NULL;
120 Py_XDECREF(t);
121 Py_XDECREF(v);
122 Py_XDECREF(tb);
123 gen->gi_frame = NULL;
124 Py_DECREF(f);
125 }
126
127 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000128}
129
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000130PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000131"send(arg) -> send 'arg' into generator,\n\
132return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000133
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500134PyObject *
135_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000136{
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500137 return gen_send_ex(gen, arg, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000138}
139
140PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400141"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000142
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000143/*
144 * This helper function is used by gen_close and gen_throw to
145 * close a subiterator being delegated to by yield-from.
146 */
147
Antoine Pitrou93963562013-05-14 20:37:52 +0200148static int
149gen_close_iter(PyObject *yf)
150{
151 PyObject *retval = NULL;
152 _Py_IDENTIFIER(close);
153
154 if (PyGen_CheckExact(yf)) {
155 retval = gen_close((PyGenObject *)yf, NULL);
156 if (retval == NULL)
157 return -1;
158 } else {
159 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
160 if (meth == NULL) {
161 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
162 PyErr_WriteUnraisable(yf);
163 PyErr_Clear();
164 } else {
165 retval = PyObject_CallFunction(meth, "");
166 Py_DECREF(meth);
167 if (retval == NULL)
168 return -1;
169 }
170 }
171 Py_XDECREF(retval);
172 return 0;
173}
174
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500175static PyObject *
176gen_yf(PyGenObject *gen)
177{
Antoine Pitrou93963562013-05-14 20:37:52 +0200178 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500179 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200180
181 if (f && f->f_stacktop) {
182 PyObject *bytecode = f->f_code->co_code;
183 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
184
185 if (code[f->f_lasti + 1] != YIELD_FROM)
186 return NULL;
187 yf = f->f_stacktop[-1];
188 Py_INCREF(yf);
189 }
190
191 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500192}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000193
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000194static PyObject *
195gen_close(PyGenObject *gen, PyObject *args)
196{
Antoine Pitrou93963562013-05-14 20:37:52 +0200197 PyObject *retval;
198 PyObject *yf = gen_yf(gen);
199 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000200
Antoine Pitrou93963562013-05-14 20:37:52 +0200201 if (yf) {
202 gen->gi_running = 1;
203 err = gen_close_iter(yf);
204 gen->gi_running = 0;
205 Py_DECREF(yf);
206 }
207 if (err == 0)
208 PyErr_SetNone(PyExc_GeneratorExit);
209 retval = gen_send_ex(gen, Py_None, 1);
210 if (retval) {
211 Py_DECREF(retval);
212 PyErr_SetString(PyExc_RuntimeError,
213 "generator ignored GeneratorExit");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 return NULL;
215 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200216 if (PyErr_ExceptionMatches(PyExc_StopIteration)
217 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
218 PyErr_Clear(); /* ignore these errors */
219 Py_INCREF(Py_None);
220 return Py_None;
221 }
222 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000223}
224
Antoine Pitrou93963562013-05-14 20:37:52 +0200225static void
226gen_del(PyObject *self)
227{
228 PyObject *res;
229 PyObject *error_type, *error_value, *error_traceback;
230 PyGenObject *gen = (PyGenObject *)self;
231
232 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
233 /* Generator isn't paused, so no need to close */
234 return;
235
236 /* Temporarily resurrect the object. */
237 assert(self->ob_refcnt == 0);
238 self->ob_refcnt = 1;
239
240 /* Save the current exception, if any. */
241 PyErr_Fetch(&error_type, &error_value, &error_traceback);
242
243 res = gen_close(gen, NULL);
244
245 if (res == NULL)
246 PyErr_WriteUnraisable(self);
247 else
248 Py_DECREF(res);
249
250 /* Restore the saved exception. */
251 PyErr_Restore(error_type, error_value, error_traceback);
252
253 /* Undo the temporary resurrection; can't use DECREF here, it would
254 * cause a recursive call.
255 */
256 assert(self->ob_refcnt > 0);
257 if (--self->ob_refcnt == 0)
258 return; /* this is the normal path out */
259
260 /* close() resurrected it! Make it look like the original Py_DECREF
261 * never happened.
262 */
263 {
264 Py_ssize_t refcnt = self->ob_refcnt;
265 _Py_NewReference(self);
266 self->ob_refcnt = refcnt;
267 }
268 assert(PyType_IS_GC(Py_TYPE(self)) &&
269 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
270
271 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
272 * we need to undo that. */
273 _Py_DEC_REFTOTAL;
274 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
275 * chain, so no more to do there.
276 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
277 * _Py_NewReference bumped tp_allocs: both of those need to be
278 * undone.
279 */
280#ifdef COUNT_ALLOCS
281 --(Py_TYPE(self)->tp_frees);
282 --(Py_TYPE(self)->tp_allocs);
283#endif
284}
285
286
287
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000288PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000289"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
290return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000291
292static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000293gen_throw(PyGenObject *gen, PyObject *args)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 PyObject *typ;
296 PyObject *tb = NULL;
297 PyObject *val = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500298 PyObject *yf = gen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000299 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
302 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000303
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000304 if (yf) {
305 PyObject *ret;
306 int err;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000307 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500308 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200309 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500310 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000311 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000312 if (err < 0)
313 return gen_send_ex(gen, Py_None, 1);
314 goto throw_here;
315 }
316 if (PyGen_CheckExact(yf)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500317 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000318 ret = gen_throw((PyGenObject *)yf, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500319 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000320 } else {
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000321 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000322 if (meth == NULL) {
323 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
324 Py_DECREF(yf);
325 return NULL;
326 }
327 PyErr_Clear();
328 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000329 goto throw_here;
330 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500331 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000332 ret = PyObject_CallObject(meth, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500333 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000334 Py_DECREF(meth);
335 }
336 Py_DECREF(yf);
337 if (!ret) {
338 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500339 /* Pop subiterator from stack */
340 ret = *(--gen->gi_frame->f_stacktop);
341 assert(ret == yf);
342 Py_DECREF(ret);
343 /* Termination repetition of YIELD_FROM */
344 gen->gi_frame->f_lasti++;
Nick Coghlanc40bc092012-06-17 15:15:49 +1000345 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000346 ret = gen_send_ex(gen, val, 0);
347 Py_DECREF(val);
348 } else {
349 ret = gen_send_ex(gen, Py_None, 1);
350 }
351 }
352 return ret;
353 }
354
355throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 /* First, check the traceback argument, replacing None with
357 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400358 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 else if (tb != NULL && !PyTraceBack_Check(tb)) {
362 PyErr_SetString(PyExc_TypeError,
363 "throw() third argument must be a traceback object");
364 return NULL;
365 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 Py_INCREF(typ);
368 Py_XINCREF(val);
369 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000370
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400371 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 else if (PyExceptionInstance_Check(typ)) {
375 /* Raising an instance. The value should be a dummy. */
376 if (val && val != Py_None) {
377 PyErr_SetString(PyExc_TypeError,
378 "instance exception may not have a separate value");
379 goto failed_throw;
380 }
381 else {
382 /* Normalize to raise <class>, <instance> */
383 Py_XDECREF(val);
384 val = typ;
385 typ = PyExceptionInstance_Class(typ);
386 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200387
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400388 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200389 /* Returns NULL if there's no traceback */
390 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 }
392 }
393 else {
394 /* Not something you can raise. throw() fails. */
395 PyErr_Format(PyExc_TypeError,
396 "exceptions must be classes or instances "
397 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000398 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 goto failed_throw;
400 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 PyErr_Restore(typ, val, tb);
403 return gen_send_ex(gen, Py_None, 1);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000404
405failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 /* Didn't use our arguments, so restore their original refcounts */
407 Py_DECREF(typ);
408 Py_XDECREF(val);
409 Py_XDECREF(tb);
410 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000411}
412
413
414static PyObject *
415gen_iternext(PyGenObject *gen)
416{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000417 PyObject *val = NULL;
418 PyObject *ret;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500419 ret = gen_send_ex(gen, val, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000420 Py_XDECREF(val);
421 return ret;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000422}
423
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000424/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000425 * If StopIteration exception is set, fetches its 'value'
426 * attribute if any, otherwise sets pvalue to None.
427 *
428 * Returns 0 if no exception or StopIteration is set.
429 * If any other exception is set, returns -1 and leaves
430 * pvalue unchanged.
431 */
432
433int
Nick Coghlanc40bc092012-06-17 15:15:49 +1000434_PyGen_FetchStopIterationValue(PyObject **pvalue) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000435 PyObject *et, *ev, *tb;
436 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500437
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
439 PyErr_Fetch(&et, &ev, &tb);
440 Py_XDECREF(et);
441 Py_XDECREF(tb);
442 if (ev) {
443 value = ((PyStopIterationObject *)ev)->value;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100444 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000445 Py_DECREF(ev);
446 }
447 } else if (PyErr_Occurred()) {
448 return -1;
449 }
450 if (value == NULL) {
451 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100452 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000453 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000454 *pvalue = value;
455 return 0;
456}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000457
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000458static PyObject *
459gen_repr(PyGenObject *gen)
460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 return PyUnicode_FromFormat("<generator object %S at %p>",
462 ((PyCodeObject *)gen->gi_code)->co_name,
463 gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000464}
465
466
467static PyObject *
468gen_get_name(PyGenObject *gen)
469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name;
471 Py_INCREF(name);
472 return name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000473}
474
475
476PyDoc_STRVAR(gen__name__doc__,
477"Return the name of the generator's associated code object.");
478
479static PyGetSetDef gen_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 {"__name__", (getter)gen_get_name, NULL, gen__name__doc__},
481 {NULL}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000482};
483
484
Martin v. Löwise440e472004-06-01 15:22:42 +0000485static PyMemberDef gen_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Benjamin Peterson657e9eb2012-03-07 18:17:03 -0600487 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
489 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000490};
491
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000492static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500493 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
495 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
496 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000497};
498
Martin v. Löwise440e472004-06-01 15:22:42 +0000499PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyVarObject_HEAD_INIT(&PyType_Type, 0)
501 "generator", /* tp_name */
502 sizeof(PyGenObject), /* tp_basicsize */
503 0, /* tp_itemsize */
504 /* methods */
505 (destructor)gen_dealloc, /* tp_dealloc */
506 0, /* tp_print */
507 0, /* tp_getattr */
508 0, /* tp_setattr */
509 0, /* tp_reserved */
510 (reprfunc)gen_repr, /* tp_repr */
511 0, /* tp_as_number */
512 0, /* tp_as_sequence */
513 0, /* tp_as_mapping */
514 0, /* tp_hash */
515 0, /* tp_call */
516 0, /* tp_str */
517 PyObject_GenericGetAttr, /* tp_getattro */
518 0, /* tp_setattro */
519 0, /* tp_as_buffer */
520 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
521 0, /* tp_doc */
522 (traverseproc)gen_traverse, /* tp_traverse */
523 0, /* tp_clear */
524 0, /* tp_richcompare */
525 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
526 PyObject_SelfIter, /* tp_iter */
527 (iternextfunc)gen_iternext, /* tp_iternext */
528 gen_methods, /* tp_methods */
529 gen_memberlist, /* tp_members */
530 gen_getsetlist, /* tp_getset */
531 0, /* tp_base */
532 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 0, /* tp_descr_get */
535 0, /* tp_descr_set */
536 0, /* tp_dictoffset */
537 0, /* tp_init */
538 0, /* tp_alloc */
539 0, /* tp_new */
540 0, /* tp_free */
541 0, /* tp_is_gc */
542 0, /* tp_bases */
543 0, /* tp_mro */
544 0, /* tp_cache */
545 0, /* tp_subclasses */
546 0, /* tp_weaklist */
Antoine Pitrou93963562013-05-14 20:37:52 +0200547 gen_del, /* tp_del */
Martin v. Löwise440e472004-06-01 15:22:42 +0000548};
549
550PyObject *
551PyGen_New(PyFrameObject *f)
552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
554 if (gen == NULL) {
555 Py_DECREF(f);
556 return NULL;
557 }
558 gen->gi_frame = f;
559 Py_INCREF(f->f_code);
560 gen->gi_code = (PyObject *)(f->f_code);
561 gen->gi_running = 0;
562 gen->gi_weakreflist = NULL;
563 _PyObject_GC_TRACK(gen);
564 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000565}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000566
567int
568PyGen_NeedsFinalizing(PyGenObject *gen)
569{
Antoine Pitrou93963562013-05-14 20:37:52 +0200570 int i;
571 PyFrameObject *f = gen->gi_frame;
572
573 if (f == NULL || f->f_stacktop == NULL)
574 return 0; /* no frame or empty blockstack == no finalization */
575
576 /* Any block type besides a loop requires cleanup. */
577 for (i = 0; i < f->f_iblock; i++)
578 if (f->f_blockstack[i].b_type != SETUP_LOOP)
579 return 1;
580
581 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000583}