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