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