--- /dev/null
+/* -*-c-*-
+ *
+ * Pyke: the Python Kit for Extensions
+ *
+ * (c) 2019 Straylight/Edgeware
+ */
+
+/*----- Licensing notice --------------------------------------------------*
+ *
+ * This file is part of Pyke: the Python Kit for Extensions.
+ *
+ * Pyke is free software: you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your
+ * option) any later version.
+ *
+ * Pyke is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Pyke. If not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+#ifndef PYKE_H
+#define PYKE_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/*----- Header files ------------------------------------------------------*/
+
+#define PY_SSIZE_T_CLEAN
+
+#include <Python.h>
+#include <structmember.h>
+
+/*----- Other preliminaries -----------------------------------------------*/
+
+#define NOTHING
+#define COMMA ,
+
+/*----- Symbol visibility -------------------------------------------------*
+ *
+ * This library is very messy regarding symbol namespace. Keep this mess
+ * within our shared-object.
+ */
+
+#define GOBBLE_SEMI extern int notexist
+#if defined(__GNUC__) && defined(__ELF__)
+# define PRIVATE_SYMBOLS _Pragma("GCC visibility push(hidden)") GOBBLE_SEMI
+# define PUBLIC_SYMBOLS _Pragma("GCC visibility pop") GOBBLE_SEMI
+# define EXPORT __attribute__((__visibility__("default")))
+#else
+# define PRIVATE_SYMBOLS GOBBLE_SEMI
+# define PUBLIC_SYMBOLS GOBBLE_SEMI
+# define EXPORT
+#endif
+
+PRIVATE_SYMBOLS;
+
+/*----- Utilities for returning values and exceptions ---------------------*/
+
+/* Returning values. */
+#define RETURN_OBJ(obj) do { Py_INCREF(obj); return (obj); } while (0)
+#define RETURN_NONE RETURN_OBJ(Py_None)
+#define RETURN_NOTIMPL RETURN_OBJ(Py_NotImplemented)
+#define RETURN_TRUE RETURN_OBJ(Py_True)
+#define RETURN_FALSE RETURN_OBJ(Py_False)
+#define RETURN_ME RETURN_OBJ(me)
+
+/* Returning exceptions. (Note that `KeyError' is `MAPERR' here, because
+ * Catacomb has its own kind of `KeyError'.)
+ */
+#define EXCERR(exc, str) do { \
+ PyErr_SetString(exc, str); \
+ goto end; \
+} while (0)
+#define VALERR(str) EXCERR(PyExc_ValueError, str)
+#define OVFERR(str) EXCERR(PyExc_OverflowError, str)
+#define TYERR(str) EXCERR(PyExc_TypeError, str)
+#define IXERR(str) EXCERR(PyExc_IndexError, str)
+#define ZDIVERR(str) EXCERR(PyExc_ZeroDivisionError, str)
+#define SYSERR(str) EXCERR(PyExc_SystemError, str)
+#define NIERR(str) EXCERR(PyExc_NotImplementedError, str)
+#define INDEXERR(idx) do { \
+ PyErr_SetObject(PyExc_KeyError, idx); \
+ goto end; \
+} while (0)
+#define OSERR(name) do { \
+ PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); \
+ goto end; \
+} while (0)
+
+/* Saving and restoring exceptions. */
+struct excinfo { PyObject *ty, *val, *tb; };
+#define EXCINFO_INIT { 0, 0, 0 }
+#define INIT_EXCINFO(exc) do { \
+ struct excinfo *_exc = (exc); _exc->ty = _exc->val = _exc->tb = 0; \
+} while (0)
+#define RELEASE_EXCINFO(exc) do { \
+ struct excinfo *_exc = (exc); \
+ Py_XDECREF(_exc->ty); _exc->ty = 0; \
+ Py_XDECREF(_exc->val); _exc->val = 0; \
+ Py_XDECREF(_exc->tb); _exc->tb = 0; \
+} while (0)
+#define STASH_EXCINFO(exc) do { \
+ struct excinfo *_exc = (exc); \
+ PyErr_Fetch(&_exc->ty, &_exc->val, &_exc->tb); \
+ PyErr_NormalizeException(&_exc->ty, &_exc->val, &_exc->tb); \
+} while (0)
+#define RESTORE_EXCINFO(exc) do { \
+ struct excinfo *_exc = (exc); \
+ PyErr_Restore(_exc->ty, _exc->val, _exc->tb); \
+ _exc->ty = _exc->val = _exc->tb = 0; \
+} while (0)
+extern void report_lost_exception(struct excinfo *, const char *, ...);
+extern void report_lost_exception_v(struct excinfo *, const char *, va_list);
+extern void stash_exception(struct excinfo *, const char *, ...);
+extern void restore_exception(struct excinfo *, const char *, ...);
+
+/*----- Conversions -------------------------------------------------------*/
+
+/* Define an input conversion (`O&') function: check that the object has
+ * Python type TY, and extract a C pointer to CTY by calling EXT on the
+ * object (which may well be a macro).
+ */
+#define CONVFUNC(ty, cty, ext) \
+ int conv##ty(PyObject *o, void *p) \
+ { \
+ if (!PyObject_TypeCheck(o, ty##_pytype)) \
+ TYERR("wanted a " #ty); \
+ *(cty *)p = ext(o); \
+ return (1); \
+ end: \
+ return (0); \
+ }
+
+/* Input conversion functions for standard kinds of objects, with overflow
+ * checking where applicable.
+ */
+extern int convulong(PyObject *, void *); /* unsigned long */
+extern int convuint(PyObject *, void *); /* unsigned int */
+extern int convszt(PyObject *, void *); /* size_t */
+extern int convbool(PyObject *, void *); /* bool */
+
+/* Output conversions. */
+extern PyObject *getbool(int); /* bool */
+extern PyObject *getulong(unsigned long); /* any kind of unsigned integer */
+
+/*----- Miscellaneous utilities -------------------------------------------*/
+
+#define FREEOBJ(obj) \
+ (((PyObject *)(obj))->ob_type->tp_free((PyObject *)(obj)))
+ /* Actually free OBJ, e.g., in a deallocation function. */
+
+extern PyObject *abstract_pynew(PyTypeObject *, PyObject *, PyObject *);
+ /* A `tp_new' function which refuses to make the object. */
+
+#define KWLIST (/*unconst*/ char **)kwlist
+ /* Strip `const' qualifiers from the keyword list `kwlist'. Useful when
+ * calling `PyArg_ParseTupleAndKeywords', which isn't `const'-correct.
+ */
+
+/*----- Type definitions --------------------------------------------------*
+ *
+ * Pyke types are defined in a rather unusual way.
+ *
+ * The main code defines a `type skeleton' of type `PyTypeObject',
+ * conventionally named `TY_pytype_skel'. Unlike typical Python type
+ * definitions in extensions, this can (and should) be read-only. Also,
+ * there's no point in setting the `tp_base' pointer here, because the actual
+ * runtime base type object won't, in general, be known at compile time.
+ * Instead, the type skeletons are converted into Python `heap types' by the
+ * `INITTYPE' macro. The main difference is that Python code can add
+ * attributes to heap types, and we make extensive use of this ability.
+ */
+
+extern void *newtype(PyTypeObject */*meta*/,
+ const PyTypeObject */*skel*/, const char */*name*/);
+ /* Make and return a new Python type object, of type META (typically
+ * `PyType_Type', but may be a subclass), filled in from the skeleton SKEL
+ * (null to inherit everything), and named NAME. The caller can mess with
+ * the type object further at this time: call `typeready' when it's set up
+ * properly.
+ */
+
+extern void typeready(PyTypeObject *);
+ /* The type object is now ready to be used. */
+
+extern PyTypeObject *inittype(PyTypeObject */*skel*/,
+ PyTypeObject */*meta*/);
+ /* All-in-one function to construct a working type from a type skeleton
+ * SKEL, with metaclass META. The caller is expected to have filled in the
+ * direct superclass in SKEL->tp_base.
+ */
+
+/* Alias for built-in types, to fit in with Pyke naming conventions. */
+#define root_pytype 0
+#define type_pytype &PyType_Type
+
+#define INITTYPE_META(ty, base, meta) do { \
+ ty##_pytype_skel.tp_base = base##_pytype; \
+ ty##_pytype = inittype(&ty##_pytype_skel, meta##_pytype); \
+} while (0)
+#define INITTYPE(ty, base) INITTYPE_META(ty, base, type)
+ /* Macros to initialize a type from its skeleton. */
+
+/* Convenience wrappers for filling in `PyMethodDef' tables, following
+ * Pyke naming convention. Define `METHNAME' locally as
+ *
+ * #define METHNAME(name) foometh_##func
+ *
+ * around the method table.
+ */
+#define METH(func, doc) \
+ { #func, METHNAME(func), METH_VARARGS, doc },
+#define KWMETH(func, doc) \
+ { #func, (PyCFunction)METHNAME(func), \
+ METH_VARARGS | METH_KEYWORDS, doc },
+
+/* Convenience wrappers for filling in `PyGetSetDef' tables, following Pyke
+ * naming convention. Define `GETSETNAME' locally as
+ *
+ * #define GETSETNAME(op, name) foo##op##_##func
+ *
+ * around the get/set table.
+ */
+#define GET(func, doc) \
+ { #func, GETSETNAME(get, func), 0, doc },
+#define GETSET(func, doc) \
+ { #func, GETSETNAME(get, func), GETSETNAME(set, func), doc },
+
+/* Convenience wrapper for filling in `PyMemberDef' tables. Define
+ * `MEMBERSTRUCT' locally as
+ *
+ * #define MEMBERSTRUCT foo_pyobj
+ *
+ * around the member table.
+ */
+#define MEMBER(name, ty, f, doc) \
+ { #name, ty, offsetof(MEMBERSTRUCT, name), f, doc },
+
+/*----- Populating modules ------------------------------------------------*/
+
+extern PyObject *modname;
+ /* The overall module name. Set this with `PyString_FromString'. */
+
+extern PyObject *home_module;
+ /* The overall module object. */
+
+extern PyObject *mkexc(PyObject */*mod*/, PyObject */*base*/,
+ const char */*name*/, PyMethodDef */*methods*/);
+ /* Make and return an exception class called NAME, which will end up in
+ * module MOD (though it is not added at this time). The new class is a
+ * subclass of BASE. Attach the METHODS to it.
+ */
+
+#define INSERT(name, ob) do { \
+ PyObject *_o = (PyObject *)(ob); \
+ Py_INCREF(_o); \
+ PyModule_AddObject(mod, name, _o); \
+} while (0)
+ /* Insert a Python object OB into the module `mod' under the given NAME. */
+
+/* Numeric constants. */
+struct nameval { const char *name; unsigned f; unsigned long value; };
+#define CF_SIGNED 1u
+extern void setconstants(PyObject *, const struct nameval *);
+
+#define INSEXC(name, var, base, meth) \
+ INSERT(name, var = mkexc(mod, base, name, meth))
+ /* Insert an exception class into the module `mod'; other arguments are as
+ * for `mkexc'.
+ */
+
+/*----- Submodules --------------------------------------------------------*
+ *
+ * It's useful to split the Python module up into multiple source files, and
+ * have each one contribute its definitions into the main module.
+ *
+ * Define a list-macro `MODULES' in the master header file naming the
+ * submodules to be processed, and run
+ *
+ * MODULES(DECLARE_MODINIT)
+ *
+ * to declare the interface functions.
+ *
+ * Each submodule FOO defines two functions: `FOO_pyinit' initializes types
+ * (see `INITTYPE' above) and accumulates methods (`addmethods' below), while
+ * `FOO_pyinsert' populates the module with additional definitions
+ * (especially types, though also constants).
+ *
+ * The top-level module initialization should call `INIT_MODULES' before
+ * creating the Python module, and `INSERT_MODULES' afterwards to make
+ * everything work.
+ */
+
+extern void addmethods(const PyMethodDef *);
+extern PyMethodDef *donemethods(void);
+ /* Accumulate method-table fragments, and return the combined table of all
+ * of the fragments.
+ */
+
+#define DECLARE_MODINIT(m) \
+ extern void m##_pyinit(void); \
+ extern void m##_pyinsert(PyObject *);
+ /* Declare submodule interface functions. */
+
+#define DOMODINIT(m) m##_pyinit();
+#define DOMODINSERT(m) m##_pyinsert(mod);
+#define INIT_MODULES do { MODULES(DOMODINIT) } while (0)
+#define INSERT_MODULES do { MODULES(DOMODINSERT) } while (0)
+ /* Top-level dispatch to the various submodules. */
+
+/*----- Generic mapping support -------------------------------------------*/
+
+/* Mapping methods. */
+#define GMAP_METH(func, doc) { #func, gmapmeth_##func, METH_VARARGS, doc },
+#define GMAP_KWMETH(func, doc) \
+ { #func, (PyCFunction)gmapmeth_##func, METH_VARARGS|METH_KEYWORDS, doc },
+#define GMAP_METHDECL(func, doc) \
+ extern PyObject *gmapmeth_##func(PyObject *, PyObject *);
+#define GMAP_KWMETHDECL(func, doc) \
+ extern PyObject *gmapmeth_##func(PyObject *, PyObject *, PyObject *);
+
+#define GMAP_DOROMETHODS(METH, KWMETH) \
+ METH (has_key, "D.has_key(KEY) -> BOOL") \
+ METH (keys, "D.keys() -> LIST") \
+ METH (values, "D.values() -> LIST") \
+ METH (items, "D.items() -> LIST") \
+ METH (iterkeys, "D.iterkeys() -> ITER") \
+ METH (itervalues, "D.itervalues() -> ITER") \
+ METH (iteritems, "D.iteritems() -> ITER") \
+ KWMETH(get, "D.get(KEY, [default = None]) -> VALUE")
+
+#define GMAP_DOMETHODS(METH, KWMETH) \
+ GMAP_DOROMETHODS(METH, KWMETH) \
+ METH (clear, "D.clear()") \
+ KWMETH(setdefault, "D.setdefault(K, [default = None]) -> VALUE") \
+ KWMETH(pop, "D.pop(KEY, [default = <error>]) -> VALUE") \
+ METH (popitem, "D.popitem() -> (KEY, VALUE)") \
+ METH (update, "D.update(MAP)")
+
+GMAP_DOMETHODS(GMAP_METHDECL, GMAP_KWMETHDECL)
+#define GMAP_ROMETHODS GMAP_DOROMETHODS(GMAP_METH, GMAP_KWMETH)
+#define GMAP_METHODS GMAP_DOMETHODS(GMAP_METH, GMAP_KWMETH)
+
+/* Mapping protocol implementation. */
+extern Py_ssize_t gmap_pysize(PyObject *); /* for `mp_length' */
+extern PySequenceMethods gmap_pysequence; /* for `tp_as_sequence' */
+extern PyMethodDef gmap_pymethods[]; /* all the standard methods */
+
+/*----- That's all, folks -------------------------------------------------*/
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif