pyke/, ...: Extract utilities into a sort-of reusable library.
[pyke] / pyke.c
CommitLineData
c1756f78
MW
1/* -*-c-*-
2 *
3 * Pyke: the Python Kit for Extensions
4 *
5 * (c) 2019 Straylight/Edgeware
6 */
7
8/*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Pyke: the Python Kit for Extensions.
11 *
12 * Pyke is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 2 of the License, or (at your
15 * option) any later version.
16 *
17 * Pyke is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with Pyke. If not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27/*----- Header files ------------------------------------------------------*/
28
29#include "pyke.h"
30
31/*----- External variables ------------------------------------------------*/
32
33PyObject *modname;
34PyObject *home_module;
35
36/*----- Conversions -------------------------------------------------------*/
37
38PyObject *getulong(unsigned long w)
39{
40 if (w <= LONG_MAX) return (PyInt_FromLong(w));
41 else return (PyLong_FromUnsignedLong(w));
42}
43
44PyObject *getbool(int b)
45 { if (b) RETURN_TRUE; else RETURN_FALSE; }
46
47int convulong(PyObject *o, void *pp)
48{
49 long i;
50 unsigned long *p = pp;
51 PyObject *t;
52
53 if (!o) VALERR("can't delete");
54 if (PyInt_Check(o)) {
55 i = PyInt_AS_LONG(o);
56 if (i < 0) VALERR("must be nonnegative");
57 *p = i;
58 } else {
59 if ((t = PyNumber_Long(o)) == 0) goto end;
60 *p = PyLong_AsUnsignedLong(t);
61 Py_DECREF(t);
62 if (PyErr_Occurred()) goto end;
63 }
64 return (1);
65end:
66 return (0);
67}
68
69int convuint(PyObject *o, void *pp)
70{
71 unsigned long u;
72 unsigned *p = pp;
73
74 if (!convulong(o, &u)) goto end;
75 if (u > UINT_MAX) VALERR("out of range");
76 *p = u;
77 return (1);
78end:
79 return (0);
80}
81
82int convszt(PyObject *o, void *pp)
83{
84 unsigned long u;
85 size_t *p = pp;
86
87 if (!convulong(o, &u)) goto end;
88 if (u > ~(size_t)0) VALERR("out of range");
89 *p = u;
90 return (1);
91end:
92 return (0);
93}
94
95int convbool(PyObject *o, void *pp)
96{
97 if (!o) VALERR("can't delete");
98 *(int *)pp = PyObject_IsTrue(o);
99 return (1);
100end:
101 return (0);
102}
103
104/*----- Miscellaneous utilities -------------------------------------------*/
105
106PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
107{
108 PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
109 return (0);
110}
111
112/*----- Saving and restoring exceptions ----------------------------------*/
113
114void report_lost_exception_v(struct excinfo *exc,
115 const char *why, va_list ap)
116{
117 PyObject *hookfn = 0;
118 PyObject *whyobj = 0;
119 PyObject *obj = 0;
120
121 /* Make sure we start out without a pending exception, or this will get
122 * really confusing.
123 */
124 assert(!PyErr_Occurred());
125
126 /* Format the explanation. */
127 if (why) whyobj = PyString_FromFormatV(why, ap);
128 else { whyobj = Py_None; Py_INCREF(whyobj); }
129
130 /* Find our home module's `lostexchook' function. This won't work if
131 * there's no module, or the function isn't defined, or it's `None'.
132 */
133 if (!home_module) goto sys;
134 hookfn = PyObject_GetAttrString(home_module, "lostexchook");
135 if (hookfn == Py_None) goto sys;
136 else if (hookfn) ;
137 else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
138 else { PyErr_Clear(); goto sys; }
139
140 /* Call the hook function. */
141 obj = PyObject_CallFunction(hookfn, "(OOOO)",
142 whyobj, exc->ty, exc->val, exc->tb);
143 if (!obj) goto ouch;
144 goto end;
145
146 /* Something went wrong reporting the problem. */
147ouch:
148 PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
149 PyErr_Print();
150 /* drop through... */
151
152 /* There was no hook, so try to do something sensible using
153 * `sys.excepthook'.
154 */
155sys:
156 PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n",
157 PyString_AS_STRING(whyobj));
158 RESTORE_EXCINFO(exc);
159 PyErr_Print();
160 /* drop through... */
161
162 /* Clean up afterwards. */
163end:
164 Py_XDECREF(hookfn);
165 Py_XDECREF(whyobj);
166 Py_XDECREF(obj);
167}
168
169void report_lost_exception(struct excinfo *exc, const char *why, ...)
170{
171 va_list ap;
172
173 va_start(ap, why);
174 report_lost_exception_v(exc, why, ap);
175 va_end(ap);
176}
177
178void stash_exception(struct excinfo *exc, const char *why, ...)
179{
180 va_list ap;
181 struct excinfo stash;
182
183 if (!exc->ty)
184 STASH_EXCINFO(exc);
185 else {
186 va_start(ap, why);
187 STASH_EXCINFO(&stash);
188 report_lost_exception_v(&stash, why, ap);
189 va_end(ap);
190 }
191}
192
193void restore_exception(struct excinfo *exc, const char *why, ...)
194{
195 va_list ap;
196 struct excinfo stash;
197
198 if (!PyErr_Occurred())
199 RESTORE_EXCINFO(exc);
200 else {
201 va_start(ap, why);
202 STASH_EXCINFO(&stash);
203 report_lost_exception_v(exc, why, ap);
204 RESTORE_EXCINFO(&stash);
205 va_end(ap);
206 }
207}
208
209/*----- Type definitions --------------------------------------------------*/
210
211static const PyTypeObject emptytype = { 0 };
212
213void *newtype(PyTypeObject *metaty,
214 const PyTypeObject *skel,
215 const char *name)
216{
217 PyHeapTypeObject *ty =
218 (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
219 if (!skel) skel = &emptytype;
220 memcpy(ty, skel, sizeof(*skel));
221 if (ty->ht_type.tp_base) Py_INCREF(ty->ht_type.tp_base);
222#define COPY(blah) do { \
223 if (ty->ht_type.tp_as_##blah) { \
224 memcpy(&ty->as_##blah, \
225 ty->ht_type.tp_as_##blah, \
226 sizeof(ty->as_##blah)); \
227 ty->ht_type.tp_as_##blah = &ty->as_##blah; \
228 } \
229 } while (0)
230 COPY(number);
231 COPY(sequence);
232 COPY(mapping);
233 COPY(buffer);
234#undef COPY
235 if (name)
236 ty->ht_name = PyString_FromString(name);
237 else if (ty->ht_type.tp_name)
238 ty->ht_name = PyString_FromString(ty->ht_type.tp_name);
239 if (ty->ht_name)
240 ty->ht_type.tp_name = PyString_AS_STRING(ty->ht_name);
241 (void)PyObject_INIT(&ty->ht_type, metaty);
242 Py_INCREF(metaty);
243 return (ty);
244}
245
246void typeready(PyTypeObject *ty)
247{
248 PyType_Ready(ty);
249 PyDict_SetItemString(ty->tp_dict, "__module__", modname);
250}
251
252PyTypeObject *inittype(PyTypeObject *tyskel, PyTypeObject *meta)
253{
254 PyTypeObject *ty = newtype(meta, tyskel, 0);
255 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
256 typeready(ty);
257 return (ty);
258}
259
260/*----- Populating modules ------------------------------------------------*/
261
262PyObject *mkexc(PyObject *mod, PyObject *base,
263 const char *name, PyMethodDef *mm)
264{
265 PyObject *nameobj = 0;
266 PyObject *dict = 0;
267 PyObject *exc = 0;
268 PyObject *func = 0;
269 PyObject *meth = 0;
270
271 if ((dict = PyDict_New()) == 0) goto fail;
272
273 if (mm) {
274 while (mm->ml_name) {
275 if ((func = PyCFunction_NewEx(mm, 0, mod)) == 0 ||
276 (meth = PyMethod_New(func, 0, exc)) == 0 ||
277 PyDict_SetItemString(dict, mm->ml_name, meth))
278 goto fail;
279 Py_DECREF(func); func = 0;
280 Py_DECREF(meth); meth = 0;
281 mm++;
282 }
283 }
284
285 if ((nameobj = PyString_FromFormat("%s.%s",
286 PyModule_GetName(mod),
287 name)) == 0 ||
288 (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
289 base, dict)) == 0)
290 goto fail;
291
292done:
293 Py_XDECREF(nameobj);
294 Py_XDECREF(dict);
295 return (exc);
296
297fail:
298 Py_XDECREF(exc);
299 Py_XDECREF(func);
300 Py_XDECREF(meth);
301 exc = 0;
302 goto done;
303}
304
305void setconstants(PyObject *mod, const struct nameval *c)
306{
307 PyObject *x;
308 unsigned long u;
309
310 while (c->name) {
311 u = c->value;
312 if (u <= LONG_MAX) x = PyInt_FromLong(u);
313 else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
314 else x = PyLong_FromUnsignedLong(u);
315 PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
316 c++;
317 }
318}
319
320/*----- Submodules --------------------------------------------------------*/
321
322static PyMethodDef *global_methods;
323static size_t nmethods, methodsz;
324
325void addmethods(const PyMethodDef *m)
326{
327 size_t n, want, newsz;
328
329 for (n = 0; m[n].ml_name; n++);
330 want = nmethods + n + 1;
331 if (want > methodsz) {
332 newsz = methodsz ? 2*methodsz : 16;
333 while (want > newsz) newsz *= 2;
334 if (!global_methods)
335 global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
336 else
337 global_methods = PyObject_Realloc(global_methods,
338 newsz*sizeof(PyMethodDef));
339 assert(global_methods);
340 methodsz = newsz;
341 }
342 memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
343 nmethods += n;
344 global_methods[nmethods].ml_name = 0;
345}
346
347PyMethodDef *donemethods(void) { return (global_methods); }
348
349/*----- Low-level Python interface ----------------------------------------*/
350
351static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
352{
353 PyObject *mod;
354
355 if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
356 return (0);
357 Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
358 RETURN_NONE;
359}
360
361static const PyMethodDef methods[] = {
362#define METHNAME(func) meth_##func
363 METH (_set_home_module, "_set_home_module(MOD)")
364#undef METHNAME
365 { 0 }
366};
367
368void pyke_core_pyinit(void) { addmethods(methods); }
369void pyke_core_pyinsert(PyObject *mod) { ; }
370
371/*----- That's all, folks -------------------------------------------------*/