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