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