3 * Miscellaneous utilities (not Catacomb-specific)
5 * (c) 2005 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the Python interface to Catacomb.
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.
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.
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.
27 /*----- Header files ------------------------------------------------------*/
29 #include "catacomb-python.h"
31 /* #undef HAVE_LONG_LONG */
33 /*----- External values ---------------------------------------------------*/
35 static PyObject *modname = 0;
36 PyObject *home_module = 0;
38 /*----- Conversions -------------------------------------------------------*/
40 PyObject *getulong(unsigned long w)
43 return (PyInt_FromLong(w));
45 return (PyLong_FromUnsignedLong(w));
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); }
54 PyObject *getk64(kludge64 u)
57 return (PyLong_FromUnsignedLongLong(GET64(unsigned PY_LONG_LONG, u)));
59 PyObject *i = 0, *j = 0, *t;
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;
66 if ((j = PyLong_FromUnsignedLong(LO64(u))) == 0) goto end;
67 if ((t = PyNumber_InPlaceOr(i, j)) == 0) goto end;
69 if ((rc = PyNumber_Int(i)) == 0) goto end;
77 PyObject *getbool(int b)
83 PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
85 PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
89 int convulong(PyObject *o, void *pp)
92 unsigned long *p = pp;
95 if (!o) VALERR("can't delete");
98 if (i < 0) VALERR("must be nonnegative");
101 if ((t = PyNumber_Long(o)) == 0) goto end;
102 *p = PyLong_AsUnsignedLong(t);
104 if (PyErr_Occurred()) goto end;
112 # define CONVu64(n) do { \
115 if (!convk64(o, &k)) goto end; \
116 t = GET64(uint64, k); \
117 if (t > MASK##n) VALERR("out of range"); \
121 # define CONVu64(n) assert(!"shouldn't be possible")
125 int convu##n(PyObject *o, void *pp) \
130 if (MASK##n > ULONG_MAX) \
133 if (!convulong(o, &u)) goto end; \
134 if (u > MASK##n) VALERR("out of range"); \
143 int convuint(PyObject *o, void *pp)
148 if (!convulong(o, &u)) goto end;
149 if (u > UINT_MAX) VALERR("out of range");
156 int convk64(PyObject *o, void *pp)
161 unsigned PY_LONG_LONG t;
167 if (!o) VALERR("can't delete");
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);
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;
179 hi = PyInt_AsUnsignedLongMask(i);
180 if ((t = PyNumber_InPlaceRshift(i, i32)) == 0) goto end;
182 if (PyObject_IsTrue(i)) VALERR("out of range");
183 SET64(*(kludge64 *)pp, hi, lo);
192 int convmpw(PyObject *o, void *pp)
197 if (!convulong(o, &u)) goto end;
198 if (u > MPW_MAX) VALERR("out of range");
205 int convszt(PyObject *o, void *pp)
210 if (!convulong(o, &u)) goto end;
211 if (u > ~(size_t)0) VALERR("out of range");
218 int convbool(PyObject *o, void *pp)
220 if (!o) VALERR("can't delete");
221 *(int *)pp = PyObject_IsTrue(o);
227 /*----- Type messing ------------------------------------------------------*/
229 static const PyTypeObject emptytype = { 0 };
231 void *newtype(PyTypeObject *metaty,
232 const PyTypeObject *skel,
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; \
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);
258 ty->ht_type.tp_name = PyString_AS_STRING(ty->ht_name);
259 DISCARD(PyObject_INIT(&ty->ht_type, metaty));
264 void typeready(PyTypeObject *ty)
267 PyDict_SetItemString(ty->tp_dict, "__module__", modname);
270 PyTypeObject *inittype(PyTypeObject *tyskel, PyTypeObject *meta)
272 PyTypeObject *ty = newtype(meta, tyskel, 0);
273 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
278 /*----- Constants ---------------------------------------------------------*/
280 void setconstants(PyObject *mod, const struct nameval *c)
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++;
294 /*----- Building method tables --------------------------------------------*/
296 DA_DECL(method_v, PyMethodDef);
297 static method_v global_pymethods = DA_INIT;
298 void addmethods(const PyMethodDef *m)
302 for (n = 0; m[n].ml_name; n++);
303 DA_ENSURE(&global_pymethods, n);
304 memcpy(DA(&global_pymethods) + DA_LEN(&global_pymethods),
306 DA_EXTEND(&global_pymethods, n);
309 PyMethodDef *donemethods(void)
311 static const PyMethodDef mzero = { 0 };
312 DA_PUSH(&global_pymethods, mzero);
313 return (DA(&global_pymethods));
316 /*----- Exceptions --------------------------------------------------------*/
318 PyObject *mkexc(PyObject *mod, PyObject *base,
319 const char *name, PyMethodDef *mm)
321 PyObject *nameobj = 0;
327 if ((dict = PyDict_New()) == 0) goto fail;
330 while (mm->ml_name) {
331 if ((func = PyCFunction_NewEx(mm, 0, mod)) == 0 ||
332 (meth = PyMethod_New(func, 0, exc)) == 0 ||
333 PyDict_SetItemString(dict, mm->ml_name, meth))
335 Py_DECREF(func); func = 0;
336 Py_DECREF(meth); meth = 0;
341 if ((nameobj = PyString_FromFormat("%s.%s",
342 PyModule_GetName(mod),
344 (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
361 void report_lost_exception_v(struct excinfo *exc,
362 const char *why, va_list ap)
364 PyObject *hookfn = 0;
365 PyObject *whyobj = 0;
368 /* Make sure we start out without a pending exception, or this will get
371 assert(!PyErr_Occurred());
373 /* Format the explanation. */
374 if (why) whyobj = PyString_FromFormatV(why, ap);
375 else { whyobj = Py_None; Py_INCREF(whyobj); }
377 /* Find our home module's `lostexchook' function. This won't work if
378 * there's no module, or the function isn't defined, or it's `None'.
380 if (!home_module) goto sys;
381 hookfn = PyObject_GetAttrString(home_module, "lostexchook");
382 if (hookfn == Py_None) goto sys;
384 else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
385 else { PyErr_Clear(); goto sys; }
387 /* Call the hook function. */
388 obj = PyObject_CallFunction(hookfn, "(OOOO)",
389 whyobj, exc->ty, exc->val, exc->tb);
393 /* Something went wrong reporting the problem. */
395 PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
397 /* drop through... */
399 /* There was no hook, so try to do something sensible using
403 PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n",
404 PyString_AS_STRING(whyobj));
405 RESTORE_EXCINFO(exc);
407 /* drop through... */
409 /* Clean up afterwards. */
416 void report_lost_exception(struct excinfo *exc, const char *why, ...)
421 report_lost_exception_v(exc, why, ap);
425 void stash_exception(struct excinfo *exc, const char *why, ...)
428 struct excinfo stash;
434 STASH_EXCINFO(&stash);
435 report_lost_exception_v(&stash, why, ap);
440 void restore_exception(struct excinfo *exc, const char *why, ...)
443 struct excinfo stash;
445 if (!PyErr_Occurred())
446 RESTORE_EXCINFO(exc);
449 STASH_EXCINFO(&stash);
450 report_lost_exception_v(exc, why, ap);
451 RESTORE_EXCINFO(&stash);
456 /*----- Generic dictionary methods ----------------------------------------*/
458 static PyTypeObject *itemiter_pytype, *valiter_pytype;
460 typedef struct iter_pyobj {
465 #define ITER_MAP(o) (((iter_pyobj *)(o))->map)
466 #define ITER_I(o) (((iter_pyobj *)(o))->i)
468 static void iter_pydealloc(PyObject *me)
469 { Py_DECREF(ITER_MAP(me)); Py_DECREF(ITER_I(me)); FREEOBJ(me); }
471 static PyObject *itemiter_pynext(PyObject *me)
473 PyObject *k = 0, *v = 0, *rc = 0;
475 if ((k = PyIter_Next(ITER_I(me))) != 0 &&
476 (v = PyObject_GetItem(ITER_MAP(me), k)) != 0)
477 rc = Py_BuildValue("(OO)", k, v);
478 Py_XDECREF(k); Py_XDECREF(v);
482 static PyTypeObject itemiter_pytype_skel = {
483 PyObject_HEAD_INIT(0) 0, /* Header */
484 "ItemIter", /* @tp_name@ */
485 sizeof(iter_pyobj), /* @tp_basicsize@ */
486 0, /* @tp_itemsize@ */
488 iter_pydealloc, /* @tp_dealloc@ */
490 0, /* @tp_getattr@ */
491 0, /* @tp_setattr@ */
492 0, /* @tp_compare@ */
494 0, /* @tp_as_number@ */
495 0, /* @tp_as_sequence@ */
496 0, /* @tp_as_mapping@ */
500 0, /* @tp_getattro@ */
501 0, /* @tp_setattro@ */
502 0, /* @tp_as_buffer@ */
503 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
507 "Iterates over the keys of a mapping.",
509 0, /* @tp_traverse@ */
511 0, /* @tp_richcompare@ */
512 0, /* @tp_weaklistoffset@ */
513 PyObject_SelfIter, /* @tp_iter@ */
514 itemiter_pynext, /* @tp_iternext@ */
515 0, /* @tp_methods@ */
516 0, /* @tp_members@ */
520 0, /* @tp_descr_get@ */
521 0, /* @tp_descr_set@ */
522 0, /* @tp_dictoffset@ */
524 PyType_GenericAlloc, /* @tp_alloc@ */
525 abstract_pynew, /* @tp_new@ */
530 static PyObject *valiter_pynext(PyObject *me)
532 PyObject *k = 0, *rc = 0;
534 if ((k = PyIter_Next(ITER_I(me))) != 0)
535 rc = PyObject_GetItem(ITER_MAP(me), k);
540 static PyTypeObject valiter_pytype_skel = {
541 PyObject_HEAD_INIT(0) 0, /* Header */
542 "ValueIter", /* @tp_name@ */
543 sizeof(iter_pyobj), /* @tp_basicsize@ */
544 0, /* @tp_itemsize@ */
546 iter_pydealloc, /* @tp_dealloc@ */
548 0, /* @tp_getattr@ */
549 0, /* @tp_setattr@ */
550 0, /* @tp_compare@ */
552 0, /* @tp_as_number@ */
553 0, /* @tp_as_sequence@ */
554 0, /* @tp_as_mapping@ */
558 0, /* @tp_getattro@ */
559 0, /* @tp_setattro@ */
560 0, /* @tp_as_buffer@ */
561 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
565 "Iterates over the values of a mapping.",
567 0, /* @tp_traverse@ */
569 0, /* @tp_richcompare@ */
570 0, /* @tp_weaklistoffset@ */
571 PyObject_SelfIter, /* @tp_iter@ */
572 valiter_pynext, /* @tp_iternext@ */
573 0, /* @tp_methods@ */
574 0, /* @tp_members@ */
578 0, /* @tp_descr_get@ */
579 0, /* @tp_descr_set@ */
580 0, /* @tp_dictoffset@ */
582 PyType_GenericAlloc, /* @tp_alloc@ */
583 abstract_pynew, /* @tp_new@ */
588 PySequenceMethods gmap_pysequence = {
594 0, /* @sq_ass_item@ */
595 0, /* @sq_ass_slice@ */
596 PyMapping_HasKey, /* @sq_contains@ */
597 0, /* @sq_inplace_concat@ */
598 0 /* @sq_inplace_repeat@ */
601 Py_ssize_t gmap_pysize(PyObject *me)
603 PyObject *i = 0, *x = 0;
604 Py_ssize_t rc = -1, n = 0;
606 if ((i = PyObject_GetIter(me)) == 0) goto done;
607 while ((x = PyIter_Next(i)) != 0) { n++; Py_DECREF(x); x = 0; }
608 if (PyErr_Occurred()) goto done;
611 Py_XDECREF(i); Py_XDECREF(x);
615 PyObject *gmapmeth_has_key(PyObject *me, PyObject *arg)
618 if (!PyArg_ParseTuple(arg, "O:has_key", &k)) return (0);
619 return (getbool(PyMapping_HasKey(me, k)));
622 PyObject *gmapmeth_keys(PyObject *me, PyObject *arg)
624 PyObject *l = 0, *i = 0, *k, *rc = 0;
627 if (!PyArg_ParseTuple(arg, ":keys") ||
628 (l = PyList_New(0)) == 0 ||
629 (i = PyObject_GetIter(me)) == 0)
631 while ((k = PyIter_Next(i)) != 0)
632 { err = PyList_Append(l, k); Py_DECREF(k); if (err) goto done; }
633 if (PyErr_Occurred()) goto done;
636 Py_XDECREF(l); Py_XDECREF(i);
640 PyObject *gmapmeth_values(PyObject *me, PyObject *arg)
642 PyObject *l = 0, *i = 0, *k, *v, *rc = 0;
645 if (!PyArg_ParseTuple(arg, ":values") ||
646 (l = PyList_New(0)) == 0 ||
647 (i = PyObject_GetIter(me)) == 0)
649 while ((k = PyIter_Next(i)) != 0) {
650 if ((v = PyObject_GetItem(me, k)) == 0 ||
653 Py_DECREF(k); Py_XDECREF(v);
656 if (PyErr_Occurred()) goto done;
659 Py_XDECREF(l); Py_XDECREF(i);
663 PyObject *gmapmeth_items(PyObject *me, PyObject *arg)
665 PyObject *l = 0, *i = 0, *k, *v, *z, *rc = 0;
668 if (!PyArg_ParseTuple(arg, ":items") ||
669 (l = PyList_New(0)) == 0 ||
670 (i = PyObject_GetIter(me)) == 0)
672 while ((k = PyIter_Next(i)) != 0) {
674 if ((v = PyObject_GetItem(me, k)) == 0 ||
675 (z = Py_BuildValue("(OO)", k, v)) == 0 ||
678 Py_DECREF(k); Py_XDECREF(v); Py_XDECREF(z);
681 if (PyErr_Occurred()) goto done;
684 Py_XDECREF(l); Py_XDECREF(i);
688 PyObject *gmapmeth_iterkeys(PyObject *me, PyObject *arg)
690 if (!PyArg_ParseTuple(arg, ":iterkeys")) return (0);
691 return (PyObject_GetIter(me));
694 PyObject *gmapmeth_itervalues(PyObject *me, PyObject *arg)
699 if (!PyArg_ParseTuple(arg, ":itervalues") ||
700 (i = PyObject_GetIter(me)) == 0)
702 ii = PyObject_NEW(iter_pyobj, valiter_pytype);
703 ii->map = me; Py_INCREF(me);
705 return ((PyObject *)ii);
708 PyObject *gmapmeth_iteritems(PyObject *me, PyObject *arg)
713 if (!PyArg_ParseTuple(arg, ":iteritems") ||
714 (i = PyObject_GetIter(me)) == 0)
716 ii = PyObject_NEW(iter_pyobj, itemiter_pytype);
717 ii->map = me; Py_INCREF(me);
719 return ((PyObject *)ii);
722 PyObject *gmapmeth_clear(PyObject *me, PyObject *arg)
724 PyObject *i = 0, *k = 0, *rc = 0;
726 if (!PyArg_ParseTuple(arg, ":clear") ||
727 (i = PyObject_GetIter(me)) == 0)
729 while ((k = PyIter_Next(i)) != 0) {
730 PyObject_DelItem(me, k);
733 if (PyErr_Occurred()) goto end;
734 rc = me; Py_INCREF(me);
740 static const char *const def_kwlist[] = { "key", "default", 0 };
742 PyObject *gmapmeth_get(PyObject *me, PyObject *arg, PyObject *kw)
744 PyObject *k, *def = Py_None, *v;
746 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|O:get",
747 (/*unconst*/ char **)def_kwlist,
750 if ((v = PyObject_GetItem(me, k)) != 0) return (v);
755 PyObject *gmapmeth_setdefault(PyObject *me, PyObject *arg, PyObject *kw)
757 PyObject *k, *def = Py_None, *v;
759 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|O:setdefault",
760 (/*unconst*/ char **)def_kwlist,
763 if ((v = PyObject_GetItem(me, k)) != 0) return (v);
765 if (PyObject_SetItem(me, k, def)) return (0);
769 PyObject *gmapmeth_pop(PyObject *me, PyObject *arg, PyObject *kw)
771 PyObject *k, *def = 0, *v;
773 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|O:pop",
774 (/*unconst*/ char **)def_kwlist,
777 if ((v = PyObject_GetItem(me, k)) != 0) {
778 PyObject_DelItem(me, k);
787 PyObject *gmapmeth_update(PyObject *me, PyObject *arg)
789 PyObject *map, *i = 0, *k, *v, *rc = 0;
792 if (!PyArg_ParseTuple(arg, "O:update", &map) ||
793 (i = PyObject_GetIter(map)) == 0)
795 while ((k = PyIter_Next(i)) != 0) {
796 if ((v = PyObject_GetItem(map, k)) == 0 ||
797 PyObject_SetItem(me, k, v))
799 Py_DECREF(k); Py_XDECREF(v);
802 if (PyErr_Occurred()) goto end;
803 rc = me; Py_INCREF(me);
809 PyObject *gmapmeth_popitem(PyObject *me, PyObject *arg)
811 PyObject *i = 0, *k = 0, *v = 0, *rc = 0;
813 if (!PyArg_ParseTuple(arg, ":popitem") ||
814 (i = PyObject_GetIter(me)) == 0)
816 if ((k = PyIter_Next(i)) == 0) {
817 if (!PyErr_Occurred()) VALERR("popitem(): mapping is empty");
820 if ((v = PyObject_GetItem(me, k)) == 0 ||
821 PyObject_DelItem(me, k))
823 rc = Py_BuildValue("(OO)", k, v);
825 Py_XDECREF(i); Py_XDECREF(k); Py_XDECREF(v);
829 PyMethodDef gmap_pymethods[] = {
834 /*----- Initialization ----------------------------------------------------*/
836 static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
840 if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
842 Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
846 static const PyMethodDef methods[] = {
847 #define METHNAME(func) meth_##func
848 METH (_set_home_module, "_set_home_module(MOD)")
853 void util_pyinit(void)
855 modname = PyString_FromString("catacomb");
856 INITTYPE(itemiter, root);
857 INITTYPE(valiter, root);
861 void util_pyinsert(PyObject *mod)
863 INSERT("ItemIter", itemiter_pytype);
864 INSERT("ValueIter", valiter_pytype);
867 /*----- That's all, folks -------------------------------------------------*/