chiark / gitweb /
catacomb-python.h, *.c: Fix how Python `pgen' handlers handle exceptions.
[catacomb-python] / util.c
1 /* -*-c-*-
2  *
3  * Miscellaneous utilities (not Catacomb-specific)
4  *
5  * (c) 2005 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of the Python interface to Catacomb.
11  *
12  * Catacomb/Python is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * Catacomb/Python is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with Catacomb/Python; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "catacomb-python.h"
30
31 /* #undef HAVE_LONG_LONG */
32
33 /*----- External values ---------------------------------------------------*/
34
35 static PyObject *modname = 0;
36 PyObject *home_module = 0;
37
38 /*----- Conversions -------------------------------------------------------*/
39
40 PyObject *getulong(unsigned long w)
41 {
42   if (w <= LONG_MAX)
43     return (PyInt_FromLong(w));
44   else
45     return (PyLong_FromUnsignedLong(w));
46 }
47
48 #ifndef HAVE_LONG_LONG
49 static PyObject *i32 = 0;
50 static int init_i32(void)
51   { if (!i32 && (i32 = PyInt_FromLong(32)) == 0) return (-1); return (0); }
52 #endif
53
54 PyObject *getk64(kludge64 u)
55 {
56 #ifdef HAVE_LONG_LONG
57   return (PyLong_FromUnsignedLongLong(GET64(unsigned PY_LONG_LONG, u)));
58 #else
59   PyObject *i = 0, *j = 0, *t;
60   PyObject *rc = 0;
61
62   if (init_i32()) goto end;
63   if ((i = PyLong_FromUnsignedLong(HI64(u))) == 0) goto end;
64   if ((t = PyNumber_InPlaceLshift(i, i32)) == 0) goto end;
65   Py_DECREF(i); i = t;
66   if ((j = PyLong_FromUnsignedLong(LO64(u))) == 0) goto end;
67   if ((t = PyNumber_InPlaceOr(i, j)) == 0) goto end;
68   Py_DECREF(i); i = t;
69   if ((rc = PyNumber_Int(i)) == 0) goto end;
70 end:
71   if (i) Py_DECREF(i);
72   if (j) Py_DECREF(j);
73   return (rc);
74 #endif
75 }
76
77 PyObject *getbool(int b)
78 {
79   if (b) RETURN_TRUE;
80   else RETURN_FALSE;
81 }
82
83 PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
84 {
85   PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
86   return (0);
87 }
88
89 int convulong(PyObject *o, void *pp)
90 {
91   long i;
92   unsigned long *p = pp;
93   PyObject *t;
94
95   if (!o) VALERR("can't delete");
96   if (PyInt_Check(o)) {
97     i = PyInt_AS_LONG(o);
98     if (i < 0) VALERR("must be nonnegative");
99     *p = i;
100   } else {
101     if ((t = PyNumber_Long(o)) == 0) goto end;
102     *p = PyLong_AsUnsignedLong(t);
103     Py_DECREF(t);
104     if (PyErr_Occurred()) goto end;
105   }
106   return (1);
107 end:
108   return (0);
109 }
110
111 #ifdef HAVE_UINT64
112 #  define CONVu64(n) do {                                               \
113      kludge64 k;                                                        \
114      uint64 t;                                                          \
115      if (!convk64(o, &k)) goto end;                                     \
116      t = GET64(uint64, k);                                              \
117      if (t > MASK##n) VALERR("out of range");                           \
118      *p = t;                                                            \
119    } while (0)
120 #else
121 #  define CONVu64(n) assert(!"shouldn't be possible")
122 #endif
123
124 #define CONVU_(n)                                                       \
125   int convu##n(PyObject *o, void *pp)                                   \
126   {                                                                     \
127     unsigned long u;                                                    \
128     uint##n *p = pp;                                                    \
129                                                                         \
130     if (MASK##n > ULONG_MAX)                                            \
131       CONVu64(n);                                                       \
132     else {                                                              \
133       if (!convulong(o, &u)) goto end;                                  \
134       if (u > MASK##n) VALERR("out of range");                          \
135       *p = u;                                                           \
136     }                                                                   \
137     return (1);                                                         \
138   end:                                                                  \
139     return (0);                                                         \
140   }
141 DOUINTSZ(CONVU_)
142
143 int convuint(PyObject *o, void *pp)
144 {
145   unsigned long u;
146   unsigned *p = pp;
147
148   if (!convulong(o, &u)) goto end;
149   if (u > UINT_MAX) VALERR("out of range");
150   *p = u;
151   return (1);
152 end:
153   return (0);
154 }
155
156 int convk64(PyObject *o, void *pp)
157 {
158   PyObject *i = 0;
159   int rc = 0;
160 #if HAVE_LONG_LONG
161   unsigned PY_LONG_LONG t;
162 #else
163   PyObject *t;
164   uint32 lo, hi;
165 #endif
166
167   if (!o) VALERR("can't delete");
168 #if HAVE_LONG_LONG
169   if ((i = PyNumber_Long(o)) == 0) goto end;
170   t = PyLong_AsUnsignedLongLong(i);
171   if (t == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) goto end;
172   ASSIGN64(*(kludge64 *)pp, t);
173 #else
174   if (init_i32()) goto end;
175   if ((i = PyNumber_Int(o)) == 0) goto end;
176   lo = PyInt_AsUnsignedLongMask(i);
177   if ((t = PyNumber_InPlaceRshift(i, i32)) == 0) goto end;
178   Py_DECREF(i); i = t;
179   hi = PyInt_AsUnsignedLongMask(i);
180   if ((t = PyNumber_InPlaceRshift(i, i32)) == 0) goto end;
181   Py_DECREF(i); i = t;
182   if (PyObject_IsTrue(i)) VALERR("out of range");
183   SET64(*(kludge64 *)pp, hi, lo);
184 #endif
185   rc = 1;
186
187 end:
188   if (i) Py_DECREF(i);
189   return (rc);
190 }
191
192 int convmpw(PyObject *o, void *pp)
193 {
194   unsigned long u;
195   unsigned *p = pp;
196
197   if (!convulong(o, &u)) goto end;
198   if (u > MPW_MAX) VALERR("out of range");
199   *p = u;
200   return (1);
201 end:
202   return (0);
203 }
204
205 int convszt(PyObject *o, void *pp)
206 {
207   unsigned long u;
208   size_t *p = pp;
209
210   if (!convulong(o, &u)) goto end;
211   if (u > ~(size_t)0) VALERR("out of range");
212   *p = u;
213   return (1);
214 end:
215   return (0);
216 }
217
218 int convbool(PyObject *o, void *pp)
219 {
220   if (!o) VALERR("can't delete");
221   *(int *)pp = PyObject_IsTrue(o);
222   return (1);
223 end:
224   return (0);
225 }
226
227 /*----- Type messing ------------------------------------------------------*/
228
229 static const PyTypeObject emptytype = { 0 };
230
231 void *newtype(PyTypeObject *metaty,
232               const PyTypeObject *skel,
233               const char *name)
234 {
235   PyHeapTypeObject *ty =
236     (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
237   if (!skel) skel = &emptytype;
238   memcpy(ty, skel, sizeof(*skel));
239   if (ty->ht_type.tp_base) Py_INCREF(ty->ht_type.tp_base);
240 #define COPY(blah) do {                                                 \
241     if (ty->ht_type.tp_as_##blah) {                                     \
242       memcpy(&ty->as_##blah,                                            \
243              ty->ht_type.tp_as_##blah,                                  \
244              sizeof(ty->as_##blah));                                    \
245       ty->ht_type.tp_as_##blah = &ty->as_##blah;                        \
246     }                                                                   \
247   } while (0)
248   COPY(number);
249   COPY(sequence);
250   COPY(mapping);
251   COPY(buffer);
252 #undef COPY
253   if (name)
254     ty->ht_name = PyString_FromString(name);
255   else if (ty->ht_type.tp_name)
256     ty->ht_name = PyString_FromString(ty->ht_type.tp_name);
257   if (ty->ht_name)
258     ty->ht_type.tp_name = PyString_AS_STRING(ty->ht_name);
259   DISCARD(PyObject_INIT(&ty->ht_type, metaty));
260   Py_INCREF(metaty);
261   return (ty);
262 }
263
264 void typeready(PyTypeObject *ty)
265 {
266   PyType_Ready(ty);
267   PyDict_SetItemString(ty->tp_dict, "__module__", modname);
268 }
269
270 PyTypeObject *inittype(PyTypeObject *tyskel, PyTypeObject *meta)
271 {
272   PyTypeObject *ty = newtype(meta, tyskel, 0);
273   ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
274   typeready(ty);
275   return (ty);
276 }
277
278 /*----- Constants ---------------------------------------------------------*/
279
280 void setconstants(PyObject *mod, const struct nameval *c)
281 {
282   PyObject *x;
283
284   while (c->name) {
285     if (c->value > LONG_MAX)
286       x = PyLong_FromUnsignedLong(c->value);
287     else
288       x = PyInt_FromLong(c->value);
289     PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
290     c++;
291   }
292 }
293
294 /*----- Building method tables --------------------------------------------*/
295
296 DA_DECL(method_v, PyMethodDef);
297 static method_v global_pymethods = DA_INIT;
298 void addmethods(const PyMethodDef *m)
299 {
300   size_t n;
301
302   for (n = 0; m[n].ml_name; n++);
303   DA_ENSURE(&global_pymethods, n);
304   memcpy(DA(&global_pymethods) + DA_LEN(&global_pymethods),
305          m, n * sizeof(*m));
306   DA_EXTEND(&global_pymethods, n);
307 }
308
309 PyMethodDef *donemethods(void)
310 {
311   static const PyMethodDef mzero = { 0 };
312   DA_PUSH(&global_pymethods, mzero);
313   return (DA(&global_pymethods));
314 }
315
316 /*----- Exceptions --------------------------------------------------------*/
317
318 PyObject *mkexc(PyObject *mod, PyObject *base,
319                 const char *name, PyMethodDef *mm)
320 {
321   PyObject *nameobj = 0;
322   PyObject *dict = 0;
323   PyObject *exc = 0;
324   PyObject *func = 0;
325   PyObject *meth = 0;
326
327   if ((nameobj = PyString_FromFormat("%s.%s",
328                                      PyModule_GetName(mod),
329                                      name)) == 0 ||
330       (dict = PyDict_New()) == 0 ||
331       (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
332                                 base, dict)) == 0)
333     goto fail;
334
335   if (mm) {
336     while (mm->ml_name) {
337       if ((func = PyCFunction_NewEx(mm, 0, mod)) == 0 ||
338           (meth = PyMethod_New(func, 0, exc)) == 0 ||
339           PyDict_SetItemString(dict, mm->ml_name, meth))
340         goto fail;
341       Py_DECREF(func); func = 0;
342       Py_DECREF(meth); meth = 0;
343       mm++;
344     }
345   }
346
347 done:
348   Py_XDECREF(nameobj);
349   Py_XDECREF(dict);
350   return (exc);
351
352 fail:
353   Py_XDECREF(exc);
354   Py_XDECREF(func);
355   Py_XDECREF(meth);
356   exc = 0;
357   goto done;
358 }
359
360 void report_lost_exception_v(struct excinfo *exc,
361                              const char *why, va_list ap)
362 {
363   PyObject *hookfn = 0;
364   PyObject *whyobj = 0;
365   PyObject *obj = 0;
366
367   /* Make sure we start out without a pending exception, or this will get
368    * really confusing.
369    */
370   assert(!PyErr_Occurred());
371
372   /* Format the explanation. */
373   if (why) whyobj = PyString_FromFormatV(why, ap);
374   else { whyobj = Py_None; Py_INCREF(whyobj); }
375
376   /* Find our home module's `lostexchook' function.  This won't work if
377    * there's no module, or the function isn't defined, or it's `None'.
378    */
379   if (!home_module) goto sys;
380   hookfn = PyObject_GetAttrString(home_module, "lostexchook");
381   if (hookfn == Py_None) goto sys;
382   else if (hookfn) ;
383   else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
384   else { PyErr_Clear(); goto sys; }
385
386   /* Call the hook function. */
387   obj = PyObject_CallFunction(hookfn, "(OOOO)",
388                               whyobj, exc->ty, exc->val, exc->tb);
389   if (!obj) goto ouch;
390   goto end;
391
392   /* Something went wrong reporting the problem. */
393 ouch:
394   PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
395   PyErr_Print();
396   /* drop through... */
397
398   /* There was no hook, so try to do something sensible using
399    * `sys.excepthook'.
400    */
401 sys:
402   PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n",
403                     PyString_AS_STRING(whyobj));
404   RESTORE_EXCINFO(exc);
405   PyErr_Print();
406   /* drop through... */
407
408   /* Clean up afterwards. */
409 end:
410   Py_XDECREF(hookfn);
411   Py_XDECREF(whyobj);
412   Py_XDECREF(obj);
413 }
414
415 void report_lost_exception(struct excinfo *exc, const char *why, ...)
416 {
417   va_list ap;
418
419   va_start(ap, why);
420   report_lost_exception_v(exc, why, ap);
421   va_end(ap);
422 }
423
424 void stash_exception(struct excinfo *exc, const char *why, ...)
425 {
426   va_list ap;
427   struct excinfo stash;
428
429   if (!exc->ty)
430     STASH_EXCINFO(exc);
431   else {
432     va_start(ap, why);
433     STASH_EXCINFO(&stash);
434     report_lost_exception_v(&stash, why, ap);
435     va_end(ap);
436   }
437 }
438
439 void restore_exception(struct excinfo *exc, const char *why, ...)
440 {
441   va_list ap;
442   struct excinfo stash;
443
444   if (!PyErr_Occurred())
445     RESTORE_EXCINFO(exc);
446   else {
447     va_start(ap, why);
448     STASH_EXCINFO(&stash);
449     report_lost_exception_v(exc, why, ap);
450     RESTORE_EXCINFO(&stash);
451     va_end(ap);
452   }
453 }
454
455 /*----- Generic dictionary methods ----------------------------------------*/
456
457 static PyTypeObject *itemiter_pytype, *valiter_pytype;
458
459 typedef struct iter_pyobj {
460   PyObject_HEAD
461   PyObject *map;
462   PyObject *i;
463 } iter_pyobj;
464 #define ITER_MAP(o) (((iter_pyobj *)(o))->map)
465 #define ITER_I(o) (((iter_pyobj *)(o))->i)
466
467 static void iter_pydealloc(PyObject *me)
468   { Py_DECREF(ITER_MAP(me)); Py_DECREF(ITER_I(me)); FREEOBJ(me); }
469
470 static PyObject *itemiter_pynext(PyObject *me)
471 {
472   PyObject *k = 0, *v = 0, *rc = 0;
473
474   if ((k = PyIter_Next(ITER_I(me))) != 0 &&
475       (v = PyObject_GetItem(ITER_MAP(me), k)) != 0)
476     rc = Py_BuildValue("(OO)", k, v);
477   Py_XDECREF(k); Py_XDECREF(v);
478   return (rc);
479 }
480
481 static PyTypeObject itemiter_pytype_skel = {
482   PyObject_HEAD_INIT(0) 0,              /* Header */
483   "ItemIter",                           /* @tp_name@ */
484   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
485   0,                                    /* @tp_itemsize@ */
486
487   iter_pydealloc,                       /* @tp_dealloc@ */
488   0,                                    /* @tp_print@ */
489   0,                                    /* @tp_getattr@ */
490   0,                                    /* @tp_setattr@ */
491   0,                                    /* @tp_compare@ */
492   0,                                    /* @tp_repr@ */
493   0,                                    /* @tp_as_number@ */
494   0,                                    /* @tp_as_sequence@ */
495   0,                                    /* @tp_as_mapping@ */
496   0,                                    /* @tp_hash@ */
497   0,                                    /* @tp_call@ */
498   0,                                    /* @tp_str@ */
499   0,                                    /* @tp_getattro@ */
500   0,                                    /* @tp_setattro@ */
501   0,                                    /* @tp_as_buffer@ */
502   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
503     Py_TPFLAGS_BASETYPE,
504
505   /* @tp_doc@ */
506 "Iterates over the keys of a mapping.",
507
508   0,                                    /* @tp_traverse@ */
509   0,                                    /* @tp_clear@ */
510   0,                                    /* @tp_richcompare@ */
511   0,                                    /* @tp_weaklistoffset@ */
512   PyObject_SelfIter,                    /* @tp_iter@ */
513   itemiter_pynext,                      /* @tp_iternext@ */
514   0,                                    /* @tp_methods@ */
515   0,                                    /* @tp_members@ */
516   0,                                    /* @tp_getset@ */
517   0,                                    /* @tp_base@ */
518   0,                                    /* @tp_dict@ */
519   0,                                    /* @tp_descr_get@ */
520   0,                                    /* @tp_descr_set@ */
521   0,                                    /* @tp_dictoffset@ */
522   0,                                    /* @tp_init@ */
523   PyType_GenericAlloc,                  /* @tp_alloc@ */
524   abstract_pynew,                       /* @tp_new@ */
525   0,                                    /* @tp_free@ */
526   0                                     /* @tp_is_gc@ */
527 };
528
529 static PyObject *valiter_pynext(PyObject *me)
530 {
531   PyObject *k = 0, *rc = 0;
532
533   if ((k = PyIter_Next(ITER_I(me))) != 0)
534     rc = PyObject_GetItem(ITER_MAP(me), k);
535   Py_XDECREF(k);
536   return (rc);
537 }
538
539 static PyTypeObject valiter_pytype_skel = {
540   PyObject_HEAD_INIT(0) 0,              /* Header */
541   "ValueIter",                          /* @tp_name@ */
542   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
543   0,                                    /* @tp_itemsize@ */
544
545   iter_pydealloc,                       /* @tp_dealloc@ */
546   0,                                    /* @tp_print@ */
547   0,                                    /* @tp_getattr@ */
548   0,                                    /* @tp_setattr@ */
549   0,                                    /* @tp_compare@ */
550   0,                                    /* @tp_repr@ */
551   0,                                    /* @tp_as_number@ */
552   0,                                    /* @tp_as_sequence@ */
553   0,                                    /* @tp_as_mapping@ */
554   0,                                    /* @tp_hash@ */
555   0,                                    /* @tp_call@ */
556   0,                                    /* @tp_str@ */
557   0,                                    /* @tp_getattro@ */
558   0,                                    /* @tp_setattro@ */
559   0,                                    /* @tp_as_buffer@ */
560   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
561     Py_TPFLAGS_BASETYPE,
562
563   /* @tp_doc@ */
564 "Iterates over the values of a mapping.",
565
566   0,                                    /* @tp_traverse@ */
567   0,                                    /* @tp_clear@ */
568   0,                                    /* @tp_richcompare@ */
569   0,                                    /* @tp_weaklistoffset@ */
570   PyObject_SelfIter,                    /* @tp_iter@ */
571   valiter_pynext,                       /* @tp_iternext@ */
572   0,                                    /* @tp_methods@ */
573   0,                                    /* @tp_members@ */
574   0,                                    /* @tp_getset@ */
575   0,                                    /* @tp_base@ */
576   0,                                    /* @tp_dict@ */
577   0,                                    /* @tp_descr_get@ */
578   0,                                    /* @tp_descr_set@ */
579   0,                                    /* @tp_dictoffset@ */
580   0,                                    /* @tp_init@ */
581   PyType_GenericAlloc,                  /* @tp_alloc@ */
582   abstract_pynew,                       /* @tp_new@ */
583   0,                                    /* @tp_free@ */
584   0                                     /* @tp_is_gc@ */
585 };
586
587 PySequenceMethods gmap_pysequence = {
588   0,                                    /* @sq_length@ */
589   0,                                    /* @sq_concat@ */
590   0,                                    /* @sq_repeat@ */
591   0,                                    /* @sq_item@ */
592   0,                                    /* @sq_slice@ */
593   0,                                    /* @sq_ass_item@ */
594   0,                                    /* @sq_ass_slice@ */
595   PyMapping_HasKey,                     /* @sq_contains@ */
596   0,                                    /* @sq_inplace_concat@ */
597   0                                     /* @sq_inplace_repeat@ */
598 };
599
600 Py_ssize_t gmap_pysize(PyObject *me)
601 {
602   PyObject *i = 0, *x = 0;
603   Py_ssize_t rc = -1, n = 0;
604
605   if ((i = PyObject_GetIter(me)) == 0) goto done;
606   while ((x = PyIter_Next(i)) != 0) { n++; Py_DECREF(x); x = 0; }
607   if (PyErr_Occurred()) goto done;
608   rc = n;
609 done:
610   Py_XDECREF(i); Py_XDECREF(x);
611   return (rc);
612 }
613
614 PyObject *gmapmeth_has_key(PyObject *me, PyObject *arg)
615 {
616   PyObject *k;
617   if (!PyArg_ParseTuple(arg, "O:has_key", &k)) return (0);
618   return (getbool(PyMapping_HasKey(me, k)));
619 }
620
621 PyObject *gmapmeth_keys(PyObject *me, PyObject *arg)
622 {
623   PyObject *l = 0, *i = 0, *k, *rc = 0;
624   int err;
625
626   if (!PyArg_ParseTuple(arg, ":keys") ||
627       (l = PyList_New(0)) == 0 ||
628       (i = PyObject_GetIter(me)) == 0)
629     goto done;
630   while ((k = PyIter_Next(i)) != 0)
631     { err = PyList_Append(l, k); Py_DECREF(k); if (err) goto done; }
632   if (PyErr_Occurred()) goto done;
633   rc = l; l = 0;
634 done:
635   Py_XDECREF(l); Py_XDECREF(i);
636   return (rc);
637 }
638
639 PyObject *gmapmeth_values(PyObject *me, PyObject *arg)
640 {
641   PyObject *l = 0, *i = 0, *k, *v, *rc = 0;
642   int err = 0;
643
644   if (!PyArg_ParseTuple(arg, ":values") ||
645       (l = PyList_New(0)) == 0 ||
646       (i = PyObject_GetIter(me)) == 0)
647     goto done;
648   while ((k = PyIter_Next(i)) != 0) {
649     if ((v = PyObject_GetItem(me, k)) == 0 ||
650         PyList_Append(l, v))
651       err = -1;
652     Py_DECREF(k); Py_XDECREF(v);
653     if (err) goto done;
654   }
655   if (PyErr_Occurred()) goto done;
656   rc = l; l = 0;
657 done:
658   Py_XDECREF(l); Py_XDECREF(i);
659   return (rc);
660 }
661
662 PyObject *gmapmeth_items(PyObject *me, PyObject *arg)
663 {
664   PyObject *l = 0, *i = 0, *k, *v, *z, *rc = 0;
665   int err = 0;
666
667   if (!PyArg_ParseTuple(arg, ":items") ||
668       (l = PyList_New(0)) == 0 ||
669       (i = PyObject_GetIter(me)) == 0)
670     goto done;
671   while ((k = PyIter_Next(i)) != 0) {
672     z = 0;
673     if ((v = PyObject_GetItem(me, k)) == 0 ||
674         (z = Py_BuildValue("(OO)", k, v)) == 0 ||
675         PyList_Append(l, z))
676       err = -1;
677     Py_DECREF(k); Py_XDECREF(v); Py_XDECREF(z);
678     if (err) goto done;
679   }
680   if (PyErr_Occurred()) goto done;
681   rc = l; l = 0;
682 done:
683   Py_XDECREF(l); Py_XDECREF(i);
684   return (rc);
685 }
686
687 PyObject *gmapmeth_iterkeys(PyObject *me, PyObject *arg)
688 {
689   if (!PyArg_ParseTuple(arg, ":iterkeys")) return (0);
690   return (PyObject_GetIter(me));
691 }
692
693 PyObject *gmapmeth_itervalues(PyObject *me, PyObject *arg)
694 {
695   PyObject *i;
696   iter_pyobj *ii;
697
698   if (!PyArg_ParseTuple(arg, ":itervalues") ||
699       (i = PyObject_GetIter(me)) == 0)
700     return (0);
701   ii = PyObject_NEW(iter_pyobj, valiter_pytype);
702   ii->map = me; Py_INCREF(me);
703   ii->i = i;
704   return ((PyObject *)ii);
705 }
706
707 PyObject *gmapmeth_iteritems(PyObject *me, PyObject *arg)
708 {
709   PyObject *i;
710   iter_pyobj *ii;
711
712   if (!PyArg_ParseTuple(arg, ":iteritems") ||
713       (i = PyObject_GetIter(me)) == 0)
714     return (0);
715   ii = PyObject_NEW(iter_pyobj, itemiter_pytype);
716   ii->map = me; Py_INCREF(me);
717   ii->i = i;
718   return ((PyObject *)ii);
719 }
720
721 PyObject *gmapmeth_clear(PyObject *me, PyObject *arg)
722 {
723   PyObject *i = 0, *k = 0, *rc = 0;
724
725   if (!PyArg_ParseTuple(arg, ":clear") ||
726       (i = PyObject_GetIter(me)) == 0)
727     goto end;
728   while ((k = PyIter_Next(i)) != 0) {
729     PyObject_DelItem(me, k);
730     Py_DECREF(k);
731   }
732   if (PyErr_Occurred()) goto end;
733   rc = me; Py_INCREF(me);
734 end:
735   Py_XDECREF(i);
736   return (rc);
737 }
738
739 static char *def_kwlist[] = { "key", "default", 0 };
740
741 PyObject *gmapmeth_get(PyObject *me, PyObject *arg, PyObject *kw)
742 {
743   PyObject *k, *def = Py_None, *v;
744
745   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:get", def_kwlist, &k, &def))
746     return (0);
747   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
748   PyErr_Clear();
749   RETURN_OBJ(def);
750 }
751
752 PyObject *gmapmeth_setdefault(PyObject *me, PyObject *arg, PyObject *kw)
753 {
754   PyObject *k, *def = Py_None, *v;
755
756   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:setdefault",
757                                    def_kwlist, &k, &def))
758     return (0);
759   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
760   PyErr_Clear();
761   if (PyObject_SetItem(me, k, def)) return (0);
762   RETURN_OBJ(def);
763 }
764
765 PyObject *gmapmeth_pop(PyObject *me, PyObject *arg, PyObject *kw)
766 {
767   PyObject *k, *def = 0, *v;
768
769   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:pop", def_kwlist, &k, &def))
770     return (0);
771   if ((v = PyObject_GetItem(me, k)) != 0) {
772     PyObject_DelItem(me, k);
773     return (v);
774   }
775   PyErr_Clear();
776   RETURN_OBJ(def);
777 }
778
779 PyObject *gmapmeth_update(PyObject *me, PyObject *arg)
780 {
781   PyObject *map, *i = 0, *k, *v, *rc = 0;
782   int err = 0;
783
784   if (!PyArg_ParseTuple(arg, "O:update", &map) ||
785       (i = PyObject_GetIter(map)) == 0)
786     goto end;
787   while ((k = PyIter_Next(i)) != 0) {
788     if ((v = PyObject_GetItem(map, k)) == 0 ||
789         PyObject_SetItem(me, k, v))
790       err = -1;
791     Py_DECREF(k); Py_XDECREF(v);
792     if (err) goto end;
793   }
794   if (PyErr_Occurred()) goto end;
795   rc = me; Py_INCREF(me);
796 end:
797   Py_XDECREF(i);
798   return (rc);
799 }
800
801 PyObject *gmapmeth_popitem(PyObject *me, PyObject *arg)
802 {
803   PyObject *i = 0, *k = 0, *v = 0, *rc = 0;
804
805   if (!PyArg_ParseTuple(arg, ":popitem") ||
806       (i = PyObject_GetIter(me)))
807     goto end;
808   if ((k = PyIter_Next(i)) == 0) {
809     if (!PyErr_Occurred()) VALERR("popitem(): mapping is empty");
810     goto end;
811   }
812   if ((v = PyObject_GetItem(me, k)) == 0 ||
813       PyObject_DelItem(me, k))
814     goto end;
815   rc = Py_BuildValue("(OO)", k, v);
816 end:
817   Py_XDECREF(i); Py_XDECREF(k); Py_XDECREF(v);
818   return (rc);
819 }
820
821 PyMethodDef gmap_pymethods[] = {
822   GMAP_METHODS
823   { 0 }
824 };
825
826 /*----- Initialization ----------------------------------------------------*/
827
828 static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
829 {
830   PyObject *mod;
831
832   if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
833     return (0);
834   Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
835   RETURN_NONE;
836 }
837
838 static const PyMethodDef methods[] = {
839 #define METHNAME(func) meth_##func
840   METH  (_set_home_module,      "_set_home_module(MOD)")
841 #undef METHNAME
842   { 0 }
843 };
844
845 void util_pyinit(void)
846 {
847   modname = PyString_FromString("catacomb");
848   INITTYPE(itemiter, root);
849   INITTYPE(valiter, root);
850   addmethods(methods);
851 }
852
853 void util_pyinsert(PyObject *mod)
854 {
855   INSERT("ItemIter", itemiter_pytype);
856   INSERT("ValueIter", valiter_pytype);
857 }
858
859 /*----- That's all, folks -------------------------------------------------*/