blob: e7b8f8754a1f93af1564b6a7dabb75031405a04d [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"
8
9static int
10gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
11{
12 return visit((PyObject *)gen->gi_frame, arg);
13}
14
15static void
16gen_dealloc(PyGenObject *gen)
17{
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000018 PyObject *self = (PyObject *) gen;
19
Martin v. Löwise440e472004-06-01 15:22:42 +000020 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000021
Martin v. Löwise440e472004-06-01 15:22:42 +000022 if (gen->gi_weakreflist != NULL)
23 PyObject_ClearWeakRefs((PyObject *) gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000024
25
26 _PyObject_GC_TRACK(self);
27
28 if (gen->gi_frame->f_stacktop!=NULL) {
29 /* Generator is paused, so we need to close */
30 gen->ob_type->tp_del(self);
31 if (self->ob_refcnt > 0)
32 return; /* resurrected. :( */
33 }
34
35 _PyObject_GC_UNTRACK(self);
36 Py_XDECREF(gen->gi_frame);
Martin v. Löwise440e472004-06-01 15:22:42 +000037 PyObject_GC_Del(gen);
38}
39
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000040
Martin v. Löwise440e472004-06-01 15:22:42 +000041static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000042gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000043{
44 PyThreadState *tstate = PyThreadState_GET();
45 PyFrameObject *f = gen->gi_frame;
46 PyObject *result;
47
48 if (gen->gi_running) {
49 PyErr_SetString(PyExc_ValueError,
50 "generator already executing");
51 return NULL;
52 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000053 if ((PyObject *)f == Py_None || f->f_stacktop == NULL) {
54 /* Only set exception if called from send() */
55 if (arg && !exc) PyErr_SetNone(PyExc_StopIteration);
Martin v. Löwise440e472004-06-01 15:22:42 +000056 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000057 }
58
59 if (f->f_lasti == -1) {
60 if (arg && arg != Py_None) {
61 PyErr_SetString(PyExc_TypeError,
62 "can't send non-None value to a just-started generator");
63 return NULL;
64 }
65 } else {
66 /* Push arg onto the frame's value stack */
67 result = arg ? arg : Py_None;
68 Py_INCREF(result);
69 *(f->f_stacktop++) = result;
70 }
Martin v. Löwise440e472004-06-01 15:22:42 +000071
72 /* Generators always return to their most recent caller, not
73 * necessarily their creator. */
74 Py_XINCREF(tstate->frame);
75 assert(f->f_back == NULL);
76 f->f_back = tstate->frame;
77
78 gen->gi_running = 1;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000079 result = PyEval_EvalFrameEx(f, exc);
Martin v. Löwise440e472004-06-01 15:22:42 +000080 gen->gi_running = 0;
81
82 /* Don't keep the reference to f_back any longer than necessary. It
83 * may keep a chain of frames alive or it could create a reference
84 * cycle. */
Phillip J. Eby00148222005-08-13 03:29:00 +000085 assert(f->f_back == tstate->frame);
Raymond Hettinger75ccea32004-09-01 07:02:44 +000086 Py_CLEAR(f->f_back);
Martin v. Löwise440e472004-06-01 15:22:42 +000087
88 /* If the generator just returned (as opposed to yielding), signal
89 * that the generator is exhausted. */
90 if (result == Py_None && f->f_stacktop == NULL) {
91 Py_DECREF(result);
92 result = NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000093 /* Set exception if not called by gen_iternext() */
94 if (arg) PyErr_SetNone(PyExc_StopIteration);
95 }
96
97 if (!result || f->f_stacktop == NULL) {
98 /* generator can't be rerun, so release the frame */
99 Py_DECREF(f);
100 gen->gi_frame = (PyFrameObject *)Py_None;
101 Py_INCREF(Py_None);
Martin v. Löwise440e472004-06-01 15:22:42 +0000102 }
103
104 return result;
105}
106
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000107PyDoc_STRVAR(send_doc,
108"send(arg) -> send 'arg' into generator, return next yielded value or raise StopIteration.");
109
110static PyObject *
111gen_send(PyGenObject *gen, PyObject *arg)
112{
113 return gen_send_ex(gen, arg, 0);
114}
115
116PyDoc_STRVAR(close_doc,
117"close(arg) -> raise GeneratorExit inside generator.");
118
119static PyObject *
120gen_close(PyGenObject *gen, PyObject *args)
121{
122 PyObject *retval;
123 PyErr_SetNone(PyExc_GeneratorExit);
124 retval = gen_send_ex(gen, Py_None, 1);
125 if (retval) {
126 Py_DECREF(retval);
127 PyErr_SetString(PyExc_RuntimeError,
128 "generator ignored GeneratorExit");
129 return NULL;
130 }
131 if ( PyErr_ExceptionMatches(PyExc_StopIteration)
132 || PyErr_ExceptionMatches(PyExc_GeneratorExit) )
133 {
134 PyErr_Clear(); /* ignore these errors */
135 Py_INCREF(Py_None);
136 return Py_None;
137 }
138 return NULL;
139}
140
141static void
142gen_del(PyObject *self)
143{
144 PyObject *res;
145 PyObject *error_type, *error_value, *error_traceback;
146 PyGenObject *gen = (PyGenObject *)self;
147
148 if ((PyObject *)gen->gi_frame == Py_None || gen->gi_frame->f_stacktop==NULL)
149 /* Generator isn't paused, so no need to close */
150 return;
151
152 /* Temporarily resurrect the object. */
153 assert(self->ob_refcnt == 0);
154 self->ob_refcnt = 1;
155
156 /* Save the current exception, if any. */
157 PyErr_Fetch(&error_type, &error_value, &error_traceback);
158
159 res = gen_close((PyGenObject *)self, NULL);
160
161 if (res == NULL)
162 PyErr_WriteUnraisable((PyObject *)self);
163 else
164 Py_DECREF(res);
165
166 /* Restore the saved exception. */
167 PyErr_Restore(error_type, error_value, error_traceback);
168
169 /* Undo the temporary resurrection; can't use DECREF here, it would
170 * cause a recursive call.
171 */
172 assert(self->ob_refcnt > 0);
173 if (--self->ob_refcnt == 0)
174 return; /* this is the normal path out */
175
176 /* close() resurrected it! Make it look like the original Py_DECREF
177 * never happened.
178 */
179 {
Martin v. Löwis725507b2006-03-07 12:08:51 +0000180 Py_ssize_t refcnt = self->ob_refcnt;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000181 _Py_NewReference(self);
182 self->ob_refcnt = refcnt;
183 }
184 assert(!PyType_IS_GC(self->ob_type) ||
185 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
186
187 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
188 * we need to undo that. */
189 _Py_DEC_REFTOTAL;
190 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
191 * chain, so no more to do there.
192 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
193 * _Py_NewReference bumped tp_allocs: both of those need to be
194 * undone.
195 */
196#ifdef COUNT_ALLOCS
197 --self->ob_type->tp_frees;
198 --self->ob_type->tp_allocs;
199#endif
200}
201
202
203
204PyDoc_STRVAR(throw_doc,
205"throw(typ[,val[,tb]]) -> raise exception in generator, return next yielded value or raise StopIteration.");
206
207static PyObject *
208gen_throw(PyGenObject *gen, PyObject *args)
209{
210 PyObject *typ;
211 PyObject *tb = NULL;
212 PyObject *val = NULL;
213
214 if (!PyArg_ParseTuple(args, "O|OO:throw", &typ, &val, &tb))
215 return NULL;
216
Armin Rigo967aa8b2006-02-14 15:50:44 +0000217 /* First, check the traceback argument, replacing None with
218 NULL. */
219 if (tb == Py_None) {
220 Py_DECREF(tb);
221 tb = NULL;
222 }
223 else if (tb != NULL && !PyTraceBack_Check(tb)) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000224 PyErr_SetString(PyExc_TypeError,
225 "throw() third argument must be a traceback object");
226 return NULL;
227 }
228
229 Py_INCREF(typ);
230 Py_XINCREF(val);
231 Py_XINCREF(tb);
232
Brett Cannonbf364092006-03-01 04:25:17 +0000233 if (PyExceptionClass_Check(typ)) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000234 PyErr_NormalizeException(&typ, &val, &tb);
235 }
236
Brett Cannonbf364092006-03-01 04:25:17 +0000237 else if (PyExceptionInstance_Check(typ)) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000238 /* Raising an instance. The value should be a dummy. */
239 if (val && val != Py_None) {
240 PyErr_SetString(PyExc_TypeError,
241 "instance exception may not have a separate value");
242 goto failed_throw;
243 }
244 else {
245 /* Normalize to raise <class>, <instance> */
Armin Rigo967aa8b2006-02-14 15:50:44 +0000246 Py_XDECREF(val);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000247 val = typ;
Brett Cannonbf364092006-03-01 04:25:17 +0000248 typ = PyExceptionInstance_Class(typ);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000249 Py_INCREF(typ);
250 }
251 }
Phillip J. Ebybee07122006-03-25 00:05:50 +0000252
253 /* Allow raising builtin string exceptions */
254
255 else if (!PyString_CheckExact(typ)) {
Armin Rigo967aa8b2006-02-14 15:50:44 +0000256 /* Not something you can raise. throw() fails. */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000257 PyErr_Format(PyExc_TypeError,
258 "exceptions must be classes, or instances, not %s",
259 typ->ob_type->tp_name);
260 goto failed_throw;
261 }
262
263 PyErr_Restore(typ,val,tb);
264 return gen_send_ex(gen, Py_None, 1);
265
266failed_throw:
267 /* Didn't use our arguments, so restore their original refcounts */
268 Py_DECREF(typ);
269 Py_XDECREF(val);
270 Py_XDECREF(tb);
271 return NULL;
272}
273
274
275static PyObject *
276gen_iternext(PyGenObject *gen)
277{
278 return gen_send_ex(gen, NULL, 0);
279}
280
281
Martin v. Löwise440e472004-06-01 15:22:42 +0000282static PyMemberDef gen_memberlist[] = {
283 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), RO},
284 {"gi_running", T_INT, offsetof(PyGenObject, gi_running), RO},
285 {NULL} /* Sentinel */
286};
287
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000288static PyMethodDef gen_methods[] = {
289 {"send",(PyCFunction)gen_send, METH_O, send_doc},
290 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
291 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
292 {NULL, NULL} /* Sentinel */
293};
294
Martin v. Löwise440e472004-06-01 15:22:42 +0000295PyTypeObject PyGen_Type = {
296 PyObject_HEAD_INIT(&PyType_Type)
297 0, /* ob_size */
298 "generator", /* tp_name */
299 sizeof(PyGenObject), /* tp_basicsize */
300 0, /* tp_itemsize */
301 /* methods */
302 (destructor)gen_dealloc, /* tp_dealloc */
303 0, /* tp_print */
304 0, /* tp_getattr */
305 0, /* tp_setattr */
306 0, /* tp_compare */
307 0, /* tp_repr */
308 0, /* tp_as_number */
309 0, /* tp_as_sequence */
310 0, /* tp_as_mapping */
311 0, /* tp_hash */
312 0, /* tp_call */
313 0, /* tp_str */
314 PyObject_GenericGetAttr, /* tp_getattro */
315 0, /* tp_setattro */
316 0, /* tp_as_buffer */
317 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
318 0, /* tp_doc */
319 (traverseproc)gen_traverse, /* tp_traverse */
320 0, /* tp_clear */
321 0, /* tp_richcompare */
322 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Raymond Hettinger6c7a00f2004-06-12 05:17:55 +0000323 PyObject_SelfIter, /* tp_iter */
Martin v. Löwise440e472004-06-01 15:22:42 +0000324 (iternextfunc)gen_iternext, /* tp_iternext */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000325 gen_methods, /* tp_methods */
Martin v. Löwise440e472004-06-01 15:22:42 +0000326 gen_memberlist, /* tp_members */
327 0, /* tp_getset */
328 0, /* tp_base */
329 0, /* tp_dict */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000330
331 0, /* tp_descr_get */
332 0, /* tp_descr_set */
333 0, /* tp_dictoffset */
334 0, /* tp_init */
335 0, /* tp_alloc */
336 0, /* tp_new */
337 0, /* tp_free */
338 0, /* tp_is_gc */
339 0, /* tp_bases */
340 0, /* tp_mro */
341 0, /* tp_cache */
342 0, /* tp_subclasses */
343 0, /* tp_weaklist */
344 gen_del, /* tp_del */
Martin v. Löwise440e472004-06-01 15:22:42 +0000345};
346
347PyObject *
348PyGen_New(PyFrameObject *f)
349{
350 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
351 if (gen == NULL) {
352 Py_DECREF(f);
353 return NULL;
354 }
355 gen->gi_frame = f;
356 gen->gi_running = 0;
357 gen->gi_weakreflist = NULL;
358 _PyObject_GC_TRACK(gen);
359 return (PyObject *)gen;
360}