chiark / gitweb /
pyke/pyke-mLib.c: Raise `OverflowError' on out-of-range inputs.
[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 /* 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
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
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
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
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
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
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  */
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
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#"
182 #endif
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  */
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
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)
276 #endif
277
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)
302 #define MAPERR(idx) do {                                                \
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. */
312 struct 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)
333 extern void report_lost_exception(struct excinfo *, const char *, ...);
334 extern void report_lost_exception_v(struct excinfo *, const char *, va_list);
335 extern void stash_exception(struct excinfo *, const char *, ...);
336 extern 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  */
358 struct bin { const void *p; Py_ssize_t sz; };
359 extern int convulong(PyObject *, void *); /* unsigned long */
360 extern int convuint(PyObject *, void *); /* unsigned int */
361 extern int convszt(PyObject *, void *); /* size_t */
362 extern int convbool(PyObject *, void *); /* bool */
363 extern int convbin(PyObject *, void *); /* read buffer holding bytes */
364
365 /* Output conversions. */
366 extern PyObject *getbool(int);          /* bool */
367 extern PyObject *getulong(unsigned long); /* any kind of unsigned integer */
368
369 /*----- Miscellaneous utilities -------------------------------------------*/
370
371 #define FREEOBJ(obj) (Py_TYPE(obj)->tp_free((PyObject *)(obj)))
372   /* Actually free OBJ, e.g., in a deallocation function. */
373
374 extern PyObject *abstract_pynew(PyTypeObject *, PyObject *, PyObject *);
375   /* A `tp_new' function which refuses to make the object. */
376
377 extern PyObject *enrich_compare(int /*op*/, int /*cmp*/);
378   /* Use a traditional compare-against-zero comparison result CMP to answer a
379    * modern Python `tp_richcompare' operation OP.
380    */
381
382 #ifndef CONVERT_CAREFULLY
383 #  define CONVERT_CAREFULLY(newty, expty, obj)                          \
384      (!sizeof(*(expty *)0 = (obj)) + (/*unconst*/ newty)(obj))
385   /* Convert OBJ to the type NEWTY, having previously checked that it is
386    * convertible to the expected type EXPTY.
387    *
388    * Because of the way we set up types, we can make many kinds of tables be
389    * `const' which can't usually be so (because Python will want to fiddle
390    * with their reference counts); and, besides, Python's internals are
391    * generally quite bad at being `const'-correct about tables.  One frequent
392    * application of this macro, then, is in removing `const' from a type
393    * without sacrificing all type safety.  The other common use is in
394    * checking that method function types match up with the signatures
395    * expected in their method definitions.
396    */
397 #endif
398
399 #define KWLIST CONVERT_CAREFULLY(char **, const char *const *, kwlist)
400   /* Strip `const' qualifiers from the keyword list `kwlist'.  Useful when
401    * calling `PyArg_ParseTupleAndKeywords', which isn't `const'-correct.
402    */
403
404 /*----- Type definitions --------------------------------------------------*
405  *
406  * Pyke types are defined in a rather unusual way.
407  *
408  * The main code defines a `type skeleton' of type `PyTypeObject',
409  * conventionally named `TY_pytype_skel'.  Unlike typical Python type
410  * definitions in extensions, this can (and should) be read-only.  Also,
411  * there's no point in setting the `tp_base' pointer here, because the actual
412  * runtime base type object won't, in general, be known at compile time.
413  * Instead, the type skeletons are converted into Python `heap types' by the
414  * `INITTYPE' macro.  The main difference is that Python code can add
415  * attributes to heap types, and we make extensive use of this ability.
416  */
417
418 extern void *newtype(PyTypeObject */*meta*/,
419                      const PyTypeObject */*skel*/, const char */*name*/);
420   /* Make and return a new Python type object, of type META (typically
421    * `PyType_Type', but may be a subclass), filled in from the skeleton SKEL
422    * (null to inherit everything), and named NAME.  The caller can mess with
423    * the type object further at this time: call `typeready' when it's set up
424    * properly.
425    */
426
427 extern void typeready(PyTypeObject *);
428   /* The type object is now ready to be used. */
429
430 extern PyTypeObject *inittype(const PyTypeObject */*skel*/,
431                               PyTypeObject */*base*/,
432                               PyTypeObject */*meta*/);
433   /* All-in-one function to construct a working type from a type skeleton
434    * SKEL, with known base type BASE (null for `object') and metaclass.
435    */
436
437 /* Alias for built-in types, to fit in with Pyke naming conventions. */
438 #define root_pytype 0
439 #define type_pytype &PyType_Type
440
441 #define INITTYPE_META(ty, base, meta) do {                              \
442   ty##_pytype = inittype(&ty##_pytype_skel, base##_pytype, meta##_pytype); \
443 } while (0)
444 #define INITTYPE(ty, base) INITTYPE_META(ty, base, type)
445   /* Macros to initialize a type from its skeleton. */
446
447 /* Macros for filling in `PyMethodDef' tables, ensuring that functions have
448  * the expected signatures.
449  */
450 #define STD_METHOD(decor, func, flags, doc)                             \
451   { #func, decor(func), METH_VARARGS | flags, doc },
452 #define KEYWORD_METHOD(decor, func, flags, doc)                         \
453   { #func,                                                              \
454     CONVERT_CAREFULLY(PyCFunction, PyCFunctionWithKeywords, decor(func)), \
455     METH_VARARGS | METH_KEYWORDS | flags,                               \
456     doc },
457 #define NOARG_METHOD(decor, func, flags, doc)                           \
458   { #func,                                                              \
459     CONVERT_CAREFULLY(PyCFunction, PyNoArgsFunction, decor(func)),      \
460     METH_NOARGS | flags,                                                \
461     doc },
462
463 /* Convenience wrappers for filling in `PyMethodDef' tables, following
464  * Pyke naming convention.  Define `METHNAME' locally as
465  *
466  *      #define METHNAME(name) foometh_##func
467  *
468  * around the method table.
469  */
470 #define METH(func, doc) STD_METHOD(METHNAME, func, 0, doc)
471 #define KWMETH(func, doc) KEYWORD_METHOD(METHNAME, func, 0, doc)
472 #define NAMETH(func, doc) NOARG_METHOD(METHNAME, func, 0, doc)
473 #define CMTH(func, doc) STD_METHOD(METHNAME, func, METH_CLASS, doc)
474 #define KWCMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_CLASS, doc)
475 #define NACMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_CLASS, doc)
476 #define SMTH(func, doc) STD_METHOD(METHNAME, func, METH_STATIC, doc)
477 #define KWSMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_STATIC, doc)
478 #define NASMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_STATIC, doc)
479
480 /* Convenience wrappers for filling in `PyGetSetDef' tables, following Pyke
481  * naming convention.  Define `GETSETNAME' locally as
482  *
483  *      #define GETSETNAME(op, name) foo##op##_##func
484  *
485  * around the get/set table.
486  */
487 #define GET(func, doc)                                                  \
488   { #func, GETSETNAME(get, func), 0, doc },
489 #define GETSET(func, doc)                                               \
490   { #func, GETSETNAME(get, func), GETSETNAME(set, func), doc },
491
492 /* Convenience wrappers for filling in `PyMemberDef' tables.  Define
493  * `MEMBERSTRUCT' locally as
494  *
495  *      #define MEMBERSTRUCT foo_pyobj
496  *
497  * around the member table.
498  */
499 #define MEMRNM(name, ty, mem, f, doc)                                   \
500   { #name, ty, offsetof(MEMBERSTRUCT, mem), f, doc },
501 #define MEMBER(name, ty, f, doc) MEMRNM(name, ty, name, f, doc)
502
503 /* Wrappers for filling in pointers in a `PyTypeObject' structure, (a)
504  * following Pyke naming convention, and (b) stripping `const' from the types
505  * without losing type safety.
506  */
507 #define UNCONST_TYPE_SLOT(type, suffix, op, ty)                         \
508   CONVERT_CAREFULLY(type *, const type *, op ty##_py##suffix)
509 #define PYGETSET(ty) UNCONST_TYPE_SLOT(PyGetSetDef, getset, NOTHING, ty)
510 #define PYMETHODS(ty) UNCONST_TYPE_SLOT(PyMethodDef, methods, NOTHING, ty)
511 #define PYMEMBERS(ty) UNCONST_TYPE_SLOT(PyMemberDef, members, NOTHING, ty)
512 #define PYNUMBER(ty) UNCONST_TYPE_SLOT(PyNumberMethods, number, &, ty)
513 #define PYSEQUENCE(ty) UNCONST_TYPE_SLOT(PySequenceMethods, sequence, &, ty)
514 #define PYMAPPING(ty) UNCONST_TYPE_SLOT(PyMappingMethods, mapping, &, ty)
515 #define PYBUFFER(ty) UNCONST_TYPE_SLOT(PyBufferProcs, buffer, &, ty)
516
517 /*----- Populating modules ------------------------------------------------*/
518
519 extern PyObject *modname;
520   /* The overall module name.  Set this with `TEXT_FROMSTR'. */
521
522 extern PyObject *home_module;
523   /* The overall module object. */
524
525 extern PyObject *mkexc(PyObject */*mod*/, PyObject */*base*/,
526                        const char */*name*/, const PyMethodDef */*methods*/);
527   /* Make and return an exception class called NAME, which will end up in
528    * module MOD (though it is not added at this time).  The new class is a
529    * subclass of BASE.  Attach the METHODS to it.
530    */
531
532 #define INSERT(name, ob) do {                                           \
533   PyObject *_o = (PyObject *)(ob);                                      \
534   Py_INCREF(_o);                                                        \
535   PyModule_AddObject(mod, name, _o);                                    \
536 } while (0)
537   /* Insert a Python object OB into the module `mod' under the given NAME. */
538
539 /* Numeric constants. */
540 struct nameval { const char *name; unsigned f; unsigned long value; };
541 #define CF_SIGNED 1u
542 extern void setconstants(PyObject *, const struct nameval *);
543 #define CONST(x) { #x, (x) >= 0 ? 0 : CF_SIGNED, x }
544 #define CONSTFLAG(f, x) { #x, f, x }
545
546 #define INSEXC(name, var, base, meth)                                   \
547   INSERT(name, var = mkexc(mod, base, name, meth))
548   /* Insert an exception class into the module `mod'; other arguments are as
549    * for `mkexc'.
550    */
551
552 /*----- Submodules --------------------------------------------------------*
553  *
554  * It's useful to split the Python module up into multiple source files, and
555  * have each one contribute its definitions into the main module.
556  *
557  * Define a list-macro `MODULES' in the master header file naming the
558  * submodules to be processed, and run
559  *
560  *      MODULES(DECLARE_MODINIT)
561  *
562  * to declare the interface functions.
563  *
564  * Each submodule FOO defines two functions: `FOO_pyinit' initializes types
565  * (see `INITTYPE' above) and accumulates methods (`addmethods' below), while
566  * `FOO_pyinsert' populates the module with additional definitions
567  * (especially types, though also constants).
568  *
569  * The top-level module initialization should call `INIT_MODULES' before
570  * creating the Python module, and `INSERT_MODULES' afterwards to make
571  * everything work.
572  */
573
574 extern void addmethods(const PyMethodDef *);
575 extern PyMethodDef *donemethods(void);
576   /* Accumulate method-table fragments, and return the combined table of all
577    * of the fragments.
578    */
579
580 #define DECLARE_MODINIT(m)                                              \
581   extern void m##_pyinit(void);                                         \
582   extern void m##_pyinsert(PyObject *);
583   /* Declare submodule interface functions. */
584
585 #define DOMODINIT(m) m##_pyinit();
586 #define DOMODINSERT(m) m##_pyinsert(mod);
587 #define INIT_MODULES do { MODULES(DOMODINIT) } while (0)
588 #define INSERT_MODULES do { MODULES(DOMODINSERT) } while (0)
589   /* Top-level dispatch to the various submodules. */
590
591 /*----- Generic mapping support -------------------------------------------*/
592
593 /* Operations table.  ME is the mapping object throughout. */
594 typedef struct gmap_ops {
595   size_t isz;                           /* iterator size */
596
597   void *(*lookup)(PyObject *me, PyObject *key, unsigned *f);
598     /* Lookup the KEY.  If it is found, return an entry pointer for it; if F
599      * is not null, set *F nonzero.  Otherwise, if F is null, return a null
600      * pointer (without setting a pending exception); if F is not null, then
601      * set *F zero and return a fresh entry pointer.  Return null on a Python
602      * exception (the caller will notice the difference.)
603      */
604
605   void (*iter_init)(PyObject *me, void *i);
606     /* Initialize an iterator at I. */
607
608   void *(*iter_next)(PyObject *me, void *i);
609     /* Return an entry pointer for a different item, or null if all have been
610      * visited.
611      */
612
613   PyObject *(*entry_key)(PyObject *me, void *e);
614     /* Return the key object for a mapping entry. */
615
616   PyObject *(*entry_value)(PyObject *me, void *e);
617     /* Return the value object for a mapping entry. */
618
619   int (*set_entry)(PyObject *me, void *e, PyObject *val);
620     /* Modify the entry by storing VAL in its place.  Return 0 on success,
621      * or -1 on a Python error.
622      */
623
624   int (*del_entry)(PyObject *me, void *e);
625     /* Delete the entry.  (It may be necessary to delete a freshly allocated
626      * entry, e.g., if `set_entry' failed.)  Return 0 on success, or -1 on a
627      * Python error.
628      */
629 } gmap_ops;
630
631 /* The intrusion at the head of a mapping object. */
632 #define GMAP_PYOBJ_HEAD                                                 \
633   PyObject_HEAD                                                         \
634   const gmap_ops *gmops;
635
636 typedef struct gmap_pyobj {
637   GMAP_PYOBJ_HEAD
638 } gmap_pyobj;
639 #define GMAP_OPS(obj) (((gmap_pyobj *)(obj))->gmops)
640   /* Discover the operations from a mapping object. */
641
642 /* Mapping methods. */
643 #define GMAP_METMNAME(func) gmapmeth_##func
644 #define GMAP_METH(func, doc) STD_METHOD(GMAP_METMNAME, func, 0, doc)
645 #define GMAP_KWMETH(func, doc) KEYWORD_METHOD(GMAP_METMNAME, func, 0, doc)
646 #define GMAP_NAMETH(func, doc) NOARG_METHOD(GMAP_METMNAME, func, 0, doc)
647 #define GMAP_METHDECL(func, doc)                                        \
648   extern PyObject *gmapmeth_##func(PyObject *, PyObject *);
649 #define GMAP_KWMETHDECL(func, doc)                                      \
650   extern PyObject *gmapmeth_##func(PyObject *, PyObject *, PyObject *);
651 #define GMAP_NAMETHDECL(func, doc)                                      \
652   extern PyObject *gmapmeth_##func(PyObject *);
653
654 #ifdef PY3
655 #  define GMAP_DOROMETHODS(METH, KWMETH, NAMETH)                        \
656     NAMETH(keys,        "D.keys() -> LIST")                             \
657     NAMETH(values,      "D.values() -> LIST")                           \
658     NAMETH(items,       "D.items() -> LIST")                            \
659     KWMETH(get,         "D.get(KEY, [default = None]) -> VALUE")
660 #else
661 #  define GMAP_DOROMETHODS(METH, KWMETH, NAMETH)                        \
662     METH  (has_key,     "D.has_key(KEY) -> BOOL")                       \
663     NAMETH(keys,        "D.keys() -> LIST")                             \
664     NAMETH(values,      "D.values() -> LIST")                           \
665     NAMETH(items,       "D.items() -> LIST")                            \
666     NAMETH(iterkeys,    "D.iterkeys() -> ITER")                         \
667     NAMETH(itervalues,  "D.itervalues() -> ITER")                       \
668     NAMETH(iteritems,   "D.iteritems() -> ITER")                        \
669     KWMETH(get,         "D.get(KEY, [default = None]) -> VALUE")
670 #endif
671
672 #define GMAP_DOMETHODS(METH, KWMETH, NAMETH)                            \
673   GMAP_DOROMETHODS(METH, KWMETH, NAMETH)                                \
674   NAMETH(clear,         "D.clear()")                                    \
675   KWMETH(setdefault,    "D.setdefault(K, [default = None]) -> VALUE")   \
676   KWMETH(pop,           "D.pop(KEY, [default = <error>]) -> VALUE")     \
677   NAMETH(popitem,       "D.popitem() -> (KEY, VALUE)")                  \
678   KWMETH(update,        "D.update(MAP)")
679
680 GMAP_DOMETHODS(GMAP_METHDECL, GMAP_KWMETHDECL, GMAP_NAMETHDECL)
681 #define GMAP_ROMETHODS GMAP_DOROMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
682 #define GMAP_METHODS GMAP_DOMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
683
684 /* Mapping protocol implementation. */
685 extern Py_ssize_t gmap_pysize(PyObject *); /* for `mp_length' */
686 extern PyObject *gmap_pyiter(PyObject *); /* for `tp_iter' */
687 extern PyObject *gmap_pylookup(PyObject *, PyObject *); /* for `mp_subscript' */
688 extern int gmap_pystore(PyObject *, PyObject *, PyObject *); /* for `mp_ass_subscript' */
689 extern int gmap_pyhaskey(PyObject *, PyObject *); /* for `sq_contains' */
690 extern const PySequenceMethods gmap_pysequence; /* for `tp_as_sequence' */
691 extern const PyMethodDef gmapro_pymethods[]; /* read-only methods */
692 extern const PyMethodDef gmap_pymethods[]; /* all the standard methods */
693
694 /*----- That's all, folks -------------------------------------------------*/
695
696 #ifdef __cplusplus
697   }
698 #endif
699
700 #endif