chiark / gitweb /
f8f821a92099a848b5c2d70e3f699a97725d44b5
[catacomb-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 /*----- Python version compatibility hacks --------------------------------*/
66
67 /* The handy `Py_TYPE' and `Py_SIZE' macros turned up in 2.6.  Define them if
68  * they're not already here.
69  */
70 #ifndef Py_TYPE
71 #  define Py_TYPE(obj) (((PyObject *)(obj))->ob_type)
72 #endif
73 #ifndef Py_SIZE
74 #  define Py_SIZE(obj) (((PyVarObject *)(obj))->ob_size)
75 #endif
76
77 /* Python 3 added internal structure to the various object headers, and
78  * defined a new macro `PyVarObject_HEAD_INIT' to initialize variable-length
79  * static instances correctly.  Define it if it's not already here.
80  */
81 #ifndef PyVarObject_HEAD_INIT
82 #  define PyVarObject_HEAD_INIT(super, sz) PyObject_HEAD_INIT(super) sz,
83 #endif
84
85 /*----- Utilities for returning values and exceptions ---------------------*/
86
87 /* Returning values. */
88 #define RETURN_OBJ(obj) do { Py_INCREF(obj); return (obj); } while (0)
89 #define RETURN_NONE RETURN_OBJ(Py_None)
90 #define RETURN_NOTIMPL RETURN_OBJ(Py_NotImplemented)
91 #define RETURN_TRUE RETURN_OBJ(Py_True)
92 #define RETURN_FALSE RETURN_OBJ(Py_False)
93 #define RETURN_ME RETURN_OBJ(me)
94
95 /* Returning exceptions.  (Note that `KeyError' is `MAPERR' here, because
96  * Catacomb has its own kind of `KeyError'.)
97  */
98 #define EXCERR(exc, str) do {                                           \
99   PyErr_SetString(exc, str);                                            \
100   goto end;                                                             \
101 } while (0)
102 #define VALERR(str) EXCERR(PyExc_ValueError, str)
103 #define OVFERR(str) EXCERR(PyExc_OverflowError, str)
104 #define TYERR(str) EXCERR(PyExc_TypeError, str)
105 #define IXERR(str) EXCERR(PyExc_IndexError, str)
106 #define ZDIVERR(str) EXCERR(PyExc_ZeroDivisionError, str)
107 #define SYSERR(str) EXCERR(PyExc_SystemError, str)
108 #define NIERR(str) EXCERR(PyExc_NotImplementedError, str)
109 #define MAPERR(idx) do {                                                \
110   PyErr_SetObject(PyExc_KeyError, idx);                                 \
111   goto end;                                                             \
112 } while (0)
113 #define OSERR(name) do {                                                \
114   PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);                  \
115   goto end;                                                             \
116 } while (0)
117
118 /* Saving and restoring exceptions. */
119 struct excinfo { PyObject *ty, *val, *tb; };
120 #define EXCINFO_INIT { 0, 0, 0 }
121 #define INIT_EXCINFO(exc) do {                                          \
122   struct excinfo *_exc = (exc); _exc->ty = _exc->val = _exc->tb = 0;    \
123 } while (0)
124 #define RELEASE_EXCINFO(exc) do {                                       \
125   struct excinfo *_exc = (exc);                                         \
126   Py_XDECREF(_exc->ty);  _exc->ty  = 0;                                 \
127   Py_XDECREF(_exc->val); _exc->val = 0;                                 \
128   Py_XDECREF(_exc->tb);  _exc->tb  = 0;                                 \
129 } while (0)
130 #define STASH_EXCINFO(exc) do {                                         \
131   struct excinfo *_exc = (exc);                                         \
132   PyErr_Fetch(&_exc->ty, &_exc->val, &_exc->tb);                        \
133   PyErr_NormalizeException(&_exc->ty, &_exc->val, &_exc->tb);           \
134 } while (0)
135 #define RESTORE_EXCINFO(exc) do {                                       \
136   struct excinfo *_exc = (exc);                                         \
137   PyErr_Restore(_exc->ty, _exc->val, _exc->tb);                         \
138   _exc->ty = _exc->val = _exc->tb = 0;                                  \
139 } while (0)
140 extern void report_lost_exception(struct excinfo *, const char *, ...);
141 extern void report_lost_exception_v(struct excinfo *, const char *, va_list);
142 extern void stash_exception(struct excinfo *, const char *, ...);
143 extern void restore_exception(struct excinfo *, const char *, ...);
144
145 /*----- Conversions -------------------------------------------------------*/
146
147 /* Define an input conversion (`O&') function: check that the object has
148  * Python type TY, and extract a C pointer to CTY by calling EXT on the
149  * object (which may well be a macro).
150  */
151 #define CONVFUNC(ty, cty, ext)                                          \
152   int conv##ty(PyObject *o, void *p)                                    \
153   {                                                                     \
154     if (!PyObject_TypeCheck(o, ty##_pytype))                            \
155       TYERR("wanted a " #ty);                                           \
156     *(cty *)p = ext(o);                                                 \
157     return (1);                                                         \
158   end:                                                                  \
159     return (0);                                                         \
160   }
161
162 /* Input conversion functions for standard kinds of objects, with overflow
163  * checking where applicable.
164  */
165 extern int convulong(PyObject *, void *); /* unsigned long */
166 extern int convuint(PyObject *, void *); /* unsigned int */
167 extern int convszt(PyObject *, void *); /* size_t */
168 extern int convbool(PyObject *, void *); /* bool */
169
170 /* Output conversions. */
171 extern PyObject *getbool(int);          /* bool */
172 extern PyObject *getulong(unsigned long); /* any kind of unsigned integer */
173
174 /*----- Miscellaneous utilities -------------------------------------------*/
175
176 #define FREEOBJ(obj) (Py_TYPE(obj)->tp_free((PyObject *)(obj)))
177   /* Actually free OBJ, e.g., in a deallocation function. */
178
179 extern PyObject *abstract_pynew(PyTypeObject *, PyObject *, PyObject *);
180   /* A `tp_new' function which refuses to make the object. */
181
182 #ifndef CONVERT_CAREFULLY
183 #  define CONVERT_CAREFULLY(newty, expty, obj)                          \
184      (!sizeof(*(expty *)0 = (obj)) + (/*unconst*/ newty)(obj))
185   /* Convert OBJ to the type NEWTY, having previously checked that it is
186    * convertible to the expected type EXPTY.
187    *
188    * Because of the way we set up types, we can make many kinds of tables be
189    * `const' which can't usually be so (because Python will want to fiddle
190    * with their reference counts); and, besides, Python's internals are
191    * generally quite bad at being `const'-correct about tables.  One frequent
192    * application of this macro, then, is in removing `const' from a type
193    * without sacrificing all type safety.  The other common use is in
194    * checking that method function types match up with the signatures
195    * expected in their method definitions.
196    */
197 #endif
198
199 #define KWLIST CONVERT_CAREFULLY(char **, const char *const *, kwlist)
200   /* Strip `const' qualifiers from the keyword list `kwlist'.  Useful when
201    * calling `PyArg_ParseTupleAndKeywords', which isn't `const'-correct.
202    */
203
204 /*----- Type definitions --------------------------------------------------*
205  *
206  * Pyke types are defined in a rather unusual way.
207  *
208  * The main code defines a `type skeleton' of type `PyTypeObject',
209  * conventionally named `TY_pytype_skel'.  Unlike typical Python type
210  * definitions in extensions, this can (and should) be read-only.  Also,
211  * there's no point in setting the `tp_base' pointer here, because the actual
212  * runtime base type object won't, in general, be known at compile time.
213  * Instead, the type skeletons are converted into Python `heap types' by the
214  * `INITTYPE' macro.  The main difference is that Python code can add
215  * attributes to heap types, and we make extensive use of this ability.
216  */
217
218 extern void *newtype(PyTypeObject */*meta*/,
219                      const PyTypeObject */*skel*/, const char */*name*/);
220   /* Make and return a new Python type object, of type META (typically
221    * `PyType_Type', but may be a subclass), filled in from the skeleton SKEL
222    * (null to inherit everything), and named NAME.  The caller can mess with
223    * the type object further at this time: call `typeready' when it's set up
224    * properly.
225    */
226
227 extern void typeready(PyTypeObject *);
228   /* The type object is now ready to be used. */
229
230 extern PyTypeObject *inittype(const PyTypeObject */*skel*/,
231                               PyTypeObject */*base*/,
232                               PyTypeObject */*meta*/);
233   /* All-in-one function to construct a working type from a type skeleton
234    * SKEL, with known base type BASE (null for `object') and metaclass.
235    */
236
237 /* Alias for built-in types, to fit in with Pyke naming conventions. */
238 #define root_pytype 0
239 #define type_pytype &PyType_Type
240
241 #define INITTYPE_META(ty, base, meta) do {                              \
242   ty##_pytype = inittype(&ty##_pytype_skel, base##_pytype, meta##_pytype); \
243 } while (0)
244 #define INITTYPE(ty, base) INITTYPE_META(ty, base, type)
245   /* Macros to initialize a type from its skeleton. */
246
247 /* Macros for filling in `PyMethodDef' tables, ensuring that functions have
248  * the expected signatures.
249  */
250 #define STD_METHOD(decor, func, flags, doc)                             \
251   { #func, decor(func), METH_VARARGS | flags, doc },
252 #define KEYWORD_METHOD(decor, func, flags, doc)                         \
253   { #func,                                                              \
254     CONVERT_CAREFULLY(PyCFunction, PyCFunctionWithKeywords, decor(func)), \
255     METH_VARARGS | METH_KEYWORDS | flags,                               \
256     doc },
257 #define NOARG_METHOD(decor, func, flags, doc)                           \
258   { #func,                                                              \
259     CONVERT_CAREFULLY(PyCFunction, PyNoArgsFunction, decor(func)),      \
260     METH_NOARGS | flags,                                                \
261     doc },
262
263 /* Convenience wrappers for filling in `PyMethodDef' tables, following
264  * Pyke naming convention.  Define `METHNAME' locally as
265  *
266  *      #define METHNAME(name) foometh_##func
267  *
268  * around the method table.
269  */
270 #define METH(func, doc) STD_METHOD(METHNAME, func, 0, doc)
271 #define KWMETH(func, doc) KEYWORD_METHOD(METHNAME, func, 0, doc)
272 #define NAMETH(func, doc) NOARG_METHOD(METHNAME, func, 0, doc)
273 #define CMTH(func, doc) STD_METHOD(METHNAME, func, METH_CLASS, doc)
274 #define KWCMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_CLASS, doc)
275 #define NACMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_CLASS, doc)
276 #define SMTH(func, doc) STD_METHOD(METHNAME, func, METH_STATIC, doc)
277 #define KWSMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_STATIC, doc)
278 #define NASMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_STATIC, doc)
279
280 /* Convenience wrappers for filling in `PyGetSetDef' tables, following Pyke
281  * naming convention.  Define `GETSETNAME' locally as
282  *
283  *      #define GETSETNAME(op, name) foo##op##_##func
284  *
285  * around the get/set table.
286  */
287 #define GET(func, doc)                                                  \
288   { #func, GETSETNAME(get, func), 0, doc },
289 #define GETSET(func, doc)                                               \
290   { #func, GETSETNAME(get, func), GETSETNAME(set, func), doc },
291
292 /* Convenience wrappers for filling in `PyMemberDef' tables.  Define
293  * `MEMBERSTRUCT' locally as
294  *
295  *      #define MEMBERSTRUCT foo_pyobj
296  *
297  * around the member table.
298  */
299 #define MEMRNM(name, ty, mem, f, doc)                                   \
300   { #name, ty, offsetof(MEMBERSTRUCT, mem), f, doc },
301 #define MEMBER(name, ty, f, doc) MEMRNM(name, ty, name, f, doc)
302
303 /* Wrappers for filling in pointers in a `PyTypeObject' structure, (a)
304  * following Pyke naming convention, and (b) stripping `const' from the types
305  * without losing type safety.
306  */
307 #define UNCONST_TYPE_SLOT(type, suffix, op, ty)                         \
308   CONVERT_CAREFULLY(type *, const type *, op ty##_py##suffix)
309 #define PYGETSET(ty) UNCONST_TYPE_SLOT(PyGetSetDef, getset, NOTHING, ty)
310 #define PYMETHODS(ty) UNCONST_TYPE_SLOT(PyMethodDef, methods, NOTHING, ty)
311 #define PYMEMBERS(ty) UNCONST_TYPE_SLOT(PyMemberDef, members, NOTHING, ty)
312 #define PYNUMBER(ty) UNCONST_TYPE_SLOT(PyNumberMethods, number, &, ty)
313 #define PYSEQUENCE(ty) UNCONST_TYPE_SLOT(PySequenceMethods, sequence, &, ty)
314 #define PYMAPPING(ty) UNCONST_TYPE_SLOT(PyMappingMethods, mapping, &, ty)
315 #define PYBUFFER(ty) UNCONST_TYPE_SLOT(PyBufferProcs, buffer, &, ty)
316
317 /*----- Populating modules ------------------------------------------------*/
318
319 extern PyObject *modname;
320   /* The overall module name.  Set this with `PyString_FromString'. */
321
322 extern PyObject *home_module;
323   /* The overall module object. */
324
325 extern PyObject *mkexc(PyObject */*mod*/, PyObject */*base*/,
326                        const char */*name*/, const PyMethodDef */*methods*/);
327   /* Make and return an exception class called NAME, which will end up in
328    * module MOD (though it is not added at this time).  The new class is a
329    * subclass of BASE.  Attach the METHODS to it.
330    */
331
332 #define INSERT(name, ob) do {                                           \
333   PyObject *_o = (PyObject *)(ob);                                      \
334   Py_INCREF(_o);                                                        \
335   PyModule_AddObject(mod, name, _o);                                    \
336 } while (0)
337   /* Insert a Python object OB into the module `mod' under the given NAME. */
338
339 /* Numeric constants. */
340 struct nameval { const char *name; unsigned f; unsigned long value; };
341 #define CF_SIGNED 1u
342 extern void setconstants(PyObject *, const struct nameval *);
343 #define CONST(x) { #x, 0, x }
344 #define CONSTFLAG(f, x) { #x, f, x }
345
346 #define INSEXC(name, var, base, meth)                                   \
347   INSERT(name, var = mkexc(mod, base, name, meth))
348   /* Insert an exception class into the module `mod'; other arguments are as
349    * for `mkexc'.
350    */
351
352 /*----- Submodules --------------------------------------------------------*
353  *
354  * It's useful to split the Python module up into multiple source files, and
355  * have each one contribute its definitions into the main module.
356  *
357  * Define a list-macro `MODULES' in the master header file naming the
358  * submodules to be processed, and run
359  *
360  *      MODULES(DECLARE_MODINIT)
361  *
362  * to declare the interface functions.
363  *
364  * Each submodule FOO defines two functions: `FOO_pyinit' initializes types
365  * (see `INITTYPE' above) and accumulates methods (`addmethods' below), while
366  * `FOO_pyinsert' populates the module with additional definitions
367  * (especially types, though also constants).
368  *
369  * The top-level module initialization should call `INIT_MODULES' before
370  * creating the Python module, and `INSERT_MODULES' afterwards to make
371  * everything work.
372  */
373
374 extern void addmethods(const PyMethodDef *);
375 extern PyMethodDef *donemethods(void);
376   /* Accumulate method-table fragments, and return the combined table of all
377    * of the fragments.
378    */
379
380 #define DECLARE_MODINIT(m)                                              \
381   extern void m##_pyinit(void);                                         \
382   extern void m##_pyinsert(PyObject *);
383   /* Declare submodule interface functions. */
384
385 #define DOMODINIT(m) m##_pyinit();
386 #define DOMODINSERT(m) m##_pyinsert(mod);
387 #define INIT_MODULES do { MODULES(DOMODINIT) } while (0)
388 #define INSERT_MODULES do { MODULES(DOMODINSERT) } while (0)
389   /* Top-level dispatch to the various submodules. */
390
391 /*----- Generic mapping support -------------------------------------------*/
392
393 /* Operations table.  ME is the mapping object throughout. */
394 typedef struct gmap_ops {
395   size_t isz;                           /* iterator size */
396
397   void *(*lookup)(PyObject *me, PyObject *key, unsigned *f);
398     /* Lookup the KEY.  If it is found, return an entry pointer for it; if F
399      * is not null, set *F nonzero.  Otherwise, if F is null, return a null
400      * pointer (without setting a pending exception); if F is not null, then
401      * set *F zero and return a fresh entry pointer.  Return null on a Python
402      * exception (the caller will notice the difference.)
403      */
404
405   void (*iter_init)(PyObject *me, void *i);
406     /* Initialize an iterator at I. */
407
408   void *(*iter_next)(PyObject *me, void *i);
409     /* Return an entry pointer for a different item, or null if all have been
410      * visited.
411      */
412
413   PyObject *(*entry_key)(PyObject *me, void *e);
414     /* Return the key object for a mapping entry. */
415
416   PyObject *(*entry_value)(PyObject *me, void *e);
417     /* Return the value object for a mapping entry. */
418
419   int (*set_entry)(PyObject *me, void *e, PyObject *val);
420     /* Modify the entry by storing VAL in its place.  Return 0 on success,
421      * or -1 on a Python error.
422      */
423
424   int (*del_entry)(PyObject *me, void *e);
425     /* Delete the entry.  (It may be necessary to delete a freshly allocated
426      * entry, e.g., if `set_entry' failed.)  Return 0 on success, or -1 on a
427      * Python error.
428      */
429 } gmap_ops;
430
431 /* The intrusion at the head of a mapping object. */
432 #define GMAP_PYOBJ_HEAD                                                 \
433   PyObject_HEAD                                                         \
434   const gmap_ops *gmops;
435
436 typedef struct gmap_pyobj {
437   GMAP_PYOBJ_HEAD
438 } gmap_pyobj;
439 #define GMAP_OPS(obj) (((gmap_pyobj *)(obj))->gmops)
440   /* Discover the operations from a mapping object. */
441
442 /* Mapping methods. */
443 #define GMAP_METMNAME(func) gmapmeth_##func
444 #define GMAP_METH(func, doc) STD_METHOD(GMAP_METMNAME, func, 0, doc)
445 #define GMAP_KWMETH(func, doc) KEYWORD_METHOD(GMAP_METMNAME, func, 0, doc)
446 #define GMAP_NAMETH(func, doc) NOARG_METHOD(GMAP_METMNAME, func, 0, doc)
447 #define GMAP_METHDECL(func, doc)                                        \
448   extern PyObject *gmapmeth_##func(PyObject *, PyObject *);
449 #define GMAP_KWMETHDECL(func, doc)                                      \
450   extern PyObject *gmapmeth_##func(PyObject *, PyObject *, PyObject *);
451 #define GMAP_NAMETHDECL(func, doc)                                      \
452   extern PyObject *gmapmeth_##func(PyObject *);
453
454 #define GMAP_DOROMETHODS(METH, KWMETH, NAMETH)                          \
455   METH  (has_key,       "D.has_key(KEY) -> BOOL")                       \
456   NAMETH(keys,          "D.keys() -> LIST")                             \
457   NAMETH(values,        "D.values() -> LIST")                           \
458   NAMETH(items,         "D.items() -> LIST")                            \
459   NAMETH(iterkeys,      "D.iterkeys() -> ITER")                         \
460   NAMETH(itervalues,    "D.itervalues() -> ITER")                       \
461   NAMETH(iteritems,     "D.iteritems() -> ITER")                        \
462   KWMETH(get,           "D.get(KEY, [default = None]) -> VALUE")
463
464 #define GMAP_DOMETHODS(METH, KWMETH, NAMETH)                            \
465   GMAP_DOROMETHODS(METH, KWMETH, NAMETH)                                \
466   NAMETH(clear,         "D.clear()")                                    \
467   KWMETH(setdefault,    "D.setdefault(K, [default = None]) -> VALUE")   \
468   KWMETH(pop,           "D.pop(KEY, [default = <error>]) -> VALUE")     \
469   NAMETH(popitem,       "D.popitem() -> (KEY, VALUE)")                  \
470   KWMETH(update,        "D.update(MAP)")
471
472 GMAP_DOMETHODS(GMAP_METHDECL, GMAP_KWMETHDECL, GMAP_NAMETHDECL)
473 #define GMAP_ROMETHODS GMAP_DOROMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
474 #define GMAP_METHODS GMAP_DOMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
475
476 /* Mapping protocol implementation. */
477 extern Py_ssize_t gmap_pysize(PyObject *); /* for `mp_length' */
478 extern PyObject *gmap_pyiter(PyObject *); /* for `tp_iter' */
479 extern PyObject *gmap_pylookup(PyObject *, PyObject *); /* for `mp_subscript' */
480 extern int gmap_pystore(PyObject *, PyObject *, PyObject *); /* for `mp_ass_subscript' */
481 extern int gmap_pyhaskey(PyObject *, PyObject *); /* for `sq_contains' */
482 extern const PySequenceMethods gmap_pysequence; /* for `tp_as_sequence' */
483 extern const PyMethodDef gmapro_pymethods[]; /* read-only methods */
484 extern const PyMethodDef gmap_pymethods[]; /* all the standard methods */
485
486 /*----- That's all, folks -------------------------------------------------*/
487
488 #ifdef __cplusplus
489   }
490 #endif
491
492 #endif