chiark / gitweb /
pyke/, ...: Extract utilities into a sort-of reusable library.
[mLib-python] / pyke.h
1 /* -*-c-*-
2  *
3  * Pyke: the Python Kit for Extensions
4  *
5  * (c) 2019 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Pyke: the Python Kit for Extensions.
11  *
12  * Pyke is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 2 of the License, or (at your
15  * option) any later version.
16  *
17  * Pyke is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with Pyke.  If not, write to the Free Software Foundation, Inc.,
24  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 #ifndef PYKE_H
28 #define PYKE_H
29
30 #ifdef __cplusplus
31   extern "C" {
32 #endif
33
34 /*----- Header files ------------------------------------------------------*/
35
36 #define PY_SSIZE_T_CLEAN
37
38 #include <Python.h>
39 #include <structmember.h>
40
41 /*----- Other preliminaries -----------------------------------------------*/
42
43 #define NOTHING
44 #define COMMA ,
45
46 /*----- Symbol visibility -------------------------------------------------*
47  *
48  * This library is very messy regarding symbol namespace.  Keep this mess
49  * within our shared-object.
50  */
51
52 #define GOBBLE_SEMI extern int notexist
53 #if defined(__GNUC__) && defined(__ELF__)
54 #  define PRIVATE_SYMBOLS _Pragma("GCC visibility push(hidden)") GOBBLE_SEMI
55 #  define PUBLIC_SYMBOLS _Pragma("GCC visibility pop") GOBBLE_SEMI
56 #  define EXPORT __attribute__((__visibility__("default")))
57 #else
58 #  define PRIVATE_SYMBOLS GOBBLE_SEMI
59 #  define PUBLIC_SYMBOLS GOBBLE_SEMI
60 #  define EXPORT
61 #endif
62
63 PRIVATE_SYMBOLS;
64
65 /*----- Utilities for returning values and exceptions ---------------------*/
66
67 /* Returning values. */
68 #define RETURN_OBJ(obj) do { Py_INCREF(obj); return (obj); } while (0)
69 #define RETURN_NONE RETURN_OBJ(Py_None)
70 #define RETURN_NOTIMPL RETURN_OBJ(Py_NotImplemented)
71 #define RETURN_TRUE RETURN_OBJ(Py_True)
72 #define RETURN_FALSE RETURN_OBJ(Py_False)
73 #define RETURN_ME RETURN_OBJ(me)
74
75 /* Returning exceptions.  (Note that `KeyError' is `MAPERR' here, because
76  * Catacomb has its own kind of `KeyError'.)
77  */
78 #define EXCERR(exc, str) do {                                           \
79   PyErr_SetString(exc, str);                                            \
80   goto end;                                                             \
81 } while (0)
82 #define VALERR(str) EXCERR(PyExc_ValueError, str)
83 #define OVFERR(str) EXCERR(PyExc_OverflowError, str)
84 #define TYERR(str) EXCERR(PyExc_TypeError, str)
85 #define IXERR(str) EXCERR(PyExc_IndexError, str)
86 #define ZDIVERR(str) EXCERR(PyExc_ZeroDivisionError, str)
87 #define SYSERR(str) EXCERR(PyExc_SystemError, str)
88 #define NIERR(str) EXCERR(PyExc_NotImplementedError, str)
89 #define INDEXERR(idx) do {                                              \
90   PyErr_SetObject(PyExc_KeyError, idx);                                 \
91   goto end;                                                             \
92 } while (0)
93 #define OSERR(name) do {                                                \
94   PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);                  \
95   goto end;                                                             \
96 } while (0)
97
98 /* Saving and restoring exceptions. */
99 struct excinfo { PyObject *ty, *val, *tb; };
100 #define EXCINFO_INIT { 0, 0, 0 }
101 #define INIT_EXCINFO(exc) do {                                          \
102   struct excinfo *_exc = (exc); _exc->ty = _exc->val = _exc->tb = 0;    \
103 } while (0)
104 #define RELEASE_EXCINFO(exc) do {                                       \
105   struct excinfo *_exc = (exc);                                         \
106   Py_XDECREF(_exc->ty);  _exc->ty  = 0;                                 \
107   Py_XDECREF(_exc->val); _exc->val = 0;                                 \
108   Py_XDECREF(_exc->tb);  _exc->tb  = 0;                                 \
109 } while (0)
110 #define STASH_EXCINFO(exc) do {                                         \
111   struct excinfo *_exc = (exc);                                         \
112   PyErr_Fetch(&_exc->ty, &_exc->val, &_exc->tb);                        \
113   PyErr_NormalizeException(&_exc->ty, &_exc->val, &_exc->tb);           \
114 } while (0)
115 #define RESTORE_EXCINFO(exc) do {                                       \
116   struct excinfo *_exc = (exc);                                         \
117   PyErr_Restore(_exc->ty, _exc->val, _exc->tb);                         \
118   _exc->ty = _exc->val = _exc->tb = 0;                                  \
119 } while (0)
120 extern void report_lost_exception(struct excinfo *, const char *, ...);
121 extern void report_lost_exception_v(struct excinfo *, const char *, va_list);
122 extern void stash_exception(struct excinfo *, const char *, ...);
123 extern void restore_exception(struct excinfo *, const char *, ...);
124
125 /*----- Conversions -------------------------------------------------------*/
126
127 /* Define an input conversion (`O&') function: check that the object has
128  * Python type TY, and extract a C pointer to CTY by calling EXT on the
129  * object (which may well be a macro).
130  */
131 #define CONVFUNC(ty, cty, ext)                                          \
132   int conv##ty(PyObject *o, void *p)                                    \
133   {                                                                     \
134     if (!PyObject_TypeCheck(o, ty##_pytype))                            \
135       TYERR("wanted a " #ty);                                           \
136     *(cty *)p = ext(o);                                                 \
137     return (1);                                                         \
138   end:                                                                  \
139     return (0);                                                         \
140   }
141
142 /* Input conversion functions for standard kinds of objects, with overflow
143  * checking where applicable.
144  */
145 extern int convulong(PyObject *, void *); /* unsigned long */
146 extern int convuint(PyObject *, void *); /* unsigned int */
147 extern int convszt(PyObject *, void *); /* size_t */
148 extern int convbool(PyObject *, void *); /* bool */
149
150 /* Output conversions. */
151 extern PyObject *getbool(int);          /* bool */
152 extern PyObject *getulong(unsigned long); /* any kind of unsigned integer */
153
154 /*----- Miscellaneous utilities -------------------------------------------*/
155
156 #define FREEOBJ(obj)                                                    \
157   (((PyObject *)(obj))->ob_type->tp_free((PyObject *)(obj)))
158   /* Actually free OBJ, e.g., in a deallocation function. */
159
160 extern PyObject *abstract_pynew(PyTypeObject *, PyObject *, PyObject *);
161   /* A `tp_new' function which refuses to make the object. */
162
163 #define KWLIST (/*unconst*/ char **)kwlist
164   /* Strip `const' qualifiers from the keyword list `kwlist'.  Useful when
165    * calling `PyArg_ParseTupleAndKeywords', which isn't `const'-correct.
166    */
167
168 /*----- Type definitions --------------------------------------------------*
169  *
170  * Pyke types are defined in a rather unusual way.
171  *
172  * The main code defines a `type skeleton' of type `PyTypeObject',
173  * conventionally named `TY_pytype_skel'.  Unlike typical Python type
174  * definitions in extensions, this can (and should) be read-only.  Also,
175  * there's no point in setting the `tp_base' pointer here, because the actual
176  * runtime base type object won't, in general, be known at compile time.
177  * Instead, the type skeletons are converted into Python `heap types' by the
178  * `INITTYPE' macro.  The main difference is that Python code can add
179  * attributes to heap types, and we make extensive use of this ability.
180  */
181
182 extern void *newtype(PyTypeObject */*meta*/,
183                      const PyTypeObject */*skel*/, const char */*name*/);
184   /* Make and return a new Python type object, of type META (typically
185    * `PyType_Type', but may be a subclass), filled in from the skeleton SKEL
186    * (null to inherit everything), and named NAME.  The caller can mess with
187    * the type object further at this time: call `typeready' when it's set up
188    * properly.
189    */
190
191 extern void typeready(PyTypeObject *);
192   /* The type object is now ready to be used. */
193
194 extern PyTypeObject *inittype(PyTypeObject */*skel*/,
195                               PyTypeObject */*meta*/);
196   /* All-in-one function to construct a working type from a type skeleton
197    * SKEL, with metaclass META.  The caller is expected to have filled in the
198    * direct superclass in SKEL->tp_base.
199    */
200
201 /* Alias for built-in types, to fit in with Pyke naming conventions. */
202 #define root_pytype 0
203 #define type_pytype &PyType_Type
204
205 #define INITTYPE_META(ty, base, meta) do {                              \
206   ty##_pytype_skel.tp_base = base##_pytype;                             \
207   ty##_pytype = inittype(&ty##_pytype_skel, meta##_pytype);             \
208 } while (0)
209 #define INITTYPE(ty, base) INITTYPE_META(ty, base, type)
210   /* Macros to initialize a type from its skeleton. */
211
212 /* Convenience wrappers for filling in `PyMethodDef' tables, following
213  * Pyke naming convention.  Define `METHNAME' locally as
214  *
215  *      #define METHNAME(name) foometh_##func
216  *
217  * around the method table.
218  */
219 #define METH(func, doc)                                                 \
220   { #func, METHNAME(func), METH_VARARGS, doc },
221 #define KWMETH(func, doc)                                               \
222   { #func, (PyCFunction)METHNAME(func),                                 \
223     METH_VARARGS | METH_KEYWORDS, doc },
224
225 /* Convenience wrappers for filling in `PyGetSetDef' tables, following Pyke
226  * naming convention.  Define `GETSETNAME' locally as
227  *
228  *      #define GETSETNAME(op, name) foo##op##_##func
229  *
230  * around the get/set table.
231  */
232 #define GET(func, doc)                                                  \
233   { #func, GETSETNAME(get, func), 0, doc },
234 #define GETSET(func, doc)                                               \
235   { #func, GETSETNAME(get, func), GETSETNAME(set, func), doc },
236
237 /* Convenience wrapper for filling in `PyMemberDef' tables.  Define
238  * `MEMBERSTRUCT' locally as
239  *
240  *      #define MEMBERSTRUCT foo_pyobj
241  *
242  * around the member table.
243  */
244 #define MEMBER(name, ty, f, doc)                                        \
245   { #name, ty, offsetof(MEMBERSTRUCT, name), f, doc },
246
247 /*----- Populating modules ------------------------------------------------*/
248
249 extern PyObject *modname;
250   /* The overall module name.  Set this with `PyString_FromString'. */
251
252 extern PyObject *home_module;
253   /* The overall module object. */
254
255 extern PyObject *mkexc(PyObject */*mod*/, PyObject */*base*/,
256                        const char */*name*/, PyMethodDef */*methods*/);
257   /* Make and return an exception class called NAME, which will end up in
258    * module MOD (though it is not added at this time).  The new class is a
259    * subclass of BASE.  Attach the METHODS to it.
260    */
261
262 #define INSERT(name, ob) do {                                           \
263   PyObject *_o = (PyObject *)(ob);                                      \
264   Py_INCREF(_o);                                                        \
265   PyModule_AddObject(mod, name, _o);                                    \
266 } while (0)
267   /* Insert a Python object OB into the module `mod' under the given NAME. */
268
269 /* Numeric constants. */
270 struct nameval { const char *name; unsigned f; unsigned long value; };
271 #define CF_SIGNED 1u
272 extern void setconstants(PyObject *, const struct nameval *);
273
274 #define INSEXC(name, var, base, meth)                                   \
275   INSERT(name, var = mkexc(mod, base, name, meth))
276   /* Insert an exception class into the module `mod'; other arguments are as
277    * for `mkexc'.
278    */
279
280 /*----- Submodules --------------------------------------------------------*
281  *
282  * It's useful to split the Python module up into multiple source files, and
283  * have each one contribute its definitions into the main module.
284  *
285  * Define a list-macro `MODULES' in the master header file naming the
286  * submodules to be processed, and run
287  *
288  *      MODULES(DECLARE_MODINIT)
289  *
290  * to declare the interface functions.
291  *
292  * Each submodule FOO defines two functions: `FOO_pyinit' initializes types
293  * (see `INITTYPE' above) and accumulates methods (`addmethods' below), while
294  * `FOO_pyinsert' populates the module with additional definitions
295  * (especially types, though also constants).
296  *
297  * The top-level module initialization should call `INIT_MODULES' before
298  * creating the Python module, and `INSERT_MODULES' afterwards to make
299  * everything work.
300  */
301
302 extern void addmethods(const PyMethodDef *);
303 extern PyMethodDef *donemethods(void);
304   /* Accumulate method-table fragments, and return the combined table of all
305    * of the fragments.
306    */
307
308 #define DECLARE_MODINIT(m)                                              \
309   extern void m##_pyinit(void);                                         \
310   extern void m##_pyinsert(PyObject *);
311   /* Declare submodule interface functions. */
312
313 #define DOMODINIT(m) m##_pyinit();
314 #define DOMODINSERT(m) m##_pyinsert(mod);
315 #define INIT_MODULES do { MODULES(DOMODINIT) } while (0)
316 #define INSERT_MODULES do { MODULES(DOMODINSERT) } while (0)
317   /* Top-level dispatch to the various submodules. */
318
319 /*----- Generic mapping support -------------------------------------------*/
320
321 /* Mapping methods. */
322 #define GMAP_METH(func, doc) { #func, gmapmeth_##func, METH_VARARGS, doc },
323 #define GMAP_KWMETH(func, doc)                                          \
324   { #func, (PyCFunction)gmapmeth_##func, METH_VARARGS|METH_KEYWORDS, doc },
325 #define GMAP_METHDECL(func, doc)                                        \
326   extern PyObject *gmapmeth_##func(PyObject *, PyObject *);
327 #define GMAP_KWMETHDECL(func, doc)                                      \
328   extern PyObject *gmapmeth_##func(PyObject *, PyObject *, PyObject *);
329
330 #define GMAP_DOROMETHODS(METH, KWMETH)                                  \
331   METH  (has_key,       "D.has_key(KEY) -> BOOL")                       \
332   METH  (keys,          "D.keys() -> LIST")                             \
333   METH  (values,        "D.values() -> LIST")                           \
334   METH  (items,         "D.items() -> LIST")                            \
335   METH  (iterkeys,      "D.iterkeys() -> ITER")                         \
336   METH  (itervalues,    "D.itervalues() -> ITER")                       \
337   METH  (iteritems,     "D.iteritems() -> ITER")                        \
338   KWMETH(get,           "D.get(KEY, [default = None]) -> VALUE")
339
340 #define GMAP_DOMETHODS(METH, KWMETH)                                    \
341   GMAP_DOROMETHODS(METH, KWMETH)                                        \
342   METH  (clear,         "D.clear()")                                    \
343   KWMETH(setdefault,    "D.setdefault(K, [default = None]) -> VALUE")   \
344   KWMETH(pop,           "D.pop(KEY, [default = <error>]) -> VALUE")     \
345   METH  (popitem,       "D.popitem() -> (KEY, VALUE)")                  \
346   METH  (update,        "D.update(MAP)")
347
348 GMAP_DOMETHODS(GMAP_METHDECL, GMAP_KWMETHDECL)
349 #define GMAP_ROMETHODS GMAP_DOROMETHODS(GMAP_METH, GMAP_KWMETH)
350 #define GMAP_METHODS GMAP_DOMETHODS(GMAP_METH, GMAP_KWMETH)
351
352 /* Mapping protocol implementation. */
353 extern Py_ssize_t gmap_pysize(PyObject *); /* for `mp_length' */
354 extern PySequenceMethods gmap_pysequence; /* for `tp_as_sequence' */
355 extern PyMethodDef gmap_pymethods[]; /* all the standard methods */
356
357 /*----- That's all, folks -------------------------------------------------*/
358
359 #ifdef __cplusplus
360   }
361 #endif
362
363 #endif