@@@ py_buffer/freebin wip
[catacomb-python] / pyke / pyke.h
CommitLineData
10e6f88a
MW
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
63PRIVATE_SYMBOLS;
64
2a448f86
MW
65/*----- Python version compatibility hacks --------------------------------*/
66
f7623015
MW
67/* Explicit version switching. */
68#if PY_VERSION_HEX >= 0x03000000
69# define PY3 1
70# define PY23(two, three) three
71#else
72# define PY2 1
73# define PY23(two, three) two
74#endif
75
2a448f86
MW
76/* The handy `Py_TYPE' and `Py_SIZE' macros turned up in 2.6. Define them if
77 * they're not already here.
78 */
79#ifndef Py_TYPE
80# define Py_TYPE(obj) (((PyObject *)(obj))->ob_type)
81#endif
82#ifndef Py_SIZE
83# define Py_SIZE(obj) (((PyVarObject *)(obj))->ob_size)
84#endif
85
591bf41b
MW
86/* Python 3 added internal structure to the various object headers, and
87 * defined a new macro `PyVarObject_HEAD_INIT' to initialize variable-length
88 * static instances correctly. Define it if it's not already here.
89 */
90#ifndef PyVarObject_HEAD_INIT
91# define PyVarObject_HEAD_INIT(super, sz) PyObject_HEAD_INIT(super) sz,
92#endif
93
f7623015
MW
94/* Python 3 doesn't have `int', only `long', even though it's called `int' at
95 * the Python level. Provide some obvious macros to fill in the gaps.
96 */
97#ifdef PY3
98# define PyInt_Check PyLong_Check
99# define PyInt_FromLong PyLong_FromLong
100# define PyInt_AS_LONG PyLong_AS_LONG
101# define PyInt_AsLong PyLong_AsLong
102# define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
103# define PyNumber_Int PyNumber_Long
104#endif
105
d6d78edc
MW
106/* Python 3.2 changed the type of hash values, so paper over this annoying
107 * difference.
108 */
109#if PY_VERSION_HEX < 0x03020000
110 typedef long Py_hash_t;
111#endif
112
f7623015
MW
113/* Python 3 always has the `CHECKTYPES' behaviour, and doesn't define the
114 * flag.
115 */
116#ifdef PY3
117# define Py_TPFLAGS_CHECKTYPES 0
118#endif
119
2135a6d3
MW
120/* Plain octet strings. Python 2 calls these `str', while Python 3 calls
121 * them `bytes'. We call them `bin' here, and define the following.
122 *
123 * * `BINOBJ' is the C type of a `bin' object.
124 * * `BIN_TYPE' is the Python `type' object for `bin'.
125 * * `BIN_CHECK(OBJ)' is true if OBJ is a `bin' object.
126 * * `BIN_PTR(OBJ)' points to the first octet of OBJ, without checking!
127 * * `BIN_LEN(OBJ)' yields the length of OBJ in octets, without checking!
128 * * `BIN_FROMSTR(STR)' makes a `bin' object from a null-terminated string.
129 * * `BIN_FORMAT(FMT, ARGS...)' and `BIN_VFORMAT(FMT, AP)' make a `bin'
130 * object from a `printf'-like format string and arguments.
131 * * `BIN_PREPAREWRITE(OBJ, PTR, LEN)' prepares to make a `bin' object: it
132 * sets PTR to point to a buffer of LEN bytes; call `BIN_DONEWRITE' when
133 * finished. The variable OBJ will eventually be the resulting object,
134 * but until `BIN_DONEWRITE' is called, it may in fact be some different
135 * object.
136 * * `BIN_DONEWRITE(OBJ, LEN)' completes making a `bin' object: it adjusts
137 * its length to be LEN, which must not be larger than the LEN given to
138 * `BIN_PREPAREWRITE', and sets OBJ to point to the finished object.
139 * * `BIN_SETLEN(OBJ, LEN)' adjusts the length of OBJ downwards to LEN,
140 * without checking!
141 # * `Y' is a format character for `PyArg_ParseTuple...' for retrieving a
142 * null-terminated octet string from a `bin' object.
143 # * `YN' is a format character for `PyArg_ParseTuple...' for retrieving an
144 * octet string and length from any sort-of vaguely binary-ish object.
145 */
f7623015
MW
146#ifdef PY3
147# define BINOBJ PyBytesObject
148# define BIN_TYPE PyBytes_Type
149# define BIN_CHECK(obj) PyBytes_Check(obj)
150# define BIN_PTR(obj) PyBytes_AS_STRING(obj)
151# define BIN_LEN(obj) PyBytes_GET_SIZE(obj)
152# define BIN_FROMSTR(str) PyBytes_FromString(str)
153# define BIN_FROMSTRLEN(str, len) PyBytes_FromStringAndSize(str, len)
154# define BIN_FORMAT PyBytes_FromFormat
155# define BIN_VFORMAT PyBytes_FromFormatV
156# define BIN_PREPAREWRITE(obj, ptr, sz) do { \
157 (obj) = PyBytes_FromStringAndSize(0, (sz)); \
158 (ptr) = PyBytes_AS_STRING(obj); \
159 } while (0)
160# define BIN_DONEWRITE(obj, sz) do Py_SIZE(obj) = (sz); while (0)
161# define BIN_SETLEN(obj, len) do Py_SIZE(obj) = (len); while (0)
162# define Y "y"
163# define YN "y#"
164#else
6286102d
MW
165# define BINOBJ PyStringObject
166# define BIN_TYPE PyString_Type
167# define BIN_CHECK(obj) PyString_Check(obj)
168# define BIN_PTR(obj) PyString_AS_STRING(obj)
169# define BIN_LEN(obj) PyString_GET_SIZE(obj)
170# define BIN_FROMSTR(str) PyString_FromString(str)
171# define BIN_FROMSTRLEN(str, len) PyString_FromStringAndSize(str, len)
172# define BIN_FORMAT PyString_FromFormat
173# define BIN_VFORMAT PyString_FromFormatV
174# define BIN_PREPAREWRITE(obj, ptr, sz) do { \
175 (obj) = PyString_FromStringAndSize(0, (sz)); \
176 (ptr) = PyString_AS_STRING(obj); \
177 } while (0)
178# define BIN_DONEWRITE(obj, sz) do Py_SIZE(obj) = (sz); while (0)
179# define BIN_SETLEN(obj, len) do Py_SIZE(obj) = (len); while (0)
180# define Y "s"
181# define YN "s#"
f7623015 182#endif
2135a6d3
MW
183
184/* Text strings. Both Python 2 and Python 3 call these `str', but they're
185 * very different because a Python 3 `str' is Unicode inside. When dealing
186 * with Python 3 text, the data is UTF-8 encoded. We call them `text' here,
187 * and define the following.
188 *
189 * * `TEXTOBJ' is the C type of a `text' object.
190 * * `TEXT_TYPE' is the Python `type' object for `text'.
191 * * `TEXT_CHECK(OBJ)' is true if OBJ is a `text' object.
192 * * `TEXT_STR(OBJ)' points to the first byte of a null-terminated string
193 * OBJ, or is null.
194 * * `TEXT_PTR(OBJ)' points to the first byte of OBJ, without checking!
195 * * `TEXT_LEN(OBJ)' yields the length of OBJ in octets, without checking!
196 * * `TEXT_FROMSTR(STR)' makes a `text' object from a null-terminated
197 * string.
198 * * `TEXT_FORMAT(FMT, ARGS...)' and `TEST_VFORMAT(FMT, AP)' make a `text'
199 * object from a `printf'-like format string and arguments.
200 * * `TEXT_PREPAREWRITE(OBJ, PTR, LEN)' prepares to make a `text' object:
201 * it sets PTR to point to a buffer of LEN bytes; call `TEXT_DONEWRITE'
202 * when finished. The variable OBJ will eventually be the resulting
203 * object, but until `TEXT_DONEWRITE' is called, it may in fact be some
204 * different object.
205 * * `TEXT_DONEWRITE(OBJ, LEN)' completes making a `text' object: it
206 * adjusts its length to be LEN, which must not be larger than the LEN
207 * given to `TEXT_PREPAREWRITE', and sets OBJ to point to the finished
208 * object.
209 *
210 * (Use `s' and `s#' in `PyArg_ParseTuple...'.)
211 */
f7623015
MW
212#ifdef PY3
213# define TEXTOBJ PyUnicodeObject
214# define TEXT_TYPE PyUnicode_Type
215# define TEXT_CHECK(obj) PyUnicode_Check(obj)
216# if PY_VERSION_HEX >= 0x03030000
217# define TEXT_PTR(obj) PyUnicode_AsUTF8(obj)
218# define TEXT_STR(obj) PyUnicode_AsUTF8(obj)
219# define TEXT_PTRLEN(obj, ptr, len) do { \
220 Py_ssize_t len_; \
221 (ptr) = PyUnicode_AsUTF8AndSize((obj), &len_); \
222 (len) = len_; \
223 } while (0)
224# define TEXT_PREPAREWRITE(obj, ptr, sz) do { \
225 (obj) = PyUnicode_New((sz), 127); \
226 (ptr) = PyUnicode_DATA(obj); \
227 } while (0)
228# define TEXT_DONEWRITE(obj, len) do { \
229 size_t len_ = (len); \
230 assert(PyUnicode_IS_COMPACT_ASCII(obj)); \
231 ((char *)PyUnicode_DATA(obj))[len_] = 0; \
232 ((PyASCIIObject *)(obj))->length = len_; \
233 } while (0)
234# else
235# define TEXT_PTR(obj) _PyUnicode_AsString(obj)
236# define TEXT_STR(obj) _PyUnicode_AsString(obj)
237# define TEXT_PTRLEN(obj, ptr, len) do { \
238 Py_ssize_t len_; \
239 (ptr) = _PyUnicode_AsStringAndSize((obj), &len_); \
240 (len) = len_; \
241 } while (0)
242# define TEXT_PREPAREWRITE(obj, ptr, sz) do { \
243 (obj) = PyBytes_FromStringAndSize(0, (sz)); \
244 (ptr) = PyBytes_AS_STRING(obj); \
245 } while (0)
246# define TEXT_DONEWRITE(obj, len) do { \
247 PyObject *new_; \
248 Py_SIZE(obj) = (len); \
249 new_ = PyUnicode_FromEncodedObject(obj, 0, 0); \
250 assert(new_); Py_DECREF(obj); (obj) = new_; \
251 } while (0)
252# endif
253# define TEXT_FORMAT PyUnicode_FromFormat
254# define TEXT_VFORMAT PyUnicode_FromFormatV
255# define TEXT_FROMSTR(str) PyUnicode_FromString(str)
256# define TEXT_FROMSTRLEN(str, len) PyUnicode_FromStringAndSize(str, len)
257#else
6286102d
MW
258# define TEXTOBJ PyStringObject
259# define TEXT_TYPE PyString_Type
260# define TEXT_CHECK(obj) PyString_Check(obj)
261# define TEXT_PTR(obj) PyString_AS_STRING(obj)
262# define TEXT_STR(obj) PyString_AsString(obj)
263# define TEXT_PTRLEN(obj, ptr, len) do { \
264 (ptr) = PyString_AS_STRING(obj); \
265 (len) = PyString_GET_SIZE(obj); \
266 } while (0)
267# define TEXT_FORMAT PyString_FromFormat
268# define TEXT_VFORMAT PyString_FromFormatV
269# define TEXT_PREPAREWRITE(obj, ptr, sz) do { \
270 (obj) = PyString_FromStringAndSize(0, (sz)); \
271 (ptr) = PyString_AS_STRING(obj); \
272 } while (0)
273# define TEXT_DONEWRITE(obj, sz) do { Py_SIZE(obj) = (sz); } while (0)
274# define TEXT_FROMSTR(str) PyString_FromString(str)
275# define TEXT_FROMSTRLEN(str, len) PyString_FromStringAndSize(str, len)
f7623015 276#endif
2135a6d3 277
10e6f88a
MW
278/*----- Utilities for returning values and exceptions ---------------------*/
279
280/* Returning values. */
281#define RETURN_OBJ(obj) do { Py_INCREF(obj); return (obj); } while (0)
282#define RETURN_NONE RETURN_OBJ(Py_None)
283#define RETURN_NOTIMPL RETURN_OBJ(Py_NotImplemented)
284#define RETURN_TRUE RETURN_OBJ(Py_True)
285#define RETURN_FALSE RETURN_OBJ(Py_False)
286#define RETURN_ME RETURN_OBJ(me)
287
288/* Returning exceptions. (Note that `KeyError' is `MAPERR' here, because
289 * Catacomb has its own kind of `KeyError'.)
290 */
291#define EXCERR(exc, str) do { \
292 PyErr_SetString(exc, str); \
293 goto end; \
294} while (0)
295#define VALERR(str) EXCERR(PyExc_ValueError, str)
296#define OVFERR(str) EXCERR(PyExc_OverflowError, str)
297#define TYERR(str) EXCERR(PyExc_TypeError, str)
298#define IXERR(str) EXCERR(PyExc_IndexError, str)
299#define ZDIVERR(str) EXCERR(PyExc_ZeroDivisionError, str)
300#define SYSERR(str) EXCERR(PyExc_SystemError, str)
301#define NIERR(str) EXCERR(PyExc_NotImplementedError, str)
f6a2cd66 302#define MAPERR(idx) do { \
10e6f88a
MW
303 PyErr_SetObject(PyExc_KeyError, idx); \
304 goto end; \
305} while (0)
306#define OSERR(name) do { \
307 PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); \
308 goto end; \
309} while (0)
310
311/* Saving and restoring exceptions. */
312struct excinfo { PyObject *ty, *val, *tb; };
313#define EXCINFO_INIT { 0, 0, 0 }
314#define INIT_EXCINFO(exc) do { \
315 struct excinfo *_exc = (exc); _exc->ty = _exc->val = _exc->tb = 0; \
316} while (0)
317#define RELEASE_EXCINFO(exc) do { \
318 struct excinfo *_exc = (exc); \
319 Py_XDECREF(_exc->ty); _exc->ty = 0; \
320 Py_XDECREF(_exc->val); _exc->val = 0; \
321 Py_XDECREF(_exc->tb); _exc->tb = 0; \
322} while (0)
323#define STASH_EXCINFO(exc) do { \
324 struct excinfo *_exc = (exc); \
325 PyErr_Fetch(&_exc->ty, &_exc->val, &_exc->tb); \
326 PyErr_NormalizeException(&_exc->ty, &_exc->val, &_exc->tb); \
327} while (0)
328#define RESTORE_EXCINFO(exc) do { \
329 struct excinfo *_exc = (exc); \
330 PyErr_Restore(_exc->ty, _exc->val, _exc->tb); \
331 _exc->ty = _exc->val = _exc->tb = 0; \
332} while (0)
333extern void report_lost_exception(struct excinfo *, const char *, ...);
334extern void report_lost_exception_v(struct excinfo *, const char *, va_list);
335extern void stash_exception(struct excinfo *, const char *, ...);
336extern void restore_exception(struct excinfo *, const char *, ...);
337
338/*----- Conversions -------------------------------------------------------*/
339
340/* Define an input conversion (`O&') function: check that the object has
341 * Python type TY, and extract a C pointer to CTY by calling EXT on the
342 * object (which may well be a macro).
343 */
344#define CONVFUNC(ty, cty, ext) \
345 int conv##ty(PyObject *o, void *p) \
346 { \
347 if (!PyObject_TypeCheck(o, ty##_pytype)) \
348 TYERR("wanted a " #ty); \
349 *(cty *)p = ext(o); \
350 return (1); \
351 end: \
352 return (0); \
353 }
354
355/* Input conversion functions for standard kinds of objects, with overflow
356 * checking where applicable.
357 */
21684137
MW
358struct bin { Py_buffer vw; const void *p; Py_ssize_t sz; };
359#define BIN_INIT { { 0 } 0, 0 }
360
10e6f88a
MW
361extern int convulong(PyObject *, void *); /* unsigned long */
362extern int convuint(PyObject *, void *); /* unsigned int */
363extern int convszt(PyObject *, void *); /* size_t */
364extern int convbool(PyObject *, void *); /* bool */
67c75893 365extern int convbin(PyObject *, void *); /* read buffer holding bytes */
21684137 366extern void freebin(struct bin *);
10e6f88a
MW
367
368/* Output conversions. */
369extern PyObject *getbool(int); /* bool */
370extern PyObject *getulong(unsigned long); /* any kind of unsigned integer */
371
372/*----- Miscellaneous utilities -------------------------------------------*/
373
2a448f86 374#define FREEOBJ(obj) (Py_TYPE(obj)->tp_free((PyObject *)(obj)))
10e6f88a
MW
375 /* Actually free OBJ, e.g., in a deallocation function. */
376
377extern PyObject *abstract_pynew(PyTypeObject *, PyObject *, PyObject *);
378 /* A `tp_new' function which refuses to make the object. */
379
77535854
MW
380extern PyObject *enrich_compare(int /*op*/, int /*cmp*/);
381 /* Use a traditional compare-against-zero comparison result CMP to answer a
382 * modern Python `tp_richcompare' operation OP.
383 */
384
c93e8163
MW
385#ifndef CONVERT_CAREFULLY
386# define CONVERT_CAREFULLY(newty, expty, obj) \
387 (!sizeof(*(expty *)0 = (obj)) + (/*unconst*/ newty)(obj))
388 /* Convert OBJ to the type NEWTY, having previously checked that it is
389 * convertible to the expected type EXPTY.
390 *
391 * Because of the way we set up types, we can make many kinds of tables be
392 * `const' which can't usually be so (because Python will want to fiddle
393 * with their reference counts); and, besides, Python's internals are
394 * generally quite bad at being `const'-correct about tables. One frequent
395 * application of this macro, then, is in removing `const' from a type
396 * without sacrificing all type safety. The other common use is in
397 * checking that method function types match up with the signatures
398 * expected in their method definitions.
399 */
400#endif
401
402#define KWLIST CONVERT_CAREFULLY(char **, const char *const *, kwlist)
10e6f88a
MW
403 /* Strip `const' qualifiers from the keyword list `kwlist'. Useful when
404 * calling `PyArg_ParseTupleAndKeywords', which isn't `const'-correct.
405 */
406
407/*----- Type definitions --------------------------------------------------*
408 *
409 * Pyke types are defined in a rather unusual way.
410 *
411 * The main code defines a `type skeleton' of type `PyTypeObject',
412 * conventionally named `TY_pytype_skel'. Unlike typical Python type
413 * definitions in extensions, this can (and should) be read-only. Also,
414 * there's no point in setting the `tp_base' pointer here, because the actual
415 * runtime base type object won't, in general, be known at compile time.
416 * Instead, the type skeletons are converted into Python `heap types' by the
417 * `INITTYPE' macro. The main difference is that Python code can add
418 * attributes to heap types, and we make extensive use of this ability.
419 */
420
421extern void *newtype(PyTypeObject */*meta*/,
422 const PyTypeObject */*skel*/, const char */*name*/);
423 /* Make and return a new Python type object, of type META (typically
424 * `PyType_Type', but may be a subclass), filled in from the skeleton SKEL
425 * (null to inherit everything), and named NAME. The caller can mess with
426 * the type object further at this time: call `typeready' when it's set up
427 * properly.
428 */
429
430extern void typeready(PyTypeObject *);
431 /* The type object is now ready to be used. */
432
c263b05c
MW
433extern PyTypeObject *inittype(const PyTypeObject */*skel*/,
434 PyTypeObject */*base*/,
10e6f88a
MW
435 PyTypeObject */*meta*/);
436 /* All-in-one function to construct a working type from a type skeleton
c263b05c 437 * SKEL, with known base type BASE (null for `object') and metaclass.
10e6f88a
MW
438 */
439
440/* Alias for built-in types, to fit in with Pyke naming conventions. */
441#define root_pytype 0
442#define type_pytype &PyType_Type
443
444#define INITTYPE_META(ty, base, meta) do { \
c263b05c 445 ty##_pytype = inittype(&ty##_pytype_skel, base##_pytype, meta##_pytype); \
10e6f88a
MW
446} while (0)
447#define INITTYPE(ty, base) INITTYPE_META(ty, base, type)
448 /* Macros to initialize a type from its skeleton. */
449
c93e8163
MW
450/* Macros for filling in `PyMethodDef' tables, ensuring that functions have
451 * the expected signatures.
452 */
a157093f
MW
453#define STD_METHOD(decor, func, flags, doc) \
454 { #func, decor(func), METH_VARARGS | flags, doc },
455#define KEYWORD_METHOD(decor, func, flags, doc) \
c93e8163
MW
456 { #func, \
457 CONVERT_CAREFULLY(PyCFunction, PyCFunctionWithKeywords, decor(func)), \
a157093f 458 METH_VARARGS | METH_KEYWORDS | flags, \
c93e8163 459 doc },
91e56f06
MW
460#define NOARG_METHOD(decor, func, flags, doc) \
461 { #func, \
462 CONVERT_CAREFULLY(PyCFunction, PyNoArgsFunction, decor(func)), \
463 METH_NOARGS | flags, \
464 doc },
c93e8163 465
10e6f88a
MW
466/* Convenience wrappers for filling in `PyMethodDef' tables, following
467 * Pyke naming convention. Define `METHNAME' locally as
468 *
469 * #define METHNAME(name) foometh_##func
470 *
471 * around the method table.
472 */
a157093f
MW
473#define METH(func, doc) STD_METHOD(METHNAME, func, 0, doc)
474#define KWMETH(func, doc) KEYWORD_METHOD(METHNAME, func, 0, doc)
91e56f06 475#define NAMETH(func, doc) NOARG_METHOD(METHNAME, func, 0, doc)
a157093f
MW
476#define CMTH(func, doc) STD_METHOD(METHNAME, func, METH_CLASS, doc)
477#define KWCMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_CLASS, doc)
91e56f06 478#define NACMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_CLASS, doc)
a157093f
MW
479#define SMTH(func, doc) STD_METHOD(METHNAME, func, METH_STATIC, doc)
480#define KWSMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_STATIC, doc)
91e56f06 481#define NASMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_STATIC, doc)
10e6f88a
MW
482
483/* Convenience wrappers for filling in `PyGetSetDef' tables, following Pyke
484 * naming convention. Define `GETSETNAME' locally as
485 *
486 * #define GETSETNAME(op, name) foo##op##_##func
487 *
488 * around the get/set table.
489 */
490#define GET(func, doc) \
491 { #func, GETSETNAME(get, func), 0, doc },
492#define GETSET(func, doc) \
493 { #func, GETSETNAME(get, func), GETSETNAME(set, func), doc },
494
c43a1ddb 495/* Convenience wrappers for filling in `PyMemberDef' tables. Define
10e6f88a
MW
496 * `MEMBERSTRUCT' locally as
497 *
498 * #define MEMBERSTRUCT foo_pyobj
499 *
500 * around the member table.
501 */
c43a1ddb
MW
502#define MEMRNM(name, ty, mem, f, doc) \
503 { #name, ty, offsetof(MEMBERSTRUCT, mem), f, doc },
504#define MEMBER(name, ty, f, doc) MEMRNM(name, ty, name, f, doc)
10e6f88a 505
c90f712e
MW
506/* Wrappers for filling in pointers in a `PyTypeObject' structure, (a)
507 * following Pyke naming convention, and (b) stripping `const' from the types
508 * without losing type safety.
509 */
510#define UNCONST_TYPE_SLOT(type, suffix, op, ty) \
511 CONVERT_CAREFULLY(type *, const type *, op ty##_py##suffix)
512#define PYGETSET(ty) UNCONST_TYPE_SLOT(PyGetSetDef, getset, NOTHING, ty)
513#define PYMETHODS(ty) UNCONST_TYPE_SLOT(PyMethodDef, methods, NOTHING, ty)
514#define PYMEMBERS(ty) UNCONST_TYPE_SLOT(PyMemberDef, members, NOTHING, ty)
515#define PYNUMBER(ty) UNCONST_TYPE_SLOT(PyNumberMethods, number, &, ty)
516#define PYSEQUENCE(ty) UNCONST_TYPE_SLOT(PySequenceMethods, sequence, &, ty)
517#define PYMAPPING(ty) UNCONST_TYPE_SLOT(PyMappingMethods, mapping, &, ty)
518#define PYBUFFER(ty) UNCONST_TYPE_SLOT(PyBufferProcs, buffer, &, ty)
519
10e6f88a
MW
520/*----- Populating modules ------------------------------------------------*/
521
522extern PyObject *modname;
2135a6d3 523 /* The overall module name. Set this with `TEXT_FROMSTR'. */
10e6f88a
MW
524
525extern PyObject *home_module;
526 /* The overall module object. */
527
528extern PyObject *mkexc(PyObject */*mod*/, PyObject */*base*/,
c90f712e 529 const char */*name*/, const PyMethodDef */*methods*/);
10e6f88a
MW
530 /* Make and return an exception class called NAME, which will end up in
531 * module MOD (though it is not added at this time). The new class is a
532 * subclass of BASE. Attach the METHODS to it.
533 */
534
535#define INSERT(name, ob) do { \
536 PyObject *_o = (PyObject *)(ob); \
537 Py_INCREF(_o); \
538 PyModule_AddObject(mod, name, _o); \
539} while (0)
540 /* Insert a Python object OB into the module `mod' under the given NAME. */
541
542/* Numeric constants. */
543struct nameval { const char *name; unsigned f; unsigned long value; };
544#define CF_SIGNED 1u
545extern void setconstants(PyObject *, const struct nameval *);
810542b0
MW
546#define CONST(x) { #x, (x) >= 0 ? 0 : CF_SIGNED, x }
547#define CONSTFLAG(f, x) { #x, f, x }
10e6f88a
MW
548
549#define INSEXC(name, var, base, meth) \
550 INSERT(name, var = mkexc(mod, base, name, meth))
551 /* Insert an exception class into the module `mod'; other arguments are as
552 * for `mkexc'.
553 */
554
555/*----- Submodules --------------------------------------------------------*
556 *
557 * It's useful to split the Python module up into multiple source files, and
558 * have each one contribute its definitions into the main module.
559 *
560 * Define a list-macro `MODULES' in the master header file naming the
561 * submodules to be processed, and run
562 *
563 * MODULES(DECLARE_MODINIT)
564 *
565 * to declare the interface functions.
566 *
567 * Each submodule FOO defines two functions: `FOO_pyinit' initializes types
568 * (see `INITTYPE' above) and accumulates methods (`addmethods' below), while
569 * `FOO_pyinsert' populates the module with additional definitions
570 * (especially types, though also constants).
571 *
572 * The top-level module initialization should call `INIT_MODULES' before
573 * creating the Python module, and `INSERT_MODULES' afterwards to make
574 * everything work.
575 */
576
577extern void addmethods(const PyMethodDef *);
578extern PyMethodDef *donemethods(void);
579 /* Accumulate method-table fragments, and return the combined table of all
580 * of the fragments.
581 */
582
583#define DECLARE_MODINIT(m) \
584 extern void m##_pyinit(void); \
585 extern void m##_pyinsert(PyObject *);
586 /* Declare submodule interface functions. */
587
588#define DOMODINIT(m) m##_pyinit();
589#define DOMODINSERT(m) m##_pyinsert(mod);
590#define INIT_MODULES do { MODULES(DOMODINIT) } while (0)
591#define INSERT_MODULES do { MODULES(DOMODINSERT) } while (0)
592 /* Top-level dispatch to the various submodules. */
593
594/*----- Generic mapping support -------------------------------------------*/
595
31ff254e
MW
596/* Operations table. ME is the mapping object throughout. */
597typedef struct gmap_ops {
598 size_t isz; /* iterator size */
599
600 void *(*lookup)(PyObject *me, PyObject *key, unsigned *f);
601 /* Lookup the KEY. If it is found, return an entry pointer for it; if F
602 * is not null, set *F nonzero. Otherwise, if F is null, return a null
603 * pointer (without setting a pending exception); if F is not null, then
604 * set *F zero and return a fresh entry pointer. Return null on a Python
605 * exception (the caller will notice the difference.)
606 */
607
608 void (*iter_init)(PyObject *me, void *i);
609 /* Initialize an iterator at I. */
610
611 void *(*iter_next)(PyObject *me, void *i);
612 /* Return an entry pointer for a different item, or null if all have been
613 * visited.
614 */
615
616 PyObject *(*entry_key)(PyObject *me, void *e);
617 /* Return the key object for a mapping entry. */
618
619 PyObject *(*entry_value)(PyObject *me, void *e);
620 /* Return the value object for a mapping entry. */
621
622 int (*set_entry)(PyObject *me, void *e, PyObject *val);
623 /* Modify the entry by storing VAL in its place. Return 0 on success,
624 * or -1 on a Python error.
625 */
626
627 int (*del_entry)(PyObject *me, void *e);
628 /* Delete the entry. (It may be necessary to delete a freshly allocated
629 * entry, e.g., if `set_entry' failed.) Return 0 on success, or -1 on a
630 * Python error.
631 */
632} gmap_ops;
633
634/* The intrusion at the head of a mapping object. */
635#define GMAP_PYOBJ_HEAD \
636 PyObject_HEAD \
637 const gmap_ops *gmops;
638
639typedef struct gmap_pyobj {
640 GMAP_PYOBJ_HEAD
641} gmap_pyobj;
642#define GMAP_OPS(obj) (((gmap_pyobj *)(obj))->gmops)
643 /* Discover the operations from a mapping object. */
644
10e6f88a 645/* Mapping methods. */
c93e8163 646#define GMAP_METMNAME(func) gmapmeth_##func
a157093f
MW
647#define GMAP_METH(func, doc) STD_METHOD(GMAP_METMNAME, func, 0, doc)
648#define GMAP_KWMETH(func, doc) KEYWORD_METHOD(GMAP_METMNAME, func, 0, doc)
91e56f06 649#define GMAP_NAMETH(func, doc) NOARG_METHOD(GMAP_METMNAME, func, 0, doc)
10e6f88a
MW
650#define GMAP_METHDECL(func, doc) \
651 extern PyObject *gmapmeth_##func(PyObject *, PyObject *);
652#define GMAP_KWMETHDECL(func, doc) \
653 extern PyObject *gmapmeth_##func(PyObject *, PyObject *, PyObject *);
91e56f06
MW
654#define GMAP_NAMETHDECL(func, doc) \
655 extern PyObject *gmapmeth_##func(PyObject *);
10e6f88a 656
f7623015
MW
657#ifdef PY3
658# define GMAP_DOROMETHODS(METH, KWMETH, NAMETH) \
659 NAMETH(keys, "D.keys() -> LIST") \
660 NAMETH(values, "D.values() -> LIST") \
661 NAMETH(items, "D.items() -> LIST") \
662 KWMETH(get, "D.get(KEY, [default = None]) -> VALUE")
663#else
6286102d
MW
664# define GMAP_DOROMETHODS(METH, KWMETH, NAMETH) \
665 METH (has_key, "D.has_key(KEY) -> BOOL") \
666 NAMETH(keys, "D.keys() -> LIST") \
667 NAMETH(values, "D.values() -> LIST") \
668 NAMETH(items, "D.items() -> LIST") \
669 NAMETH(iterkeys, "D.iterkeys() -> ITER") \
670 NAMETH(itervalues, "D.itervalues() -> ITER") \
671 NAMETH(iteritems, "D.iteritems() -> ITER") \
672 KWMETH(get, "D.get(KEY, [default = None]) -> VALUE")
f7623015 673#endif
10e6f88a 674
91e56f06
MW
675#define GMAP_DOMETHODS(METH, KWMETH, NAMETH) \
676 GMAP_DOROMETHODS(METH, KWMETH, NAMETH) \
677 NAMETH(clear, "D.clear()") \
10e6f88a
MW
678 KWMETH(setdefault, "D.setdefault(K, [default = None]) -> VALUE") \
679 KWMETH(pop, "D.pop(KEY, [default = <error>]) -> VALUE") \
91e56f06 680 NAMETH(popitem, "D.popitem() -> (KEY, VALUE)") \
31ff254e 681 KWMETH(update, "D.update(MAP)")
10e6f88a 682
91e56f06
MW
683GMAP_DOMETHODS(GMAP_METHDECL, GMAP_KWMETHDECL, GMAP_NAMETHDECL)
684#define GMAP_ROMETHODS GMAP_DOROMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
685#define GMAP_METHODS GMAP_DOMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
10e6f88a
MW
686
687/* Mapping protocol implementation. */
688extern Py_ssize_t gmap_pysize(PyObject *); /* for `mp_length' */
31ff254e
MW
689extern PyObject *gmap_pyiter(PyObject *); /* for `tp_iter' */
690extern PyObject *gmap_pylookup(PyObject *, PyObject *); /* for `mp_subscript' */
691extern int gmap_pystore(PyObject *, PyObject *, PyObject *); /* for `mp_ass_subscript' */
692extern int gmap_pyhaskey(PyObject *, PyObject *); /* for `sq_contains' */
c90f712e 693extern const PySequenceMethods gmap_pysequence; /* for `tp_as_sequence' */
31ff254e 694extern const PyMethodDef gmapro_pymethods[]; /* read-only methods */
c90f712e 695extern const PyMethodDef gmap_pymethods[]; /* all the standard methods */
10e6f88a
MW
696
697/*----- That's all, folks -------------------------------------------------*/
698
699#ifdef __cplusplus
700 }
701#endif
702
703#endif