chiark / gitweb /
Overhaul formatting.
[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 /*----- Conversions -------------------------------------------------------*/
32
33 PyObject *getulong(unsigned long w)
34 {
35   if (w <= LONG_MAX)
36     return (PyInt_FromLong(w));
37   else
38     return (PyLong_FromUnsignedLong(w));
39 }
40
41 PyObject *getbool(int b)
42 {
43   if (b) RETURN_TRUE;
44   else RETURN_FALSE;
45 }
46
47 PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
48 {
49   PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
50   return (0);
51 }
52
53 int convulong(PyObject *o, void *pp)
54 {
55   long i;
56   unsigned long *p = pp;
57   PyObject *t;
58
59   if (PyInt_Check(o)) {
60     i = PyInt_AS_LONG(o);
61     if (i < 0) VALERR("must be nonnegative");
62     *p = i;
63   } else {
64     if ((t = PyNumber_Long(o)) == 0) goto end;
65     *p = PyLong_AsUnsignedLong(t);
66     Py_DECREF(t);
67     if (PyErr_Occurred()) goto end;
68   }
69   return (1);
70 end:
71   return (0);
72 }
73
74 #define CONVU_(n)                                                       \
75   int convu##n(PyObject *o, void *pp)                                   \
76   {                                                                     \
77     unsigned long u;                                                    \
78     uint##n *p = pp;                                                    \
79                                                                         \
80     if (!convulong(o, &u)) goto end;                                    \
81     if (u > MASK##n) VALERR("out of range");                            \
82     *p = u;                                                             \
83     return (1);                                                         \
84   end:                                                                  \
85     return (0);                                                         \
86   }
87 DOUINTSZ(CONVU_)
88
89 int convuint(PyObject *o, void *pp)
90 {
91   unsigned long u;
92   unsigned *p = pp;
93
94   if (!convulong(o, &u)) goto end;
95   if (u > UINT_MAX) VALERR("out of range");
96   *p = u;
97   return (1);
98 end:
99   return (0);
100 }
101
102 int convmpw(PyObject *o, void *pp)
103 {
104   unsigned long u;
105   unsigned *p = pp;
106
107   if (!convulong(o, &u)) goto end;
108   if (u > MPW_MAX) VALERR("out of range");
109   *p = u;
110   return (1);
111 end:
112   return (0);
113 }
114
115 int convszt(PyObject *o, void *pp)
116 {
117   unsigned long u;
118   size_t *p = pp;
119
120   if (!convulong(o, &u)) goto end;
121   if (u > ~(size_t)0) VALERR("out of range");
122   *p = u;
123   return (1);
124 end:
125   return (0);
126 }
127
128 int convbool(PyObject *o, void *pp)
129 {
130   *(int *)pp = PyObject_IsTrue(o);
131   return (1);
132 }
133
134 /*----- Type messing ------------------------------------------------------*/
135
136 static const PyTypeObject emptytype = { 0 };
137
138 void *newtype(PyTypeObject *metaty,
139               const PyTypeObject *skel,
140               const char *name)
141 {
142   PyHeapTypeObject *ty =
143     (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
144   if (!skel) skel = &emptytype;
145   memcpy(ty, skel, sizeof(*skel));
146   if (ty->ht_type.tp_base) Py_INCREF(ty->ht_type.tp_base);
147 #define COPY(blah) do {                                                 \
148     if (ty->ht_type.tp_as_##blah) {                                     \
149       memcpy(&ty->as_##blah,                                            \
150              ty->ht_type.tp_as_##blah,                                  \
151              sizeof(ty->as_##blah));                                    \
152       ty->ht_type.tp_as_##blah = &ty->as_##blah;                        \
153     }                                                                   \
154   } while (0)
155   COPY(number);
156   COPY(sequence);
157   COPY(mapping);
158   COPY(buffer);
159 #undef COPY
160   if (name)
161     ty->ht_name = PyString_FromString(name);
162   else if (ty->ht_type.tp_name)
163     ty->ht_name = PyString_FromString(ty->ht_type.tp_name);
164   if (ty->ht_name)
165     ty->ht_type.tp_name = PyString_AS_STRING(ty->ht_name);
166   PyObject_INIT(&ty->ht_type, metaty);
167   Py_INCREF(metaty);
168   return (ty);
169 }
170
171 PyTypeObject *inittype(PyTypeObject *tyskel)
172 {
173   PyTypeObject *ty = newtype(&PyType_Type, tyskel, 0);
174   ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
175   PyType_Ready(ty);
176   return (ty);
177 }
178
179 /*----- Constants ---------------------------------------------------------*/
180
181 void setconstants(PyObject *mod, const struct nameval *c)
182 {
183   PyObject *x;
184
185   while (c->name) {
186     if (c->value > LONG_MAX)
187       x = PyLong_FromUnsignedLong(c->value);
188     else
189       x = PyInt_FromLong(c->value);
190     PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
191     c++;
192   }
193 }
194
195 /*----- Building method tables --------------------------------------------*/
196
197 DA_DECL(method_v, PyMethodDef);
198 static method_v global_pymethods = DA_INIT;
199 void addmethods(const PyMethodDef *m)
200 {
201   size_t n;
202
203   for (n = 0; m[n].ml_name; n++);
204   DA_ENSURE(&global_pymethods, n);
205   memcpy(DA(&global_pymethods) + DA_LEN(&global_pymethods),
206          m, n * sizeof(*m));
207   DA_EXTEND(&global_pymethods, n);
208 }
209
210 PyMethodDef *donemethods(void)
211 {
212   static const PyMethodDef mzero = { 0 };
213   DA_PUSH(&global_pymethods, mzero);
214   return (DA(&global_pymethods));
215 }
216
217 /*----- Exceptions --------------------------------------------------------*/
218
219 PyObject * mkexc(PyObject *mod, PyObject *base,
220                  const char *name, PyMethodDef *mm)
221 {
222   PyObject *nameobj = 0;
223   PyObject *dict = 0;
224   PyObject *exc = 0;
225   PyObject *func = 0;
226   PyObject *meth = 0;
227
228   if ((nameobj = PyString_FromFormat("%s.%s",
229                                      PyModule_GetName(mod),
230                                      name)) == 0 ||
231       (dict = PyDict_New()) == 0 ||
232       (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
233                                 base, dict)) == 0)
234     goto fail;
235
236   if (mm) {
237     while (mm->ml_name) {
238       if ((func = PyCFunction_NewEx(mm, 0, mod)) == 0 ||
239           (meth = PyMethod_New(func, 0, exc)) == 0 ||
240           PyDict_SetItemString(dict, mm->ml_name, meth))
241         goto fail;
242       Py_DECREF(func); func = 0;
243       Py_DECREF(meth); meth = 0;
244       mm++;
245     }
246   }
247
248 done:
249   Py_XDECREF(nameobj);
250   Py_XDECREF(dict);
251   return (exc);
252
253 fail:
254   Py_XDECREF(exc);
255   Py_XDECREF(func);
256   Py_XDECREF(meth);
257   exc = 0;
258   goto done;
259 }
260
261 /*----- Generic dictionary methods ----------------------------------------*/
262
263 static PyTypeObject *itemiter_pytype, *valiter_pytype;
264
265 typedef struct iter_pyobj {
266   PyObject_HEAD
267   PyObject *map;
268   PyObject *i;
269 } iter_pyobj;
270 #define ITER_MAP(o) (((iter_pyobj *)(o))->map)
271 #define ITER_I(o) (((iter_pyobj *)(o))->i)
272
273 static void iter_pydealloc(PyObject *me)
274   { Py_DECREF(ITER_MAP(me)); Py_DECREF(ITER_I(me)); FREEOBJ(me); }
275
276 static PyObject *itemiter_pynext(PyObject *me)
277 {
278   PyObject *k = 0, *v = 0, *rc = 0;
279
280   if ((k = PyIter_Next(ITER_I(me))) != 0 &&
281       (v = PyObject_GetItem(ITER_MAP(me), k)) != 0)
282     rc = Py_BuildValue("(OO)", k, v);
283   Py_XDECREF(k); Py_XDECREF(v);
284   return (rc);
285 }
286
287 static PyTypeObject itemiter_pytype_skel = {
288   PyObject_HEAD_INIT(0) 0,              /* Header */
289   "ItemIter",                           /* @tp_name@ */
290   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
291   0,                                    /* @tp_itemsize@ */
292
293   iter_pydealloc,                       /* @tp_dealloc@ */
294   0,                                    /* @tp_print@ */
295   0,                                    /* @tp_getattr@ */
296   0,                                    /* @tp_setattr@ */
297   0,                                    /* @tp_compare@ */
298   0,                                    /* @tp_repr@ */
299   0,                                    /* @tp_as_number@ */
300   0,                                    /* @tp_as_sequence@ */
301   0,                                    /* @tp_as_mapping@ */
302   0,                                    /* @tp_hash@ */
303   0,                                    /* @tp_call@ */
304   0,                                    /* @tp_str@ */
305   0,                                    /* @tp_getattro@ */
306   0,                                    /* @tp_setattro@ */
307   0,                                    /* @tp_as_buffer@ */
308   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
309     Py_TPFLAGS_BASETYPE,
310
311   /* @tp_doc@ */
312 "Iterates over the items of a mapping.",
313
314   0,                                    /* @tp_traverse@ */
315   0,                                    /* @tp_clear@ */
316   0,                                    /* @tp_richcompare@ */
317   0,                                    /* @tp_weaklistoffset@ */
318   PyObject_SelfIter,                    /* @tp_iter@ */
319   itemiter_pynext,                      /* @tp_iternext@ */
320   0,                                    /* @tp_methods@ */
321   0,                                    /* @tp_members@ */
322   0,                                    /* @tp_getset@ */
323   0,                                    /* @tp_base@ */
324   0,                                    /* @tp_dict@ */
325   0,                                    /* @tp_descr_get@ */
326   0,                                    /* @tp_descr_set@ */
327   0,                                    /* @tp_dictoffset@ */
328   0,                                    /* @tp_init@ */
329   PyType_GenericAlloc,                  /* @tp_alloc@ */
330   abstract_pynew,                       /* @tp_new@ */
331   0,                                    /* @tp_free@ */
332   0                                     /* @tp_is_gc@ */
333 };
334
335 static PyObject *valiter_pynext(PyObject *me)
336 {
337   PyObject *k = 0, *rc = 0;
338
339   if ((k = PyIter_Next(ITER_I(me))) != 0)
340     rc = PyObject_GetItem(ITER_MAP(me), k);
341   Py_XDECREF(k);
342   return (rc);
343 }
344
345 static PyTypeObject valiter_pytype_skel = {
346   PyObject_HEAD_INIT(0) 0,              /* Header */
347   "ValueIter",                          /* @tp_name@ */
348   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
349   0,                                    /* @tp_itemsize@ */
350
351   iter_pydealloc,                       /* @tp_dealloc@ */
352   0,                                    /* @tp_print@ */
353   0,                                    /* @tp_getattr@ */
354   0,                                    /* @tp_setattr@ */
355   0,                                    /* @tp_compare@ */
356   0,                                    /* @tp_repr@ */
357   0,                                    /* @tp_as_number@ */
358   0,                                    /* @tp_as_sequence@ */
359   0,                                    /* @tp_as_mapping@ */
360   0,                                    /* @tp_hash@ */
361   0,                                    /* @tp_call@ */
362   0,                                    /* @tp_str@ */
363   0,                                    /* @tp_getattro@ */
364   0,                                    /* @tp_setattro@ */
365   0,                                    /* @tp_as_buffer@ */
366   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
367     Py_TPFLAGS_BASETYPE,
368
369   /* @tp_doc@ */
370 "Iterates over the items of a mapping.",
371
372   0,                                    /* @tp_traverse@ */
373   0,                                    /* @tp_clear@ */
374   0,                                    /* @tp_richcompare@ */
375   0,                                    /* @tp_weaklistoffset@ */
376   PyObject_SelfIter,                    /* @tp_iter@ */
377   valiter_pynext,                       /* @tp_iternext@ */
378   0,                                    /* @tp_methods@ */
379   0,                                    /* @tp_members@ */
380   0,                                    /* @tp_getset@ */
381   0,                                    /* @tp_base@ */
382   0,                                    /* @tp_dict@ */
383   0,                                    /* @tp_descr_get@ */
384   0,                                    /* @tp_descr_set@ */
385   0,                                    /* @tp_dictoffset@ */
386   0,                                    /* @tp_init@ */
387   PyType_GenericAlloc,                  /* @tp_alloc@ */
388   abstract_pynew,                       /* @tp_new@ */
389   0,                                    /* @tp_free@ */
390   0                                     /* @tp_is_gc@ */
391 };
392
393 PySequenceMethods gmap_pysequence = {
394   0,                                    /* @sq_length@ */
395   0,                                    /* @sq_concat@ */
396   0,                                    /* @sq_repeat@ */
397   0,                                    /* @sq_item@ */
398   0,                                    /* @sq_slice@ */
399   0,                                    /* @sq_ass_item@ */
400   0,                                    /* @sq_ass_slice@ */
401   PyMapping_HasKey,                     /* @sq_contains@ */
402   0,                                    /* @sq_inplace_concat@ */
403   0                                     /* @sq_inplace_repeat@ */
404 };
405
406 int gmap_pysize(PyObject *me)
407 {
408   PyObject *i = 0, *x = 0;
409   int rc = -1;
410   int n = 0;
411
412   if ((i = PyObject_GetIter(me)) == 0) goto done;
413   while ((x = PyIter_Next(i)) != 0) { n++; Py_DECREF(x); x = 0; }
414   if (PyErr_Occurred()) goto done;
415   rc = n;
416 done:
417   Py_XDECREF(i); Py_XDECREF(x);
418   return (rc);
419 }
420
421 PyObject *gmapmeth_has_key(PyObject *me, PyObject *arg)
422 {
423   PyObject *k;
424   if (!PyArg_ParseTuple(arg, "O:has_key", &k)) return (0);
425   return (getbool(PyMapping_HasKey(me, k)));
426 }
427
428 PyObject *gmapmeth_keys(PyObject *me, PyObject *arg)
429 {
430   PyObject *l = 0, *i = 0, *k, *rc = 0;
431   int err;
432
433   if (!PyArg_ParseTuple(arg, ":keys") ||
434       (l = PyList_New(0)) == 0 ||
435       (i = PyObject_GetIter(me)) == 0)
436     goto done;
437   while ((k = PyIter_Next(i)) != 0)
438     { err = PyList_Append(l, k); Py_DECREF(k); if (err) goto done; }
439   if (PyErr_Occurred()) goto done;
440   rc = l; l = 0;
441 done:
442   Py_XDECREF(l); Py_XDECREF(i);
443   return (rc);
444 }
445
446 PyObject *gmapmeth_values(PyObject *me, PyObject *arg)
447 {
448   PyObject *l = 0, *i = 0, *k, *v, *rc = 0;
449   int err = 0;
450
451   if (!PyArg_ParseTuple(arg, ":values") ||
452       (l = PyList_New(0)) == 0 ||
453       (i = PyObject_GetIter(me)) == 0)
454     goto done;
455   while ((k = PyIter_Next(i)) != 0) {
456     if ((v = PyObject_GetItem(me, k)) == 0 ||
457         PyList_Append(l, v))
458       err = -1;
459     Py_DECREF(k); Py_XDECREF(v);
460     if (err) goto done;
461   }
462   if (PyErr_Occurred()) goto done;
463   rc = l; l = 0;
464 done:
465   Py_XDECREF(l); Py_XDECREF(i);
466   return (rc);
467 }
468
469 PyObject *gmapmeth_items(PyObject *me, PyObject *arg)
470 {
471   PyObject *l = 0, *i = 0, *k, *v, *z, *rc = 0;
472   int err = 0;
473
474   if (!PyArg_ParseTuple(arg, ":items") ||
475       (l = PyList_New(0)) == 0 ||
476       (i = PyObject_GetIter(me)) == 0)
477     goto done;
478   while ((k = PyIter_Next(i)) != 0) {
479     z = 0;
480     if ((v = PyObject_GetItem(me, k)) == 0 ||
481         (z = Py_BuildValue("(OO)", k, v)) == 0 ||
482         PyList_Append(l, z))
483       err = -1;
484     Py_DECREF(k); Py_XDECREF(v); Py_XDECREF(z);
485     if (err) goto done;
486   }
487   if (PyErr_Occurred()) goto done;
488   rc = l; l = 0;
489 done:
490   Py_XDECREF(l); Py_XDECREF(i);
491   return (rc);
492 }
493
494 PyObject *gmapmeth_iterkeys(PyObject *me, PyObject *arg)
495 {
496   if (!PyArg_ParseTuple(arg, ":iterkeys")) return (0);
497   return (PyObject_GetIter(me));
498 }
499
500 PyObject *gmapmeth_itervalues(PyObject *me, PyObject *arg)
501 {
502   PyObject *i;
503   iter_pyobj *ii;
504
505   if (!PyArg_ParseTuple(arg, ":itervalues") ||
506       (i = PyObject_GetIter(me)) == 0)
507     return (0);
508   ii = PyObject_NEW(iter_pyobj, valiter_pytype);
509   ii->map = me; Py_INCREF(me);
510   ii->i = i;
511   return ((PyObject *)ii);
512 }
513
514 PyObject *gmapmeth_iteritems(PyObject *me, PyObject *arg)
515 {
516   PyObject *i;
517   iter_pyobj *ii;
518
519   if (!PyArg_ParseTuple(arg, ":iteritems") ||
520       (i = PyObject_GetIter(me)) == 0)
521     return (0);
522   ii = PyObject_NEW(iter_pyobj, itemiter_pytype);
523   ii->map = me; Py_INCREF(me);
524   ii->i = i;
525   return ((PyObject *)ii);
526 }
527
528 PyObject *gmapmeth_clear(PyObject *me, PyObject *arg)
529 {
530   PyObject *i = 0, *k = 0, *rc = 0;
531
532   if (!PyArg_ParseTuple(arg, ":clear") ||
533       (i = PyObject_GetIter(me)) == 0)
534     goto end;
535   while ((k = PyIter_Next(i)) != 0) {
536     PyObject_DelItem(me, k);
537     Py_DECREF(k);
538   }
539   if (PyErr_Occurred()) goto end;
540   rc = me; Py_INCREF(me);
541 end:
542   Py_XDECREF(i);
543   return (rc);
544 }
545
546 static char *def_kwlist[] = { "key", "default", 0 };
547
548 PyObject *gmapmeth_get(PyObject *me, PyObject *arg, PyObject *kw)
549 {
550   PyObject *k, *def = Py_None, *v;
551
552   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:get", def_kwlist, &k, &def))
553     return (0);
554   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
555   PyErr_Clear();
556   RETURN_OBJ(def);
557 }
558
559 PyObject *gmapmeth_setdefault(PyObject *me, PyObject *arg, PyObject *kw)
560 {
561   PyObject *k, *def = Py_None, *v;
562
563   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:setdefault",
564                                    def_kwlist, &k, &def))
565     return (0);
566   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
567   PyErr_Clear();
568   if (PyObject_SetItem(me, k, def)) return (0);
569   RETURN_OBJ(def);
570 }
571
572 PyObject *gmapmeth_pop(PyObject *me, PyObject *arg, PyObject *kw)
573 {
574   PyObject *k, *def = 0, *v;
575
576   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:pop", def_kwlist, &k, &def))
577     return (0);
578   if ((v = PyObject_GetItem(me, k)) != 0) {
579     PyObject_DelItem(me, k);
580     return (v);
581   }
582   PyErr_Clear();
583   RETURN_OBJ(def);
584 }
585
586 PyObject *gmapmeth_update(PyObject *me, PyObject *arg)
587 {
588   PyObject *map, *i = 0, *k, *v, *rc = 0;
589   int err = 0;
590
591   if (!PyArg_ParseTuple(arg, "O:update", &map) ||
592       (i = PyObject_GetIter(map)) == 0)
593     goto end;
594   while ((k = PyIter_Next(i)) != 0) {
595     if ((v = PyObject_GetItem(map, k)) == 0 ||
596         PyObject_SetItem(me, k, v))
597       err = -1;
598     Py_DECREF(k); Py_XDECREF(v);
599     if (err) goto end;
600   }
601   if (PyErr_Occurred()) goto end;
602   rc = me; Py_INCREF(me);
603 end:
604   Py_XDECREF(i);
605   return (rc);
606 }
607
608 PyObject *gmapmeth_popitem(PyObject *me, PyObject *arg)
609 {
610   PyObject *i = 0, *k = 0, *v = 0, *rc = 0;
611
612   if (!PyArg_ParseTuple(arg, ":popitem") ||
613       (i = PyObject_GetIter(me)))
614     goto end;
615   if ((k = PyIter_Next(i)) == 0) {
616     if (!PyErr_Occurred()) VALERR("popitem(): mapping is empty");
617     goto end;
618   }
619   if ((v = PyObject_GetItem(me, k)) == 0 ||
620       PyObject_DelItem(me, k))
621     goto end;
622   rc = Py_BuildValue("(OO)", k, v);
623 end:
624   Py_XDECREF(i); Py_XDECREF(k); Py_XDECREF(v);
625   return (rc);
626 }
627
628 PyMethodDef gmap_pymethods[] = {
629   GMAP_METHODS
630   { 0 }
631 };
632
633 /*----- Initialization ----------------------------------------------------*/
634
635 void util_pyinit(void)
636 {
637   INITTYPE(itemiter, root);
638   INITTYPE(valiter, root);
639 }
640
641 void util_pyinsert(PyObject *mod)
642 {
643   INSERT("ItemIter", itemiter_pytype);
644   INSERT("ValueIter", valiter_pytype);
645 }
646
647 /*----- That's all, folks -------------------------------------------------*/