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