blob: bad485c2df0710d0b0fd2ef04d47b742cbd87f1e [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"
5#include "genobject.h"
6#include "ceval.h"
7#include "structmember.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00009
10static int
11gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
12{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013 Py_VISIT((PyObject *)gen->gi_frame);
14 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000015}
16
17static void
18gen_dealloc(PyGenObject *gen)
19{
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000020 PyObject *self = (PyObject *) gen;
21
Martin v. Löwise440e472004-06-01 15:22:42 +000022 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000023
Martin v. Löwise440e472004-06-01 15:22:42 +000024 if (gen->gi_weakreflist != NULL)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000026
27 _PyObject_GC_TRACK(self);
28
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000029 if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000030 /* Generator is paused, so we need to close */
31 gen->ob_type->tp_del(self);
32 if (self->ob_refcnt > 0)
33 return; /* resurrected. :( */
34 }
35
36 _PyObject_GC_UNTRACK(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000037 Py_CLEAR(gen->gi_frame);
Martin v. Löwise440e472004-06-01 15:22:42 +000038 PyObject_GC_Del(gen);
39}
40
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000041
Martin v. Löwise440e472004-06-01 15:22:42 +000042static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000043gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000044{
45 PyThreadState *tstate = PyThreadState_GET();
46 PyFrameObject *f = gen->gi_frame;
47 PyObject *result;
48
49 if (gen->gi_running) {
50 PyErr_SetString(PyExc_ValueError,
51 "generator already executing");
52 return NULL;
53 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 if (f==NULL || f->f_stacktop == NULL) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000055 /* Only set exception if called from send() */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056 if (arg && !exc)
57 PyErr_SetNone(PyExc_StopIteration);
Martin v. Löwise440e472004-06-01 15:22:42 +000058 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000059 }
60
61 if (f->f_lasti == -1) {
62 if (arg && arg != Py_None) {
63 PyErr_SetString(PyExc_TypeError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064 "can't send non-None value to a "
65 "just-started generator");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000066 return NULL;
67 }
68 } else {
69 /* Push arg onto the frame's value stack */
70 result = arg ? arg : Py_None;
71 Py_INCREF(result);
72 *(f->f_stacktop++) = result;
73 }
Martin v. Löwise440e472004-06-01 15:22:42 +000074
75 /* Generators always return to their most recent caller, not
76 * necessarily their creator. */
77 Py_XINCREF(tstate->frame);
78 assert(f->f_back == NULL);
79 f->f_back = tstate->frame;
80
81 gen->gi_running = 1;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000082 result = PyEval_EvalFrameEx(f, exc);
Martin v. Löwise440e472004-06-01 15:22:42 +000083 gen->gi_running = 0;
84
85 /* Don't keep the reference to f_back any longer than necessary. It
86 * may keep a chain of frames alive or it could create a reference
87 * cycle. */
Phillip J. Eby00148222005-08-13 03:29:00 +000088 assert(f->f_back == tstate->frame);
Raymond Hettinger75ccea32004-09-01 07:02:44 +000089 Py_CLEAR(f->f_back);
Martin v. Löwise440e472004-06-01 15:22:42 +000090
91 /* If the generator just returned (as opposed to yielding), signal
92 * that the generator is exhausted. */
93 if (result == Py_None && f->f_stacktop == NULL) {
94 Py_DECREF(result);
95 result = NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000096 /* Set exception if not called by gen_iternext() */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000097 if (arg)
98 PyErr_SetNone(PyExc_StopIteration);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000099 }
100
101 if (!result || f->f_stacktop == NULL) {
102 /* generator can't be rerun, so release the frame */
103 Py_DECREF(f);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000104 gen->gi_frame = NULL;
Martin v. Löwise440e472004-06-01 15:22:42 +0000105 }
106
107 return result;
108}
109
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000110PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000111"send(arg) -> send 'arg' into generator,\n\
112return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000113
114static PyObject *
115gen_send(PyGenObject *gen, PyObject *arg)
116{
117 return gen_send_ex(gen, arg, 0);
118}
119
120PyDoc_STRVAR(close_doc,
121"close(arg) -> raise GeneratorExit inside generator.");
122
123static PyObject *
124gen_close(PyGenObject *gen, PyObject *args)
125{
126 PyObject *retval;
127 PyErr_SetNone(PyExc_GeneratorExit);
128 retval = gen_send_ex(gen, Py_None, 1);
129 if (retval) {
130 Py_DECREF(retval);
131 PyErr_SetString(PyExc_RuntimeError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000132 "generator ignored GeneratorExit");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000133 return NULL;
134 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000135 if (PyErr_ExceptionMatches(PyExc_StopIteration)
136 || PyErr_ExceptionMatches(PyExc_GeneratorExit))
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000137 {
138 PyErr_Clear(); /* ignore these errors */
139 Py_INCREF(Py_None);
140 return Py_None;
141 }
142 return NULL;
143}
144
145static void
146gen_del(PyObject *self)
147{
148 PyObject *res;
149 PyObject *error_type, *error_value, *error_traceback;
150 PyGenObject *gen = (PyGenObject *)self;
151
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000152 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000153 /* Generator isn't paused, so no need to close */
154 return;
155
156 /* Temporarily resurrect the object. */
157 assert(self->ob_refcnt == 0);
158 self->ob_refcnt = 1;
159
160 /* Save the current exception, if any. */
161 PyErr_Fetch(&error_type, &error_value, &error_traceback);
162
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163 res = gen_close(gen, NULL);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000164
165 if (res == NULL)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166 PyErr_WriteUnraisable(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000167 else
168 Py_DECREF(res);
169
170 /* Restore the saved exception. */
171 PyErr_Restore(error_type, error_value, error_traceback);
172
173 /* Undo the temporary resurrection; can't use DECREF here, it would
174 * cause a recursive call.
175 */
176 assert(self->ob_refcnt > 0);
177 if (--self->ob_refcnt == 0)
178 return; /* this is the normal path out */
179
180 /* close() resurrected it! Make it look like the original Py_DECREF
181 * never happened.
182 */
183 {
Martin v. Löwis725507b2006-03-07 12:08:51 +0000184 Py_ssize_t refcnt = self->ob_refcnt;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000185 _Py_NewReference(self);
186 self->ob_refcnt = refcnt;
187 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188 assert(PyType_IS_GC(self->ob_type) &&
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000189 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
190
191 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
192 * we need to undo that. */
193 _Py_DEC_REFTOTAL;
194 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
195 * chain, so no more to do there.
196 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
197 * _Py_NewReference bumped tp_allocs: both of those need to be
198 * undone.
199 */
200#ifdef COUNT_ALLOCS
201 --self->ob_type->tp_frees;
202 --self->ob_type->tp_allocs;
203#endif
204}
205
206
207
208PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
210return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000211
212static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000213gen_throw(PyGenObject *gen, PyObject *args)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000214{
215 PyObject *typ;
216 PyObject *tb = NULL;
217 PyObject *val = NULL;
218
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000219 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000220 return NULL;
221
Armin Rigo967aa8b2006-02-14 15:50:44 +0000222 /* First, check the traceback argument, replacing None with
223 NULL. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000224 if (tb == Py_None)
Armin Rigo967aa8b2006-02-14 15:50:44 +0000225 tb = NULL;
Armin Rigo967aa8b2006-02-14 15:50:44 +0000226 else if (tb != NULL && !PyTraceBack_Check(tb)) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000227 PyErr_SetString(PyExc_TypeError,
228 "throw() third argument must be a traceback object");
229 return NULL;
230 }
231
232 Py_INCREF(typ);
233 Py_XINCREF(val);
234 Py_XINCREF(tb);
235
Brett Cannonbf364092006-03-01 04:25:17 +0000236 if (PyExceptionClass_Check(typ)) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000237 PyErr_NormalizeException(&typ, &val, &tb);
238 }
239
Brett Cannonbf364092006-03-01 04:25:17 +0000240 else if (PyExceptionInstance_Check(typ)) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000241 /* Raising an instance. The value should be a dummy. */
242 if (val && val != Py_None) {
243 PyErr_SetString(PyExc_TypeError,
244 "instance exception may not have a separate value");
245 goto failed_throw;
246 }
247 else {
248 /* Normalize to raise <class>, <instance> */
Armin Rigo967aa8b2006-02-14 15:50:44 +0000249 Py_XDECREF(val);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000250 val = typ;
Brett Cannonbf364092006-03-01 04:25:17 +0000251 typ = PyExceptionInstance_Class(typ);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000252 Py_INCREF(typ);
253 }
254 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000255
Guido van Rossumbf12cdb2006-08-17 20:24:18 +0000256 else {
Armin Rigo967aa8b2006-02-14 15:50:44 +0000257 /* Not something you can raise. throw() fails. */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000258 PyErr_Format(PyExc_TypeError,
Guido van Rossumbf12cdb2006-08-17 20:24:18 +0000259 "exceptions must be classes or instances "
260 "deriving from BaseException, not %s",
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000261 typ->ob_type->tp_name);
262 goto failed_throw;
263 }
264
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000265 PyErr_Restore(typ, val, tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000266 return gen_send_ex(gen, Py_None, 1);
267
268failed_throw:
269 /* Didn't use our arguments, so restore their original refcounts */
270 Py_DECREF(typ);
271 Py_XDECREF(val);
272 Py_XDECREF(tb);
273 return NULL;
274}
275
276
277static PyObject *
278gen_iternext(PyGenObject *gen)
279{
280 return gen_send_ex(gen, NULL, 0);
281}
282
283
Martin v. Löwise440e472004-06-01 15:22:42 +0000284static PyMemberDef gen_memberlist[] = {
285 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), RO},
286 {"gi_running", T_INT, offsetof(PyGenObject, gi_running), RO},
287 {NULL} /* Sentinel */
288};
289
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000290static PyMethodDef gen_methods[] = {
291 {"send",(PyCFunction)gen_send, METH_O, send_doc},
292 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
293 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
294 {NULL, NULL} /* Sentinel */
295};
296
Martin v. Löwise440e472004-06-01 15:22:42 +0000297PyTypeObject PyGen_Type = {
298 PyObject_HEAD_INIT(&PyType_Type)
299 0, /* ob_size */
300 "generator", /* tp_name */
301 sizeof(PyGenObject), /* tp_basicsize */
302 0, /* tp_itemsize */
303 /* methods */
304 (destructor)gen_dealloc, /* tp_dealloc */
305 0, /* tp_print */
306 0, /* tp_getattr */
307 0, /* tp_setattr */
308 0, /* tp_compare */
309 0, /* tp_repr */
310 0, /* tp_as_number */
311 0, /* tp_as_sequence */
312 0, /* tp_as_mapping */
313 0, /* tp_hash */
314 0, /* tp_call */
315 0, /* tp_str */
316 PyObject_GenericGetAttr, /* tp_getattro */
317 0, /* tp_setattro */
318 0, /* tp_as_buffer */
319 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
320 0, /* tp_doc */
321 (traverseproc)gen_traverse, /* tp_traverse */
322 0, /* tp_clear */
323 0, /* tp_richcompare */
324 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Raymond Hettinger6c7a00f2004-06-12 05:17:55 +0000325 PyObject_SelfIter, /* tp_iter */
Martin v. Löwise440e472004-06-01 15:22:42 +0000326 (iternextfunc)gen_iternext, /* tp_iternext */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000327 gen_methods, /* tp_methods */
Martin v. Löwise440e472004-06-01 15:22:42 +0000328 gen_memberlist, /* tp_members */
329 0, /* tp_getset */
330 0, /* tp_base */
331 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000332
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000333 0, /* tp_descr_get */
334 0, /* tp_descr_set */
335 0, /* tp_dictoffset */
336 0, /* tp_init */
337 0, /* tp_alloc */
338 0, /* tp_new */
339 0, /* tp_free */
340 0, /* tp_is_gc */
341 0, /* tp_bases */
342 0, /* tp_mro */
343 0, /* tp_cache */
344 0, /* tp_subclasses */
345 0, /* tp_weaklist */
346 gen_del, /* tp_del */
Martin v. Löwise440e472004-06-01 15:22:42 +0000347};
348
349PyObject *
350PyGen_New(PyFrameObject *f)
351{
352 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
353 if (gen == NULL) {
354 Py_DECREF(f);
355 return NULL;
356 }
357 gen->gi_frame = f;
358 gen->gi_running = 0;
359 gen->gi_weakreflist = NULL;
360 _PyObject_GC_TRACK(gen);
361 return (PyObject *)gen;
362}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000363
364int
365PyGen_NeedsFinalizing(PyGenObject *gen)
366{
367 int i;
368 PyFrameObject *f = gen->gi_frame;
369
370 if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0)
371 return 0; /* no frame or empty blockstack == no finalization */
372
373 /* Any block type besides a loop requires cleanup. */
374 i = f->f_iblock;
375 while (--i >= 0) {
376 if (f->f_blockstack[i].b_type != SETUP_LOOP)
377 return 1;
378 }
379
380 /* No blocks except loops, it's safe to skip finalization. */
381 return 0;
382}