chiark / gitweb /
Stamp the module name onto types properly.
[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 /*----- 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   DISCARD(PyObject_INIT(&ty->ht_type, metaty));
167   Py_INCREF(metaty);
168   return (ty);
169 }
170
171 PyTypeObject *inittype(PyTypeObject *tyskel)
172 {
173   static PyObject *modname = 0;
174   PyTypeObject *ty = newtype(&PyType_Type, tyskel, 0);
175   if (!modname) modname = PyString_FromString("catacomb");
176   ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
177   PyType_Ready(ty);
178   PyDict_SetItemString(ty->tp_dict, "__module__", modname);
179   return (ty);
180 }
181
182 /*----- Constants ---------------------------------------------------------*/
183
184 void setconstants(PyObject *mod, const struct nameval *c)
185 {
186   PyObject *x;
187
188   while (c->name) {
189     if (c->value > LONG_MAX)
190       x = PyLong_FromUnsignedLong(c->value);
191     else
192       x = PyInt_FromLong(c->value);
193     PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
194     c++;
195   }
196 }
197
198 /*----- Building method tables --------------------------------------------*/
199
200 DA_DECL(method_v, PyMethodDef);
201 static method_v global_pymethods = DA_INIT;
202 void addmethods(const PyMethodDef *m)
203 {
204   size_t n;
205
206   for (n = 0; m[n].ml_name; n++);
207   DA_ENSURE(&global_pymethods, n);
208   memcpy(DA(&global_pymethods) + DA_LEN(&global_pymethods),
209          m, n * sizeof(*m));
210   DA_EXTEND(&global_pymethods, n);
211 }
212
213 PyMethodDef *donemethods(void)
214 {
215   static const PyMethodDef mzero = { 0 };
216   DA_PUSH(&global_pymethods, mzero);
217   return (DA(&global_pymethods));
218 }
219
220 /*----- Exceptions --------------------------------------------------------*/
221
222 PyObject * mkexc(PyObject *mod, PyObject *base,
223                  const char *name, PyMethodDef *mm)
224 {
225   PyObject *nameobj = 0;
226   PyObject *dict = 0;
227   PyObject *exc = 0;
228   PyObject *func = 0;
229   PyObject *meth = 0;
230
231   if ((nameobj = PyString_FromFormat("%s.%s",
232                                      PyModule_GetName(mod),
233                                      name)) == 0 ||
234       (dict = PyDict_New()) == 0 ||
235       (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
236                                 base, dict)) == 0)
237     goto fail;
238
239   if (mm) {
240     while (mm->ml_name) {
241       if ((func = PyCFunction_NewEx(mm, 0, mod)) == 0 ||
242           (meth = PyMethod_New(func, 0, exc)) == 0 ||
243           PyDict_SetItemString(dict, mm->ml_name, meth))
244         goto fail;
245       Py_DECREF(func); func = 0;
246       Py_DECREF(meth); meth = 0;
247       mm++;
248     }
249   }
250
251 done:
252   Py_XDECREF(nameobj);
253   Py_XDECREF(dict);
254   return (exc);
255
256 fail:
257   Py_XDECREF(exc);
258   Py_XDECREF(func);
259   Py_XDECREF(meth);
260   exc = 0;
261   goto done;
262 }
263
264 /*----- Generic dictionary methods ----------------------------------------*/
265
266 static PyTypeObject *itemiter_pytype, *valiter_pytype;
267
268 typedef struct iter_pyobj {
269   PyObject_HEAD
270   PyObject *map;
271   PyObject *i;
272 } iter_pyobj;
273 #define ITER_MAP(o) (((iter_pyobj *)(o))->map)
274 #define ITER_I(o) (((iter_pyobj *)(o))->i)
275
276 static void iter_pydealloc(PyObject *me)
277   { Py_DECREF(ITER_MAP(me)); Py_DECREF(ITER_I(me)); FREEOBJ(me); }
278
279 static PyObject *itemiter_pynext(PyObject *me)
280 {
281   PyObject *k = 0, *v = 0, *rc = 0;
282
283   if ((k = PyIter_Next(ITER_I(me))) != 0 &&
284       (v = PyObject_GetItem(ITER_MAP(me), k)) != 0)
285     rc = Py_BuildValue("(OO)", k, v);
286   Py_XDECREF(k); Py_XDECREF(v);
287   return (rc);
288 }
289
290 static PyTypeObject itemiter_pytype_skel = {
291   PyObject_HEAD_INIT(0) 0,              /* Header */
292   "ItemIter",                           /* @tp_name@ */
293   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
294   0,                                    /* @tp_itemsize@ */
295
296   iter_pydealloc,                       /* @tp_dealloc@ */
297   0,                                    /* @tp_print@ */
298   0,                                    /* @tp_getattr@ */
299   0,                                    /* @tp_setattr@ */
300   0,                                    /* @tp_compare@ */
301   0,                                    /* @tp_repr@ */
302   0,                                    /* @tp_as_number@ */
303   0,                                    /* @tp_as_sequence@ */
304   0,                                    /* @tp_as_mapping@ */
305   0,                                    /* @tp_hash@ */
306   0,                                    /* @tp_call@ */
307   0,                                    /* @tp_str@ */
308   0,                                    /* @tp_getattro@ */
309   0,                                    /* @tp_setattro@ */
310   0,                                    /* @tp_as_buffer@ */
311   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
312     Py_TPFLAGS_BASETYPE,
313
314   /* @tp_doc@ */
315 "Iterates over the items of a mapping.",
316
317   0,                                    /* @tp_traverse@ */
318   0,                                    /* @tp_clear@ */
319   0,                                    /* @tp_richcompare@ */
320   0,                                    /* @tp_weaklistoffset@ */
321   PyObject_SelfIter,                    /* @tp_iter@ */
322   itemiter_pynext,                      /* @tp_iternext@ */
323   0,                                    /* @tp_methods@ */
324   0,                                    /* @tp_members@ */
325   0,                                    /* @tp_getset@ */
326   0,                                    /* @tp_base@ */
327   0,                                    /* @tp_dict@ */
328   0,                                    /* @tp_descr_get@ */
329   0,                                    /* @tp_descr_set@ */
330   0,                                    /* @tp_dictoffset@ */
331   0,                                    /* @tp_init@ */
332   PyType_GenericAlloc,                  /* @tp_alloc@ */
333   abstract_pynew,                       /* @tp_new@ */
334   0,                                    /* @tp_free@ */
335   0                                     /* @tp_is_gc@ */
336 };
337
338 static PyObject *valiter_pynext(PyObject *me)
339 {
340   PyObject *k = 0, *rc = 0;
341
342   if ((k = PyIter_Next(ITER_I(me))) != 0)
343     rc = PyObject_GetItem(ITER_MAP(me), k);
344   Py_XDECREF(k);
345   return (rc);
346 }
347
348 static PyTypeObject valiter_pytype_skel = {
349   PyObject_HEAD_INIT(0) 0,              /* Header */
350   "ValueIter",                          /* @tp_name@ */
351   sizeof(iter_pyobj),                   /* @tp_basicsize@ */
352   0,                                    /* @tp_itemsize@ */
353
354   iter_pydealloc,                       /* @tp_dealloc@ */
355   0,                                    /* @tp_print@ */
356   0,                                    /* @tp_getattr@ */
357   0,                                    /* @tp_setattr@ */
358   0,                                    /* @tp_compare@ */
359   0,                                    /* @tp_repr@ */
360   0,                                    /* @tp_as_number@ */
361   0,                                    /* @tp_as_sequence@ */
362   0,                                    /* @tp_as_mapping@ */
363   0,                                    /* @tp_hash@ */
364   0,                                    /* @tp_call@ */
365   0,                                    /* @tp_str@ */
366   0,                                    /* @tp_getattro@ */
367   0,                                    /* @tp_setattro@ */
368   0,                                    /* @tp_as_buffer@ */
369   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
370     Py_TPFLAGS_BASETYPE,
371
372   /* @tp_doc@ */
373 "Iterates over the items of a mapping.",
374
375   0,                                    /* @tp_traverse@ */
376   0,                                    /* @tp_clear@ */
377   0,                                    /* @tp_richcompare@ */
378   0,                                    /* @tp_weaklistoffset@ */
379   PyObject_SelfIter,                    /* @tp_iter@ */
380   valiter_pynext,                       /* @tp_iternext@ */
381   0,                                    /* @tp_methods@ */
382   0,                                    /* @tp_members@ */
383   0,                                    /* @tp_getset@ */
384   0,                                    /* @tp_base@ */
385   0,                                    /* @tp_dict@ */
386   0,                                    /* @tp_descr_get@ */
387   0,                                    /* @tp_descr_set@ */
388   0,                                    /* @tp_dictoffset@ */
389   0,                                    /* @tp_init@ */
390   PyType_GenericAlloc,                  /* @tp_alloc@ */
391   abstract_pynew,                       /* @tp_new@ */
392   0,                                    /* @tp_free@ */
393   0                                     /* @tp_is_gc@ */
394 };
395
396 PySequenceMethods gmap_pysequence = {
397   0,                                    /* @sq_length@ */
398   0,                                    /* @sq_concat@ */
399   0,                                    /* @sq_repeat@ */
400   0,                                    /* @sq_item@ */
401   0,                                    /* @sq_slice@ */
402   0,                                    /* @sq_ass_item@ */
403   0,                                    /* @sq_ass_slice@ */
404   PyMapping_HasKey,                     /* @sq_contains@ */
405   0,                                    /* @sq_inplace_concat@ */
406   0                                     /* @sq_inplace_repeat@ */
407 };
408
409 int gmap_pysize(PyObject *me)
410 {
411   PyObject *i = 0, *x = 0;
412   int rc = -1;
413   int n = 0;
414
415   if ((i = PyObject_GetIter(me)) == 0) goto done;
416   while ((x = PyIter_Next(i)) != 0) { n++; Py_DECREF(x); x = 0; }
417   if (PyErr_Occurred()) goto done;
418   rc = n;
419 done:
420   Py_XDECREF(i); Py_XDECREF(x);
421   return (rc);
422 }
423
424 PyObject *gmapmeth_has_key(PyObject *me, PyObject *arg)
425 {
426   PyObject *k;
427   if (!PyArg_ParseTuple(arg, "O:has_key", &k)) return (0);
428   return (getbool(PyMapping_HasKey(me, k)));
429 }
430
431 PyObject *gmapmeth_keys(PyObject *me, PyObject *arg)
432 {
433   PyObject *l = 0, *i = 0, *k, *rc = 0;
434   int err;
435
436   if (!PyArg_ParseTuple(arg, ":keys") ||
437       (l = PyList_New(0)) == 0 ||
438       (i = PyObject_GetIter(me)) == 0)
439     goto done;
440   while ((k = PyIter_Next(i)) != 0)
441     { err = PyList_Append(l, k); Py_DECREF(k); if (err) goto done; }
442   if (PyErr_Occurred()) goto done;
443   rc = l; l = 0;
444 done:
445   Py_XDECREF(l); Py_XDECREF(i);
446   return (rc);
447 }
448
449 PyObject *gmapmeth_values(PyObject *me, PyObject *arg)
450 {
451   PyObject *l = 0, *i = 0, *k, *v, *rc = 0;
452   int err = 0;
453
454   if (!PyArg_ParseTuple(arg, ":values") ||
455       (l = PyList_New(0)) == 0 ||
456       (i = PyObject_GetIter(me)) == 0)
457     goto done;
458   while ((k = PyIter_Next(i)) != 0) {
459     if ((v = PyObject_GetItem(me, k)) == 0 ||
460         PyList_Append(l, v))
461       err = -1;
462     Py_DECREF(k); Py_XDECREF(v);
463     if (err) goto done;
464   }
465   if (PyErr_Occurred()) goto done;
466   rc = l; l = 0;
467 done:
468   Py_XDECREF(l); Py_XDECREF(i);
469   return (rc);
470 }
471
472 PyObject *gmapmeth_items(PyObject *me, PyObject *arg)
473 {
474   PyObject *l = 0, *i = 0, *k, *v, *z, *rc = 0;
475   int err = 0;
476
477   if (!PyArg_ParseTuple(arg, ":items") ||
478       (l = PyList_New(0)) == 0 ||
479       (i = PyObject_GetIter(me)) == 0)
480     goto done;
481   while ((k = PyIter_Next(i)) != 0) {
482     z = 0;
483     if ((v = PyObject_GetItem(me, k)) == 0 ||
484         (z = Py_BuildValue("(OO)", k, v)) == 0 ||
485         PyList_Append(l, z))
486       err = -1;
487     Py_DECREF(k); Py_XDECREF(v); Py_XDECREF(z);
488     if (err) goto done;
489   }
490   if (PyErr_Occurred()) goto done;
491   rc = l; l = 0;
492 done:
493   Py_XDECREF(l); Py_XDECREF(i);
494   return (rc);
495 }
496
497 PyObject *gmapmeth_iterkeys(PyObject *me, PyObject *arg)
498 {
499   if (!PyArg_ParseTuple(arg, ":iterkeys")) return (0);
500   return (PyObject_GetIter(me));
501 }
502
503 PyObject *gmapmeth_itervalues(PyObject *me, PyObject *arg)
504 {
505   PyObject *i;
506   iter_pyobj *ii;
507
508   if (!PyArg_ParseTuple(arg, ":itervalues") ||
509       (i = PyObject_GetIter(me)) == 0)
510     return (0);
511   ii = PyObject_NEW(iter_pyobj, valiter_pytype);
512   ii->map = me; Py_INCREF(me);
513   ii->i = i;
514   return ((PyObject *)ii);
515 }
516
517 PyObject *gmapmeth_iteritems(PyObject *me, PyObject *arg)
518 {
519   PyObject *i;
520   iter_pyobj *ii;
521
522   if (!PyArg_ParseTuple(arg, ":iteritems") ||
523       (i = PyObject_GetIter(me)) == 0)
524     return (0);
525   ii = PyObject_NEW(iter_pyobj, itemiter_pytype);
526   ii->map = me; Py_INCREF(me);
527   ii->i = i;
528   return ((PyObject *)ii);
529 }
530
531 PyObject *gmapmeth_clear(PyObject *me, PyObject *arg)
532 {
533   PyObject *i = 0, *k = 0, *rc = 0;
534
535   if (!PyArg_ParseTuple(arg, ":clear") ||
536       (i = PyObject_GetIter(me)) == 0)
537     goto end;
538   while ((k = PyIter_Next(i)) != 0) {
539     PyObject_DelItem(me, k);
540     Py_DECREF(k);
541   }
542   if (PyErr_Occurred()) goto end;
543   rc = me; Py_INCREF(me);
544 end:
545   Py_XDECREF(i);
546   return (rc);
547 }
548
549 static char *def_kwlist[] = { "key", "default", 0 };
550
551 PyObject *gmapmeth_get(PyObject *me, PyObject *arg, PyObject *kw)
552 {
553   PyObject *k, *def = Py_None, *v;
554
555   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:get", def_kwlist, &k, &def))
556     return (0);
557   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
558   PyErr_Clear();
559   RETURN_OBJ(def);
560 }
561
562 PyObject *gmapmeth_setdefault(PyObject *me, PyObject *arg, PyObject *kw)
563 {
564   PyObject *k, *def = Py_None, *v;
565
566   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:setdefault",
567                                    def_kwlist, &k, &def))
568     return (0);
569   if ((v = PyObject_GetItem(me, k)) != 0) return (v);
570   PyErr_Clear();
571   if (PyObject_SetItem(me, k, def)) return (0);
572   RETURN_OBJ(def);
573 }
574
575 PyObject *gmapmeth_pop(PyObject *me, PyObject *arg, PyObject *kw)
576 {
577   PyObject *k, *def = 0, *v;
578
579   if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:pop", def_kwlist, &k, &def))
580     return (0);
581   if ((v = PyObject_GetItem(me, k)) != 0) {
582     PyObject_DelItem(me, k);
583     return (v);
584   }
585   PyErr_Clear();
586   RETURN_OBJ(def);
587 }
588
589 PyObject *gmapmeth_update(PyObject *me, PyObject *arg)
590 {
591   PyObject *map, *i = 0, *k, *v, *rc = 0;
592   int err = 0;
593
594   if (!PyArg_ParseTuple(arg, "O:update", &map) ||
595       (i = PyObject_GetIter(map)) == 0)
596     goto end;
597   while ((k = PyIter_Next(i)) != 0) {
598     if ((v = PyObject_GetItem(map, k)) == 0 ||
599         PyObject_SetItem(me, k, v))
600       err = -1;
601     Py_DECREF(k); Py_XDECREF(v);
602     if (err) goto end;
603   }
604   if (PyErr_Occurred()) goto end;
605   rc = me; Py_INCREF(me);
606 end:
607   Py_XDECREF(i);
608   return (rc);
609 }
610
611 PyObject *gmapmeth_popitem(PyObject *me, PyObject *arg)
612 {
613   PyObject *i = 0, *k = 0, *v = 0, *rc = 0;
614
615   if (!PyArg_ParseTuple(arg, ":popitem") ||
616       (i = PyObject_GetIter(me)))
617     goto end;
618   if ((k = PyIter_Next(i)) == 0) {
619     if (!PyErr_Occurred()) VALERR("popitem(): mapping is empty");
620     goto end;
621   }
622   if ((v = PyObject_GetItem(me, k)) == 0 ||
623       PyObject_DelItem(me, k))
624     goto end;
625   rc = Py_BuildValue("(OO)", k, v);
626 end:
627   Py_XDECREF(i); Py_XDECREF(k); Py_XDECREF(v);
628   return (rc);
629 }
630
631 PyMethodDef gmap_pymethods[] = {
632   GMAP_METHODS
633   { 0 }
634 };
635
636 /*----- Initialization ----------------------------------------------------*/
637
638 void util_pyinit(void)
639 {
640   INITTYPE(itemiter, root);
641   INITTYPE(valiter, root);
642 }
643
644 void util_pyinsert(PyObject *mod)
645 {
646   INSERT("ItemIter", itemiter_pytype);
647   INSERT("ValueIter", valiter_pytype);
648 }
649
650 /*----- That's all, folks -------------------------------------------------*/