chiark / gitweb /
b39b7d553496259a7dfcb0b9a364531b2bbef754
[mLib-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 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   Py_XDECREF(i);
72   Py_XDECREF(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   Py_XDECREF(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   unsigned long u;
284
285   while (c->name) {
286     u = c->value;
287     if (u <= LONG_MAX) x = PyInt_FromLong(u);
288     else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
289     else x = PyLong_FromUnsignedLong(u);
290     PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x); c++;
291   }
292 }
293
294 /*----- Building method tables --------------------------------------------*/
295
296 static PyMethodDef *global_methods;
297 static size_t nmethods, methodsz;
298
299 void addmethods(const PyMethodDef *m)
300 {
301   size_t n, want, newsz;
302
303   for (n = 0; m[n].ml_name; n++);
304   want = nmethods + n + 1;
305   if (want > methodsz) {
306     newsz = methodsz ? 2*methodsz : 16;
307     while (want > newsz) newsz *= 2;
308     if (!global_methods)
309       global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
310     else
311       global_methods = PyObject_Realloc(global_methods,
312                                         newsz*sizeof(PyMethodDef));
313     assert(global_methods);
314     methodsz = newsz;
315   }
316   memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
317   nmethods += n;
318   global_methods[nmethods].ml_name = 0;
319 }
320
321 PyMethodDef *donemethods(void) { return (global_methods); }
322
323 /*----- Exceptions --------------------------------------------------------*/
324
325 PyObject *mkexc(PyObject *mod, PyObject *base,
326                 const char *name, PyMethodDef *mm)
327 {
328   PyObject *nameobj = 0;
329   PyObject *dict = 0;
330   PyObject *exc = 0;
331   PyObject *func = 0;
332   PyObject *meth = 0;
333
334   if ((dict = PyDict_New()) == 0) goto fail;
335
336   if (mm) {
337     while (mm->ml_name) {
338       if ((func = PyCFunction_NewEx(mm, 0, mod)) == 0 ||
339           (meth = PyMethod_New(func, 0, exc)) == 0 ||
340           PyDict_SetItemString(dict, mm->ml_name, meth))
341         goto fail;
342       Py_DECREF(func); func = 0;
343       Py_DECREF(meth); meth = 0;
344       mm++;
345     }
346   }
347
348   if ((nameobj = PyString_FromFormat("%s.%s",
349                                      PyModule_GetName(mod),
350                                      name)) == 0 ||
351       (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
352                                 base, dict)) == 0)
353     goto fail;
354
355 done:
356   Py_XDECREF(nameobj);
357   Py_XDECREF(dict);
358   return (exc);
359
360 fail:
361   Py_XDECREF(exc);
362   Py_XDECREF(func);
363   Py_XDECREF(meth);
364   exc = 0;
365   goto done;
366 }
367
368 void report_lost_exception_v(struct excinfo *exc,
369                              const char *why, va_list ap)
370 {
371   PyObject *hookfn = 0;
372   PyObject *whyobj = 0;
373   PyObject *obj = 0;
374
375   /* Make sure we start out without a pending exception, or this will get
376    * really confusing.
377    */
378   assert(!PyErr_Occurred());
379
380   /* Format the explanation. */
381   if (why) whyobj = PyString_FromFormatV(why, ap);
382   else { whyobj = Py_None; Py_INCREF(whyobj); }
383
384   /* Find our home module's `lostexchook' function.  This won't work if
385    * there's no module, or the function isn't defined, or it's `None'.
386    */
387   if (!home_module) goto sys;
388   hookfn = PyObject_GetAttrString(home_module, "lostexchook");
389   if (hookfn == Py_None) goto sys;
390   else if (hookfn) ;
391   else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
392   else { PyErr_Clear(); goto sys; }
393
394   /* Call the hook function. */
395   obj = PyObject_CallFunction(hookfn, "(OOOO)",
396                               whyobj, exc->ty, exc->val, exc->tb);
397   if (!obj) goto ouch;
398   goto end;
399
400   /* Something went wrong reporting the problem. */
401 ouch:
402   PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
403   PyErr_Print();
404   /* drop through... */
405
406   /* There was no hook, so try to do something sensible using
407    * `sys.excepthook'.
408    */
409 sys:
410   PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n",
411                     PyString_AS_STRING(whyobj));
412   RESTORE_EXCINFO(exc);
413   PyErr_Print();
414   /* drop through... */
415
416   /* Clean up afterwards. */
417 end:
418   Py_XDECREF(hookfn);
419   Py_XDECREF(whyobj);
420   Py_XDECREF(obj);
421 }
422
423 void report_lost_exception(struct excinfo *exc, const char *why, ...)
424 {
425   va_list ap;
426
427   va_start(ap, why);
428   report_lost_exception_v(exc, why, ap);
429   va_end(ap);
430 }
431
432 void stash_exception(struct excinfo *exc, const char *why, ...)
433 {
434   va_list ap;
435   struct excinfo stash;
436
437   if (!exc->ty)
438     STASH_EXCINFO(exc);
439   else {
440     va_start(ap, why);
441     STASH_EXCINFO(&stash);
442     report_lost_exception_v(&stash, why, ap);
443     va_end(ap);
444   }
445 }
446
447 void restore_exception(struct excinfo *exc, const char *why, ...)
448 {
449   va_list ap;
450   struct excinfo stash;
451
452   if (!PyErr_Occurred())
453     RESTORE_EXCINFO(exc);
454   else {
455     va_start(ap, why);
456     STASH_EXCINFO(&stash);
457     report_lost_exception_v(exc, why, ap);
458     RESTORE_EXCINFO(&stash);
459     va_end(ap);
460   }
461 }
462
463 /*----- Generic dictionary methods ----------------------------------------*/
464
465 static PyTypeObject *itemiter_pytype, *valiter_pytype;
466
467 typedef struct iter_pyobj {
468   PyObject_HEAD
469   PyObject *map;
470   PyObject *i;
471 } iter_pyobj;
472 #define ITER_MAP(o) (((iter_pyobj *)(o))->map)
473 #define ITER_I(o) (((iter_pyobj *)(o))->i)
474
475 static void iter_pydealloc(PyObject *me)
476   { Py_DECREF(ITER_MAP(me)); Py_DECREF(ITER_I(me)); FREEOBJ(me); }
477
478 static PyObject *itemiter_pynext(PyObject *me)
479 {
480   PyObject *k = 0, *v = 0, *rc = 0;
481
482   if ((k = PyIter_Next(ITER_I(me))) != 0 &&
483       (v = PyObject_GetItem(ITER_MAP(me), k)) != 0)
484     rc = Py_BuildValue("(OO)", k, v);
485   Py_XDECREF(k); Py_XDECREF(v);
486   return (rc);
487 }
488
489 static PyTypeObject itemiter_pytype_skel = {
490   PyObject_HEAD_INIT(0) 0,              /* Header */
491   "ItemIter",                           /* @tp_name@ */
492   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
493   0,                                    /* @tp_itemsize@ */
494
495   iter_pydealloc,                       /* @tp_dealloc@ */
496   0,                                    /* @tp_print@ */
497   0,                                    /* @tp_getattr@ */
498   0,                                    /* @tp_setattr@ */
499   0,                                    /* @tp_compare@ */
500   0,                                    /* @tp_repr@ */
501   0,                                    /* @tp_as_number@ */
502   0,                                    /* @tp_as_sequence@ */
503   0,                                    /* @tp_as_mapping@ */
504   0,                                    /* @tp_hash@ */
505   0,                                    /* @tp_call@ */
506   0,                                    /* @tp_str@ */
507   0,                                    /* @tp_getattro@ */
508   0,                                    /* @tp_setattro@ */
509   0,                                    /* @tp_as_buffer@ */
510   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
511     Py_TPFLAGS_BASETYPE,
512
513   /* @tp_doc@ */
514   "Iterates over the items of a mapping.",
515
516   0,                                    /* @tp_traverse@ */
517   0,                                    /* @tp_clear@ */
518   0,                                    /* @tp_richcompare@ */
519   0,                                    /* @tp_weaklistoffset@ */
520   PyObject_SelfIter,                    /* @tp_iter@ */
521   itemiter_pynext,                      /* @tp_iternext@ */
522   0,                                    /* @tp_methods@ */
523   0,                                    /* @tp_members@ */
524   0,                                    /* @tp_getset@ */
525   0,                                    /* @tp_base@ */
526   0,                                    /* @tp_dict@ */
527   0,                                    /* @tp_descr_get@ */
528   0,                                    /* @tp_descr_set@ */
529   0,                                    /* @tp_dictoffset@ */
530   0,                                    /* @tp_init@ */
531   PyType_GenericAlloc,                  /* @tp_alloc@ */
532   abstract_pynew,                       /* @tp_new@ */
533   0,                                    /* @tp_free@ */
534   0                                     /* @tp_is_gc@ */
535 };
536
537 static PyObject *valiter_pynext(PyObject *me)
538 {
539   PyObject *k = 0, *rc = 0;
540
541   if ((k = PyIter_Next(ITER_I(me))) != 0)
542     rc = PyObject_GetItem(ITER_MAP(me), k);
543   Py_XDECREF(k);
544   return (rc);
545 }
546
547 static PyTypeObject valiter_pytype_skel = {
548   PyObject_HEAD_INIT(0) 0,              /* Header */
549   "ValueIter",                          /* @tp_name@ */
550   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
551   0,                                    /* @tp_itemsize@ */
552
553   iter_pydealloc,                       /* @tp_dealloc@ */
554   0,                                    /* @tp_print@ */
555   0,                                    /* @tp_getattr@ */
556   0,                                    /* @tp_setattr@ */
557   0,                                    /* @tp_compare@ */
558   0,                                    /* @tp_repr@ */
559   0,                                    /* @tp_as_number@ */
560   0,                                    /* @tp_as_sequence@ */
561   0,                                    /* @tp_as_mapping@ */
562   0,                                    /* @tp_hash@ */
563   0,                                    /* @tp_call@ */
564   0,                                    /* @tp_str@ */
565   0,                                    /* @tp_getattro@ */
566   0,                                    /* @tp_setattro@ */
567   0,                                    /* @tp_as_buffer@ */
568   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
569     Py_TPFLAGS_BASETYPE,
570
571   /* @tp_doc@ */
572   "Iterates over the values of a mapping.",
573
574   0,                                    /* @tp_traverse@ */
575   0,                                    /* @tp_clear@ */
576   0,                                    /* @tp_richcompare@ */
577   0,                                    /* @tp_weaklistoffset@ */
578   PyObject_SelfIter,                    /* @tp_iter@ */
579   valiter_pynext,                       /* @tp_iternext@ */
580   0,                                    /* @tp_methods@ */
581   0,                                    /* @tp_members@ */
582   0,                                    /* @tp_getset@ */
583   0,                                    /* @tp_base@ */
584   0,                                    /* @tp_dict@ */
585   0,                                    /* @tp_descr_get@ */
586   0,                                    /* @tp_descr_set@ */
587   0,                                    /* @tp_dictoffset@ */
588   0,                                    /* @tp_init@ */
589   PyType_GenericAlloc,                  /* @tp_alloc@ */
590   abstract_pynew,                       /* @tp_new@ */
591   0,                                    /* @tp_free@ */
592   0                                     /* @tp_is_gc@ */
593 };
594
595 PySequenceMethods gmap_pysequence = {
596   0,                                    /* @sq_length@ */
597   0,                                    /* @sq_concat@ */
598   0,                                    /* @sq_repeat@ */
599   0,                                    /* @sq_item@ */
600   0,                                    /* @sq_slice@ */
601   0,                                    /* @sq_ass_item@ */
602   0,                                    /* @sq_ass_slice@ */
603   PyMapping_HasKey,                     /* @sq_contains@ */
604   0,                                    /* @sq_inplace_concat@ */
605   0                                     /* @sq_inplace_repeat@ */
606 };
607
608 Py_ssize_t gmap_pysize(PyObject *me)
609 {
610   PyObject *i = 0, *x = 0;
611   Py_ssize_t rc = -1, n = 0;
612
613   if ((i = PyObject_GetIter(me)) == 0) goto done;
614   while ((x = PyIter_Next(i)) != 0) { n++; Py_DECREF(x); x = 0; }
615   if (PyErr_Occurred()) goto done;
616   rc = n;
617 done:
618   Py_XDECREF(i); Py_XDECREF(x);
619   return (rc);
620 }
621
622 PyObject *gmapmeth_has_key(PyObject *me, PyObject *arg)
623 {
624   PyObject *k;
625   if (!PyArg_ParseTuple(arg, "O:has_key", &k)) return (0);
626   return (getbool(PyMapping_HasKey(me, k)));
627 }
628
629 PyObject *gmapmeth_keys(PyObject *me, PyObject *arg)
630 {
631   PyObject *l = 0, *i = 0, *k, *rc = 0;
632   int err;
633
634   if (!PyArg_ParseTuple(arg, ":keys") ||
635       (l = PyList_New(0)) == 0 ||
636       (i = PyObject_GetIter(me)) == 0)
637     goto done;
638   while ((k = PyIter_Next(i)) != 0)
639     { err = PyList_Append(l, k); Py_DECREF(k); if (err) goto done; }
640   if (PyErr_Occurred()) goto done;
641   rc = l; l = 0;
642 done:
643   Py_XDECREF(l); Py_XDECREF(i);
644   return (rc);
645 }
646
647 PyObject *gmapmeth_values(PyObject *me, PyObject *arg)
648 {
649   PyObject *l = 0, *i = 0, *k, *v, *rc = 0;
650   int err = 0;
651
652   if (!PyArg_ParseTuple(arg, ":values") ||
653       (l = PyList_New(0)) == 0 ||
654       (i = PyObject_GetIter(me)) == 0)
655     goto done;
656   while ((k = PyIter_Next(i)) != 0) {
657     if ((v = PyObject_GetItem(me, k)) == 0 ||
658         PyList_Append(l, v))
659       err = -1;
660     Py_DECREF(k); Py_XDECREF(v);
661     if (err) goto done;
662   }
663   if (PyErr_Occurred()) goto done;
664   rc = l; l = 0;
665 done:
666   Py_XDECREF(l); Py_XDECREF(i);
667   return (rc);
668 }
669
670 PyObject *gmapmeth_items(PyObject *me, PyObject *arg)
671 {
672   PyObject *l = 0, *i = 0, *k, *v, *z, *rc = 0;
673   int err = 0;
674
675   if (!PyArg_ParseTuple(arg, ":items") ||
676       (l = PyList_New(0)) == 0 ||
677       (i = PyObject_GetIter(me)) == 0)
678     goto done;
679   while ((k = PyIter_Next(i)) != 0) {
680     z = 0;
681     if ((v = PyObject_GetItem(me, k)) == 0 ||
682         (z = Py_BuildValue("(OO)", k, v)) == 0 ||
683         PyList_Append(l, z))
684       err = -1;
685     Py_DECREF(k); Py_XDECREF(v); Py_XDECREF(z);
686     if (err) goto done;
687   }
688   if (PyErr_Occurred()) goto done;
689   rc = l; l = 0;
690 done:
691   Py_XDECREF(l); Py_XDECREF(i);
692   return (rc);
693 }
694
695 PyObject *gmapmeth_iterkeys(PyObject *me, PyObject *arg)
696 {
697   if (!PyArg_ParseTuple(arg, ":iterkeys")) return (0);
698   return (PyObject_GetIter(me));
699 }
700
701 PyObject *gmapmeth_itervalues(PyObject *me, PyObject *arg)
702 {
703   PyObject *i;
704   iter_pyobj *ii;
705
706   if (!PyArg_ParseTuple(arg, ":itervalues") ||
707       (i = PyObject_GetIter(me)) == 0)
708     return (0);
709   ii = PyObject_NEW(iter_pyobj, valiter_pytype);
710   ii->map = me; Py_INCREF(me);
711   ii->i = i;
712   return ((PyObject *)ii);
713 }
714
715 PyObject *gmapmeth_iteritems(PyObject *me, PyObject *arg)
716 {
717   PyObject *i;
718   iter_pyobj *ii;
719
720   if (!PyArg_ParseTuple(arg, ":iteritems") ||
721       (i = PyObject_GetIter(me)) == 0)
722     return (0);
723   ii = PyObject_NEW(iter_pyobj, itemiter_pytype);
724   ii->map = me; Py_INCREF(me);
725   ii->i = i;
726   return ((PyObject *)ii);
727 }
728
729 PyObject *gmapmeth_clear(PyObject *me, PyObject *arg)
730 {
731   PyObject *i = 0, *k = 0, *rc = 0;
732
733   if (!PyArg_ParseTuple(arg, ":clear") ||
734       (i = PyObject_GetIter(me)) == 0)
735     goto end;
736   while ((k = PyIter_Next(i)) != 0) {
737     PyObject_DelItem(me, k);
738     Py_DECREF(k);
739   }
740   if (PyErr_Occurred()) goto end;
741   rc = me; Py_INCREF(me);
742 end:
743   Py_XDECREF(i);
744   return (rc);
745 }
746
747 static const char *const def_kwlist[] = { "key", "default", 0 };
748
749 PyObject *gmapmeth_get(PyObject *me, PyObject *arg, PyObject *kw)
750 {
751   PyObject *k, *def = Py_None, *v;
752
753   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|O:get",
754                                    (/*unconst*/ char **)def_kwlist,
755                                    &k, &def))
756     return (0);
757   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
758   PyErr_Clear();
759   RETURN_OBJ(def);
760 }
761
762 PyObject *gmapmeth_setdefault(PyObject *me, PyObject *arg, PyObject *kw)
763 {
764   PyObject *k, *def = Py_None, *v;
765
766   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|O:setdefault",
767                                    (/*unconst*/ char **)def_kwlist,
768                                    &k, &def))
769     return (0);
770   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
771   PyErr_Clear();
772   if (PyObject_SetItem(me, k, def)) return (0);
773   RETURN_OBJ(def);
774 }
775
776 PyObject *gmapmeth_pop(PyObject *me, PyObject *arg, PyObject *kw)
777 {
778   PyObject *k, *def = 0, *v;
779
780   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|O:pop",
781                                    (/*unconst*/ char **)def_kwlist,
782                                    &k, &def))
783     return (0);
784   if ((v = PyObject_GetItem(me, k)) != 0) {
785     PyObject_DelItem(me, k);
786     return (v);
787   } else if (def) {
788     PyErr_Clear();
789     RETURN_OBJ(def);
790   } else
791     return (0);
792 }
793
794 PyObject *gmapmeth_update(PyObject *me, PyObject *arg)
795 {
796   PyObject *map, *i = 0, *k, *v, *rc = 0;
797   int err = 0;
798
799   if (!PyArg_ParseTuple(arg, "O:update", &map) ||
800       (i = PyObject_GetIter(map)) == 0)
801     goto end;
802   while ((k = PyIter_Next(i)) != 0) {
803     if ((v = PyObject_GetItem(map, k)) == 0 ||
804         PyObject_SetItem(me, k, v))
805       err = -1;
806     Py_DECREF(k); Py_XDECREF(v);
807     if (err) goto end;
808   }
809   if (PyErr_Occurred()) goto end;
810   rc = me; Py_INCREF(me);
811 end:
812   Py_XDECREF(i);
813   return (rc);
814 }
815
816 PyObject *gmapmeth_popitem(PyObject *me, PyObject *arg)
817 {
818   PyObject *i = 0, *k = 0, *v = 0, *rc = 0;
819
820   if (!PyArg_ParseTuple(arg, ":popitem") ||
821       (i = PyObject_GetIter(me)) == 0)
822     goto end;
823   if ((k = PyIter_Next(i)) == 0) {
824     if (!PyErr_Occurred()) VALERR("popitem(): mapping is empty");
825     goto end;
826   }
827   if ((v = PyObject_GetItem(me, k)) == 0 ||
828       PyObject_DelItem(me, k))
829     goto end;
830   rc = Py_BuildValue("(OO)", k, v);
831 end:
832   Py_XDECREF(i); Py_XDECREF(k); Py_XDECREF(v);
833   return (rc);
834 }
835
836 PyMethodDef gmap_pymethods[] = {
837   GMAP_METHODS
838   { 0 }
839 };
840
841 /*----- Initialization ----------------------------------------------------*/
842
843 static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
844 {
845   PyObject *mod;
846
847   if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
848     return (0);
849   Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
850   RETURN_NONE;
851 }
852
853 static const PyMethodDef methods[] = {
854 #define METHNAME(func) meth_##func
855   METH  (_set_home_module, "_set_home_module(MOD)")
856 #undef METHNAME
857   { 0 }
858 };
859
860 void util_pyinit(void)
861 {
862   INITTYPE(itemiter, root);
863   INITTYPE(valiter, root);
864   addmethods(methods);
865 }
866
867 void util_pyinsert(PyObject *mod)
868 {
869   INSERT("ItemIter", itemiter_pytype);
870   INSERT("ValueIter", valiter_pytype);
871 }
872
873 /*----- That's all, folks -------------------------------------------------*/