chiark / gitweb /
*.c: Separate string function calls according to text/binary usage.
[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 #ifndef CONVERT_CAREFULLY
283 #  define CONVERT_CAREFULLY(newty, expty, obj)                          \
284      (!sizeof(*(expty *)0 = (obj)) + (/*unconst*/ newty)(obj))
285   /* Convert OBJ to the type NEWTY, having previously checked that it is
286    * convertible to the expected type EXPTY.
287    *
288    * Because of the way we set up types, we can make many kinds of tables be
289    * `const' which can't usually be so (because Python will want to fiddle
290    * with their reference counts); and, besides, Python's internals are
291    * generally quite bad at being `const'-correct about tables.  One frequent
292    * application of this macro, then, is in removing `const' from a type
293    * without sacrificing all type safety.  The other common use is in
294    * checking that method function types match up with the signatures
295    * expected in their method definitions.
296    */
297 #endif
298
299 #define KWLIST CONVERT_CAREFULLY(char **, const char *const *, kwlist)
300   /* Strip `const' qualifiers from the keyword list `kwlist'.  Useful when
301    * calling `PyArg_ParseTupleAndKeywords', which isn't `const'-correct.
302    */
303
304 /*----- Type definitions --------------------------------------------------*
305  *
306  * Pyke types are defined in a rather unusual way.
307  *
308  * The main code defines a `type skeleton' of type `PyTypeObject',
309  * conventionally named `TY_pytype_skel'.  Unlike typical Python type
310  * definitions in extensions, this can (and should) be read-only.  Also,
311  * there's no point in setting the `tp_base' pointer here, because the actual
312  * runtime base type object won't, in general, be known at compile time.
313  * Instead, the type skeletons are converted into Python `heap types' by the
314  * `INITTYPE' macro.  The main difference is that Python code can add
315  * attributes to heap types, and we make extensive use of this ability.
316  */
317
318 extern void *newtype(PyTypeObject */*meta*/,
319                      const PyTypeObject */*skel*/, const char */*name*/);
320   /* Make and return a new Python type object, of type META (typically
321    * `PyType_Type', but may be a subclass), filled in from the skeleton SKEL
322    * (null to inherit everything), and named NAME.  The caller can mess with
323    * the type object further at this time: call `typeready' when it's set up
324    * properly.
325    */
326
327 extern void typeready(PyTypeObject *);
328   /* The type object is now ready to be used. */
329
330 extern PyTypeObject *inittype(const PyTypeObject */*skel*/,
331                               PyTypeObject */*base*/,
332                               PyTypeObject */*meta*/);
333   /* All-in-one function to construct a working type from a type skeleton
334    * SKEL, with known base type BASE (null for `object') and metaclass.
335    */
336
337 /* Alias for built-in types, to fit in with Pyke naming conventions. */
338 #define root_pytype 0
339 #define type_pytype &PyType_Type
340
341 #define INITTYPE_META(ty, base, meta) do {                              \
342   ty##_pytype = inittype(&ty##_pytype_skel, base##_pytype, meta##_pytype); \
343 } while (0)
344 #define INITTYPE(ty, base) INITTYPE_META(ty, base, type)
345   /* Macros to initialize a type from its skeleton. */
346
347 /* Macros for filling in `PyMethodDef' tables, ensuring that functions have
348  * the expected signatures.
349  */
350 #define STD_METHOD(decor, func, flags, doc)                             \
351   { #func, decor(func), METH_VARARGS | flags, doc },
352 #define KEYWORD_METHOD(decor, func, flags, doc)                         \
353   { #func,                                                              \
354     CONVERT_CAREFULLY(PyCFunction, PyCFunctionWithKeywords, decor(func)), \
355     METH_VARARGS | METH_KEYWORDS | flags,                               \
356     doc },
357 #define NOARG_METHOD(decor, func, flags, doc)                           \
358   { #func,                                                              \
359     CONVERT_CAREFULLY(PyCFunction, PyNoArgsFunction, decor(func)),      \
360     METH_NOARGS | flags,                                                \
361     doc },
362
363 /* Convenience wrappers for filling in `PyMethodDef' tables, following
364  * Pyke naming convention.  Define `METHNAME' locally as
365  *
366  *      #define METHNAME(name) foometh_##func
367  *
368  * around the method table.
369  */
370 #define METH(func, doc) STD_METHOD(METHNAME, func, 0, doc)
371 #define KWMETH(func, doc) KEYWORD_METHOD(METHNAME, func, 0, doc)
372 #define NAMETH(func, doc) NOARG_METHOD(METHNAME, func, 0, doc)
373 #define CMTH(func, doc) STD_METHOD(METHNAME, func, METH_CLASS, doc)
374 #define KWCMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_CLASS, doc)
375 #define NACMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_CLASS, doc)
376 #define SMTH(func, doc) STD_METHOD(METHNAME, func, METH_STATIC, doc)
377 #define KWSMTH(func, doc) KEYWORD_METHOD(METHNAME, func, METH_STATIC, doc)
378 #define NASMTH(func, doc) NOARG_METHOD(METHNAME, func, METH_STATIC, doc)
379
380 /* Convenience wrappers for filling in `PyGetSetDef' tables, following Pyke
381  * naming convention.  Define `GETSETNAME' locally as
382  *
383  *      #define GETSETNAME(op, name) foo##op##_##func
384  *
385  * around the get/set table.
386  */
387 #define GET(func, doc)                                                  \
388   { #func, GETSETNAME(get, func), 0, doc },
389 #define GETSET(func, doc)                                               \
390   { #func, GETSETNAME(get, func), GETSETNAME(set, func), doc },
391
392 /* Convenience wrappers for filling in `PyMemberDef' tables.  Define
393  * `MEMBERSTRUCT' locally as
394  *
395  *      #define MEMBERSTRUCT foo_pyobj
396  *
397  * around the member table.
398  */
399 #define MEMRNM(name, ty, mem, f, doc)                                   \
400   { #name, ty, offsetof(MEMBERSTRUCT, mem), f, doc },
401 #define MEMBER(name, ty, f, doc) MEMRNM(name, ty, name, f, doc)
402
403 /* Wrappers for filling in pointers in a `PyTypeObject' structure, (a)
404  * following Pyke naming convention, and (b) stripping `const' from the types
405  * without losing type safety.
406  */
407 #define UNCONST_TYPE_SLOT(type, suffix, op, ty)                         \
408   CONVERT_CAREFULLY(type *, const type *, op ty##_py##suffix)
409 #define PYGETSET(ty) UNCONST_TYPE_SLOT(PyGetSetDef, getset, NOTHING, ty)
410 #define PYMETHODS(ty) UNCONST_TYPE_SLOT(PyMethodDef, methods, NOTHING, ty)
411 #define PYMEMBERS(ty) UNCONST_TYPE_SLOT(PyMemberDef, members, NOTHING, ty)
412 #define PYNUMBER(ty) UNCONST_TYPE_SLOT(PyNumberMethods, number, &, ty)
413 #define PYSEQUENCE(ty) UNCONST_TYPE_SLOT(PySequenceMethods, sequence, &, ty)
414 #define PYMAPPING(ty) UNCONST_TYPE_SLOT(PyMappingMethods, mapping, &, ty)
415 #define PYBUFFER(ty) UNCONST_TYPE_SLOT(PyBufferProcs, buffer, &, ty)
416
417 /*----- Populating modules ------------------------------------------------*/
418
419 extern PyObject *modname;
420   /* The overall module name.  Set this with `TEXT_FROMSTR'. */
421
422 extern PyObject *home_module;
423   /* The overall module object. */
424
425 extern PyObject *mkexc(PyObject */*mod*/, PyObject */*base*/,
426                        const char */*name*/, const PyMethodDef */*methods*/);
427   /* Make and return an exception class called NAME, which will end up in
428    * module MOD (though it is not added at this time).  The new class is a
429    * subclass of BASE.  Attach the METHODS to it.
430    */
431
432 #define INSERT(name, ob) do {                                           \
433   PyObject *_o = (PyObject *)(ob);                                      \
434   Py_INCREF(_o);                                                        \
435   PyModule_AddObject(mod, name, _o);                                    \
436 } while (0)
437   /* Insert a Python object OB into the module `mod' under the given NAME. */
438
439 /* Numeric constants. */
440 struct nameval { const char *name; unsigned f; unsigned long value; };
441 #define CF_SIGNED 1u
442 extern void setconstants(PyObject *, const struct nameval *);
443 #define CONST(x) { #x, (x) >= 0 ? 0 : CF_SIGNED, x }
444 #define CONSTFLAG(f, x) { #x, f, x }
445
446 #define INSEXC(name, var, base, meth)                                   \
447   INSERT(name, var = mkexc(mod, base, name, meth))
448   /* Insert an exception class into the module `mod'; other arguments are as
449    * for `mkexc'.
450    */
451
452 /*----- Submodules --------------------------------------------------------*
453  *
454  * It's useful to split the Python module up into multiple source files, and
455  * have each one contribute its definitions into the main module.
456  *
457  * Define a list-macro `MODULES' in the master header file naming the
458  * submodules to be processed, and run
459  *
460  *      MODULES(DECLARE_MODINIT)
461  *
462  * to declare the interface functions.
463  *
464  * Each submodule FOO defines two functions: `FOO_pyinit' initializes types
465  * (see `INITTYPE' above) and accumulates methods (`addmethods' below), while
466  * `FOO_pyinsert' populates the module with additional definitions
467  * (especially types, though also constants).
468  *
469  * The top-level module initialization should call `INIT_MODULES' before
470  * creating the Python module, and `INSERT_MODULES' afterwards to make
471  * everything work.
472  */
473
474 extern void addmethods(const PyMethodDef *);
475 extern PyMethodDef *donemethods(void);
476   /* Accumulate method-table fragments, and return the combined table of all
477    * of the fragments.
478    */
479
480 #define DECLARE_MODINIT(m)                                              \
481   extern void m##_pyinit(void);                                         \
482   extern void m##_pyinsert(PyObject *);
483   /* Declare submodule interface functions. */
484
485 #define DOMODINIT(m) m##_pyinit();
486 #define DOMODINSERT(m) m##_pyinsert(mod);
487 #define INIT_MODULES do { MODULES(DOMODINIT) } while (0)
488 #define INSERT_MODULES do { MODULES(DOMODINSERT) } while (0)
489   /* Top-level dispatch to the various submodules. */
490
491 /*----- Generic mapping support -------------------------------------------*/
492
493 /* Operations table.  ME is the mapping object throughout. */
494 typedef struct gmap_ops {
495   size_t isz;                           /* iterator size */
496
497   void *(*lookup)(PyObject *me, PyObject *key, unsigned *f);
498     /* Lookup the KEY.  If it is found, return an entry pointer for it; if F
499      * is not null, set *F nonzero.  Otherwise, if F is null, return a null
500      * pointer (without setting a pending exception); if F is not null, then
501      * set *F zero and return a fresh entry pointer.  Return null on a Python
502      * exception (the caller will notice the difference.)
503      */
504
505   void (*iter_init)(PyObject *me, void *i);
506     /* Initialize an iterator at I. */
507
508   void *(*iter_next)(PyObject *me, void *i);
509     /* Return an entry pointer for a different item, or null if all have been
510      * visited.
511      */
512
513   PyObject *(*entry_key)(PyObject *me, void *e);
514     /* Return the key object for a mapping entry. */
515
516   PyObject *(*entry_value)(PyObject *me, void *e);
517     /* Return the value object for a mapping entry. */
518
519   int (*set_entry)(PyObject *me, void *e, PyObject *val);
520     /* Modify the entry by storing VAL in its place.  Return 0 on success,
521      * or -1 on a Python error.
522      */
523
524   int (*del_entry)(PyObject *me, void *e);
525     /* Delete the entry.  (It may be necessary to delete a freshly allocated
526      * entry, e.g., if `set_entry' failed.)  Return 0 on success, or -1 on a
527      * Python error.
528      */
529 } gmap_ops;
530
531 /* The intrusion at the head of a mapping object. */
532 #define GMAP_PYOBJ_HEAD                                                 \
533   PyObject_HEAD                                                         \
534   const gmap_ops *gmops;
535
536 typedef struct gmap_pyobj {
537   GMAP_PYOBJ_HEAD
538 } gmap_pyobj;
539 #define GMAP_OPS(obj) (((gmap_pyobj *)(obj))->gmops)
540   /* Discover the operations from a mapping object. */
541
542 /* Mapping methods. */
543 #define GMAP_METMNAME(func) gmapmeth_##func
544 #define GMAP_METH(func, doc) STD_METHOD(GMAP_METMNAME, func, 0, doc)
545 #define GMAP_KWMETH(func, doc) KEYWORD_METHOD(GMAP_METMNAME, func, 0, doc)
546 #define GMAP_NAMETH(func, doc) NOARG_METHOD(GMAP_METMNAME, func, 0, doc)
547 #define GMAP_METHDECL(func, doc)                                        \
548   extern PyObject *gmapmeth_##func(PyObject *, PyObject *);
549 #define GMAP_KWMETHDECL(func, doc)                                      \
550   extern PyObject *gmapmeth_##func(PyObject *, PyObject *, PyObject *);
551 #define GMAP_NAMETHDECL(func, doc)                                      \
552   extern PyObject *gmapmeth_##func(PyObject *);
553
554 #define GMAP_DOROMETHODS(METH, KWMETH, NAMETH)                          \
555   METH  (has_key,       "D.has_key(KEY) -> BOOL")                       \
556   NAMETH(keys,          "D.keys() -> LIST")                             \
557   NAMETH(values,        "D.values() -> LIST")                           \
558   NAMETH(items,         "D.items() -> LIST")                            \
559   NAMETH(iterkeys,      "D.iterkeys() -> ITER")                         \
560   NAMETH(itervalues,    "D.itervalues() -> ITER")                       \
561   NAMETH(iteritems,     "D.iteritems() -> ITER")                        \
562   KWMETH(get,           "D.get(KEY, [default = None]) -> VALUE")
563
564 #define GMAP_DOMETHODS(METH, KWMETH, NAMETH)                            \
565   GMAP_DOROMETHODS(METH, KWMETH, NAMETH)                                \
566   NAMETH(clear,         "D.clear()")                                    \
567   KWMETH(setdefault,    "D.setdefault(K, [default = None]) -> VALUE")   \
568   KWMETH(pop,           "D.pop(KEY, [default = <error>]) -> VALUE")     \
569   NAMETH(popitem,       "D.popitem() -> (KEY, VALUE)")                  \
570   KWMETH(update,        "D.update(MAP)")
571
572 GMAP_DOMETHODS(GMAP_METHDECL, GMAP_KWMETHDECL, GMAP_NAMETHDECL)
573 #define GMAP_ROMETHODS GMAP_DOROMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
574 #define GMAP_METHODS GMAP_DOMETHODS(GMAP_METH, GMAP_KWMETH, GMAP_NAMETH)
575
576 /* Mapping protocol implementation. */
577 extern Py_ssize_t gmap_pysize(PyObject *); /* for `mp_length' */
578 extern PyObject *gmap_pyiter(PyObject *); /* for `tp_iter' */
579 extern PyObject *gmap_pylookup(PyObject *, PyObject *); /* for `mp_subscript' */
580 extern int gmap_pystore(PyObject *, PyObject *, PyObject *); /* for `mp_ass_subscript' */
581 extern int gmap_pyhaskey(PyObject *, PyObject *); /* for `sq_contains' */
582 extern const PySequenceMethods gmap_pysequence; /* for `tp_as_sequence' */
583 extern const PyMethodDef gmapro_pymethods[]; /* read-only methods */
584 extern const PyMethodDef gmap_pymethods[]; /* all the standard methods */
585
586 /*----- That's all, folks -------------------------------------------------*/
587
588 #ifdef __cplusplus
589   }
590 #endif
591
592 #endif