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
)
285 if (c
->value
> LONG_MAX
)
286 x
= PyLong_FromUnsignedLong(c
->value
);
288 x
= PyInt_FromLong(c
->value
);
289 PyModule_AddObject(mod
, (/*unconst*/ char *)c
->name
, x
);
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 ((nameobj
= PyString_FromFormat("%s.%s",
328 PyModule_GetName(mod
),
330 (dict
= PyDict_New()) == 0 ||
331 (exc
= PyErr_NewException(PyString_AS_STRING(nameobj
),
336 while (mm
->ml_name
) {
337 if ((func
= PyCFunction_NewEx(mm
, 0, mod
)) == 0 ||
338 (meth
= PyMethod_New(func
, 0, exc
)) == 0 ||
339 PyDict_SetItemString(dict
, mm
->ml_name
, meth
))
341 Py_DECREF(func
); func
= 0;
342 Py_DECREF(meth
); meth
= 0;
360 void report_lost_exception_v(struct excinfo
*exc
,
361 const char *why
, va_list ap
)
363 PyObject
*hookfn
= 0;
364 PyObject
*whyobj
= 0;
367 /* Make sure we start out without a pending exception, or this will get
370 assert(!PyErr_Occurred());
372 /* Format the explanation. */
373 if (why
) whyobj
= PyString_FromFormatV(why
, ap
);
374 else { whyobj
= Py_None
; Py_INCREF(whyobj
); }
376 /* Find our home module's `lostexchook' function. This won't work if
377 * there's no module, or the function isn't defined, or it's `None'.
379 if (!home_module
) goto sys
;
380 hookfn
= PyObject_GetAttrString(home_module
, "lostexchook");
381 if (hookfn
== Py_None
) goto sys
;
383 else if (!PyErr_ExceptionMatches(PyExc_AttributeError
)) goto ouch
;
384 else { PyErr_Clear(); goto sys
; }
386 /* Call the hook function. */
387 obj
= PyObject_CallFunction(hookfn
, "(OOOO)",
388 whyobj
, exc
->ty
, exc
->val
, exc
->tb
);
392 /* Something went wrong reporting the problem. */
394 PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
396 /* drop through... */
398 /* There was no hook, so try to do something sensible using
402 PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n",
403 PyString_AS_STRING(whyobj
));
404 RESTORE_EXCINFO(exc
);
406 /* drop through... */
408 /* Clean up afterwards. */
415 void report_lost_exception(struct excinfo
*exc
, const char *why
, ...)
420 report_lost_exception_v(exc
, why
, ap
);
424 void stash_exception(struct excinfo
*exc
, const char *why
, ...)
427 struct excinfo stash
;
433 STASH_EXCINFO(&stash
);
434 report_lost_exception_v(&stash
, why
, ap
);
439 void restore_exception(struct excinfo
*exc
, const char *why
, ...)
442 struct excinfo stash
;
444 if (!PyErr_Occurred())
445 RESTORE_EXCINFO(exc
);
448 STASH_EXCINFO(&stash
);
449 report_lost_exception_v(exc
, why
, ap
);
450 RESTORE_EXCINFO(&stash
);
455 /*----- Generic dictionary methods ----------------------------------------*/
457 static PyTypeObject
*itemiter_pytype
, *valiter_pytype
;
459 typedef struct iter_pyobj
{
464 #define ITER_MAP(o) (((iter_pyobj *)(o))->map)
465 #define ITER_I(o) (((iter_pyobj *)(o))->i)
467 static void iter_pydealloc(PyObject
*me
)
468 { Py_DECREF(ITER_MAP(me
)); Py_DECREF(ITER_I(me
)); FREEOBJ(me
); }
470 static PyObject
*itemiter_pynext(PyObject
*me
)
472 PyObject
*k
= 0, *v
= 0, *rc
= 0;
474 if ((k
= PyIter_Next(ITER_I(me
))) != 0 &&
475 (v
= PyObject_GetItem(ITER_MAP(me
), k
)) != 0)
476 rc
= Py_BuildValue("(OO)", k
, v
);
477 Py_XDECREF(k
); Py_XDECREF(v
);
481 static PyTypeObject itemiter_pytype_skel
= {
482 PyObject_HEAD_INIT(0) 0, /* Header */
483 "ItemIter", /* @tp_name@ */
484 sizeof(iter_pyobj
), /* @tp_basicsize@ */
485 0, /* @tp_itemsize@ */
487 iter_pydealloc
, /* @tp_dealloc@ */
489 0, /* @tp_getattr@ */
490 0, /* @tp_setattr@ */
491 0, /* @tp_compare@ */
493 0, /* @tp_as_number@ */
494 0, /* @tp_as_sequence@ */
495 0, /* @tp_as_mapping@ */
499 0, /* @tp_getattro@ */
500 0, /* @tp_setattro@ */
501 0, /* @tp_as_buffer@ */
502 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
506 "Iterates over the keys of a mapping.",
508 0, /* @tp_traverse@ */
510 0, /* @tp_richcompare@ */
511 0, /* @tp_weaklistoffset@ */
512 PyObject_SelfIter
, /* @tp_iter@ */
513 itemiter_pynext
, /* @tp_iternext@ */
514 0, /* @tp_methods@ */
515 0, /* @tp_members@ */
519 0, /* @tp_descr_get@ */
520 0, /* @tp_descr_set@ */
521 0, /* @tp_dictoffset@ */
523 PyType_GenericAlloc
, /* @tp_alloc@ */
524 abstract_pynew
, /* @tp_new@ */
529 static PyObject
*valiter_pynext(PyObject
*me
)
531 PyObject
*k
= 0, *rc
= 0;
533 if ((k
= PyIter_Next(ITER_I(me
))) != 0)
534 rc
= PyObject_GetItem(ITER_MAP(me
), k
);
539 static PyTypeObject valiter_pytype_skel
= {
540 PyObject_HEAD_INIT(0) 0, /* Header */
541 "ValueIter", /* @tp_name@ */
542 sizeof(iter_pyobj
), /* @tp_basicsize@ */
543 0, /* @tp_itemsize@ */
545 iter_pydealloc
, /* @tp_dealloc@ */
547 0, /* @tp_getattr@ */
548 0, /* @tp_setattr@ */
549 0, /* @tp_compare@ */
551 0, /* @tp_as_number@ */
552 0, /* @tp_as_sequence@ */
553 0, /* @tp_as_mapping@ */
557 0, /* @tp_getattro@ */
558 0, /* @tp_setattro@ */
559 0, /* @tp_as_buffer@ */
560 Py_TPFLAGS_DEFAULT
| /* @tp_flags@ */
564 "Iterates over the values of a mapping.",
566 0, /* @tp_traverse@ */
568 0, /* @tp_richcompare@ */
569 0, /* @tp_weaklistoffset@ */
570 PyObject_SelfIter
, /* @tp_iter@ */
571 valiter_pynext
, /* @tp_iternext@ */
572 0, /* @tp_methods@ */
573 0, /* @tp_members@ */
577 0, /* @tp_descr_get@ */
578 0, /* @tp_descr_set@ */
579 0, /* @tp_dictoffset@ */
581 PyType_GenericAlloc
, /* @tp_alloc@ */
582 abstract_pynew
, /* @tp_new@ */
587 PySequenceMethods gmap_pysequence
= {
593 0, /* @sq_ass_item@ */
594 0, /* @sq_ass_slice@ */
595 PyMapping_HasKey
, /* @sq_contains@ */
596 0, /* @sq_inplace_concat@ */
597 0 /* @sq_inplace_repeat@ */
600 Py_ssize_t
gmap_pysize(PyObject
*me
)
602 PyObject
*i
= 0, *x
= 0;
603 Py_ssize_t rc
= -1, n
= 0;
605 if ((i
= PyObject_GetIter(me
)) == 0) goto done
;
606 while ((x
= PyIter_Next(i
)) != 0) { n
++; Py_DECREF(x
); x
= 0; }
607 if (PyErr_Occurred()) goto done
;
610 Py_XDECREF(i
); Py_XDECREF(x
);
614 PyObject
*gmapmeth_has_key(PyObject
*me
, PyObject
*arg
)
617 if (!PyArg_ParseTuple(arg
, "O:has_key", &k
)) return (0);
618 return (getbool(PyMapping_HasKey(me
, k
)));
621 PyObject
*gmapmeth_keys(PyObject
*me
, PyObject
*arg
)
623 PyObject
*l
= 0, *i
= 0, *k
, *rc
= 0;
626 if (!PyArg_ParseTuple(arg
, ":keys") ||
627 (l
= PyList_New(0)) == 0 ||
628 (i
= PyObject_GetIter(me
)) == 0)
630 while ((k
= PyIter_Next(i
)) != 0)
631 { err
= PyList_Append(l
, k
); Py_DECREF(k
); if (err
) goto done
; }
632 if (PyErr_Occurred()) goto done
;
635 Py_XDECREF(l
); Py_XDECREF(i
);
639 PyObject
*gmapmeth_values(PyObject
*me
, PyObject
*arg
)
641 PyObject
*l
= 0, *i
= 0, *k
, *v
, *rc
= 0;
644 if (!PyArg_ParseTuple(arg
, ":values") ||
645 (l
= PyList_New(0)) == 0 ||
646 (i
= PyObject_GetIter(me
)) == 0)
648 while ((k
= PyIter_Next(i
)) != 0) {
649 if ((v
= PyObject_GetItem(me
, k
)) == 0 ||
652 Py_DECREF(k
); Py_XDECREF(v
);
655 if (PyErr_Occurred()) goto done
;
658 Py_XDECREF(l
); Py_XDECREF(i
);
662 PyObject
*gmapmeth_items(PyObject
*me
, PyObject
*arg
)
664 PyObject
*l
= 0, *i
= 0, *k
, *v
, *z
, *rc
= 0;
667 if (!PyArg_ParseTuple(arg
, ":items") ||
668 (l
= PyList_New(0)) == 0 ||
669 (i
= PyObject_GetIter(me
)) == 0)
671 while ((k
= PyIter_Next(i
)) != 0) {
673 if ((v
= PyObject_GetItem(me
, k
)) == 0 ||
674 (z
= Py_BuildValue("(OO)", k
, v
)) == 0 ||
677 Py_DECREF(k
); Py_XDECREF(v
); Py_XDECREF(z
);
680 if (PyErr_Occurred()) goto done
;
683 Py_XDECREF(l
); Py_XDECREF(i
);
687 PyObject
*gmapmeth_iterkeys(PyObject
*me
, PyObject
*arg
)
689 if (!PyArg_ParseTuple(arg
, ":iterkeys")) return (0);
690 return (PyObject_GetIter(me
));
693 PyObject
*gmapmeth_itervalues(PyObject
*me
, PyObject
*arg
)
698 if (!PyArg_ParseTuple(arg
, ":itervalues") ||
699 (i
= PyObject_GetIter(me
)) == 0)
701 ii
= PyObject_NEW(iter_pyobj
, valiter_pytype
);
702 ii
->map
= me
; Py_INCREF(me
);
704 return ((PyObject
*)ii
);
707 PyObject
*gmapmeth_iteritems(PyObject
*me
, PyObject
*arg
)
712 if (!PyArg_ParseTuple(arg
, ":iteritems") ||
713 (i
= PyObject_GetIter(me
)) == 0)
715 ii
= PyObject_NEW(iter_pyobj
, itemiter_pytype
);
716 ii
->map
= me
; Py_INCREF(me
);
718 return ((PyObject
*)ii
);
721 PyObject
*gmapmeth_clear(PyObject
*me
, PyObject
*arg
)
723 PyObject
*i
= 0, *k
= 0, *rc
= 0;
725 if (!PyArg_ParseTuple(arg
, ":clear") ||
726 (i
= PyObject_GetIter(me
)) == 0)
728 while ((k
= PyIter_Next(i
)) != 0) {
729 PyObject_DelItem(me
, k
);
732 if (PyErr_Occurred()) goto end
;
733 rc
= me
; Py_INCREF(me
);
739 static char *def_kwlist
[] = { "key", "default", 0 };
741 PyObject
*gmapmeth_get(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
743 PyObject
*k
, *def
= Py_None
, *v
;
745 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|O:get", def_kwlist
, &k
, &def
))
747 if ((v
= PyObject_GetItem(me
, k
)) != 0) return (v
);
752 PyObject
*gmapmeth_setdefault(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
754 PyObject
*k
, *def
= Py_None
, *v
;
756 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|O:setdefault",
757 def_kwlist
, &k
, &def
))
759 if ((v
= PyObject_GetItem(me
, k
)) != 0) return (v
);
761 if (PyObject_SetItem(me
, k
, def
)) return (0);
765 PyObject
*gmapmeth_pop(PyObject
*me
, PyObject
*arg
, PyObject
*kw
)
767 PyObject
*k
, *def
= 0, *v
;
769 if (!PyArg_ParseTupleAndKeywords(arg
, kw
, "O|O:pop", def_kwlist
, &k
, &def
))
771 if ((v
= PyObject_GetItem(me
, k
)) != 0) {
772 PyObject_DelItem(me
, k
);
781 PyObject
*gmapmeth_update(PyObject
*me
, PyObject
*arg
)
783 PyObject
*map
, *i
= 0, *k
, *v
, *rc
= 0;
786 if (!PyArg_ParseTuple(arg
, "O:update", &map
) ||
787 (i
= PyObject_GetIter(map
)) == 0)
789 while ((k
= PyIter_Next(i
)) != 0) {
790 if ((v
= PyObject_GetItem(map
, k
)) == 0 ||
791 PyObject_SetItem(me
, k
, v
))
793 Py_DECREF(k
); Py_XDECREF(v
);
796 if (PyErr_Occurred()) goto end
;
797 rc
= me
; Py_INCREF(me
);
803 PyObject
*gmapmeth_popitem(PyObject
*me
, PyObject
*arg
)
805 PyObject
*i
= 0, *k
= 0, *v
= 0, *rc
= 0;
807 if (!PyArg_ParseTuple(arg
, ":popitem") ||
808 (i
= PyObject_GetIter(me
)) == 0)
810 if ((k
= PyIter_Next(i
)) == 0) {
811 if (!PyErr_Occurred()) VALERR("popitem(): mapping is empty");
814 if ((v
= PyObject_GetItem(me
, k
)) == 0 ||
815 PyObject_DelItem(me
, k
))
817 rc
= Py_BuildValue("(OO)", k
, v
);
819 Py_XDECREF(i
); Py_XDECREF(k
); Py_XDECREF(v
);
823 PyMethodDef gmap_pymethods
[] = {
828 /*----- Initialization ----------------------------------------------------*/
830 static PyObject
*meth__set_home_module(PyObject
*me
, PyObject
*arg
)
834 if (!PyArg_ParseTuple(arg
, "O!:_set_home_module", &PyModule_Type
, &mod
))
836 Py_XDECREF(home_module
); home_module
= mod
; Py_INCREF(home_module
);
840 static const PyMethodDef methods
[] = {
841 #define METHNAME(func) meth_##func
842 METH (_set_home_module
, "_set_home_module(MOD)")
847 void util_pyinit(void)
849 modname
= PyString_FromString("catacomb");
850 INITTYPE(itemiter
, root
);
851 INITTYPE(valiter
, root
);
855 void util_pyinsert(PyObject
*mod
)
857 INSERT("ItemIter", itemiter_pytype
);
858 INSERT("ValueIter", valiter_pytype
);
861 /*----- That's all, folks -------------------------------------------------*/