chiark / gitweb /
@@@ mdwopt buggy wip
[mLib-python] / 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
fcc8f4ca
MW
47int convlong(PyObject *o, void *pp)
48{
49 long *p = pp;
50 PyObject *t;
51
52 if (!o) VALERR("can't delete");
53#ifdef PY2
54 if (PyInt_Check(o))
55 *p = PyInt_AS_LONG(o);
56 else
57#endif
58 {
59 if ((t = PyNumber_Index(o)) == 0) goto end;
60 *p = PyLong_AsLong(t);
61 Py_DECREF(t);
62 if (PyErr_Occurred()) goto end;
63 }
64 return (1);
65end:
66 return (0);
67}
68
69int convint(PyObject *o, void *pp)
70{
71 long l;
72 int *p = pp;
73
74 if (!convlong(o, &l)) goto end;
75 if (INT_MIN > l || l > INT_MAX) VALERR("out of range");
76 *p = l;
77 return (1);
78end:
79 return (0);
80}
81
c1756f78
MW
82int convulong(PyObject *o, void *pp)
83{
c1756f78
MW
84 unsigned long *p = pp;
85 PyObject *t;
86
87 if (!o) VALERR("can't delete");
c80de12d 88#ifdef PY2
c1756f78 89 if (PyInt_Check(o)) {
83a72c0d 90 long i = PyInt_AS_LONG(o);
c1756f78
MW
91 if (i < 0) VALERR("must be nonnegative");
92 *p = i;
83a72c0d 93 } else
c80de12d 94#endif
83a72c0d 95 {
fcc8f4ca 96 if ((t = PyNumber_Index(o)) == 0) goto end;
c1756f78
MW
97 *p = PyLong_AsUnsignedLong(t);
98 Py_DECREF(t);
99 if (PyErr_Occurred()) goto end;
100 }
101 return (1);
102end:
103 return (0);
104}
105
106int convuint(PyObject *o, void *pp)
107{
108 unsigned long u;
109 unsigned *p = pp;
110
111 if (!convulong(o, &u)) goto end;
112 if (u > UINT_MAX) VALERR("out of range");
113 *p = u;
114 return (1);
115end:
116 return (0);
117}
118
119int convszt(PyObject *o, void *pp)
120{
121 unsigned long u;
122 size_t *p = pp;
123
124 if (!convulong(o, &u)) goto end;
125 if (u > ~(size_t)0) VALERR("out of range");
126 *p = u;
127 return (1);
128end:
129 return (0);
130}
131
132int convbool(PyObject *o, void *pp)
133{
134 if (!o) VALERR("can't delete");
135 *(int *)pp = PyObject_IsTrue(o);
136 return (1);
137end:
138 return (0);
139}
140
7e18a150
MW
141int convbin(PyObject *o, void *pp)
142{
143 struct bin *r = pp;
144
e0a7dece
MW
145 if (BIN_CHECK(o)) {
146 r->p = BIN_PTR(o);
147 r->sz = BIN_LEN(o);
7e18a150
MW
148 return (1);
149 }
c80de12d 150#ifdef PY2
7e18a150
MW
151 if (PyUnicode_Check(o)) {
152 o = _PyUnicode_AsDefaultEncodedString(o, 0);
153 if (!o) return (0);
154 r->p = PyString_AS_STRING(o);
155 r->sz = PyString_GET_SIZE(o);
156 return (1);
157 }
c80de12d 158#endif
7e18a150
MW
159 return (PyObject_AsReadBuffer(o, &r->p, &r->sz) ? 0 : 1);
160}
161
c1756f78
MW
162/*----- Miscellaneous utilities -------------------------------------------*/
163
164PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
165{
166 PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
167 return (0);
168}
169
1c0e9c88
MW
170PyObject *enrich_compare(int op, int cmp)
171{
172 int r = -1;
173
174 switch (op) {
175 case Py_LT: r = cmp < 0; break;
176 case Py_LE: r = cmp <= 0; break;
177 case Py_EQ: r = cmp == 0; break;
178 case Py_NE: r = cmp != 0; break;
179 case Py_GE: r = cmp >= 0; break;
180 case Py_GT: r = cmp > 0; break;
181 default: assert(0);
182 }
183 return (getbool(r));
184}
185
c1756f78
MW
186/*----- Saving and restoring exceptions ----------------------------------*/
187
188void report_lost_exception_v(struct excinfo *exc,
189 const char *why, va_list ap)
190{
191 PyObject *hookfn = 0;
192 PyObject *whyobj = 0;
193 PyObject *obj = 0;
194
195 /* Make sure we start out without a pending exception, or this will get
196 * really confusing.
197 */
198 assert(!PyErr_Occurred());
199
200 /* Format the explanation. */
e0a7dece 201 if (why) whyobj = TEXT_VFORMAT(why, ap);
c1756f78
MW
202 else { whyobj = Py_None; Py_INCREF(whyobj); }
203
204 /* Find our home module's `lostexchook' function. This won't work if
205 * there's no module, or the function isn't defined, or it's `None'.
206 */
207 if (!home_module) goto sys;
208 hookfn = PyObject_GetAttrString(home_module, "lostexchook");
209 if (hookfn == Py_None) goto sys;
210 else if (hookfn) ;
211 else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
212 else { PyErr_Clear(); goto sys; }
213
214 /* Call the hook function. */
215 obj = PyObject_CallFunction(hookfn, "(OOOO)",
216 whyobj, exc->ty, exc->val, exc->tb);
217 if (!obj) goto ouch;
218 goto end;
219
220 /* Something went wrong reporting the problem. */
221ouch:
222 PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
223 PyErr_Print();
224 /* drop through... */
225
226 /* There was no hook, so try to do something sensible using
227 * `sys.excepthook'.
228 */
229sys:
e0a7dece 230 PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n", TEXT_PTR(whyobj));
c1756f78
MW
231 RESTORE_EXCINFO(exc);
232 PyErr_Print();
233 /* drop through... */
234
235 /* Clean up afterwards. */
236end:
237 Py_XDECREF(hookfn);
238 Py_XDECREF(whyobj);
239 Py_XDECREF(obj);
240}
241
242void report_lost_exception(struct excinfo *exc, const char *why, ...)
243{
244 va_list ap;
245
246 va_start(ap, why);
247 report_lost_exception_v(exc, why, ap);
248 va_end(ap);
249}
250
251void stash_exception(struct excinfo *exc, const char *why, ...)
252{
253 va_list ap;
254 struct excinfo stash;
255
256 if (!exc->ty)
257 STASH_EXCINFO(exc);
258 else {
259 va_start(ap, why);
260 STASH_EXCINFO(&stash);
261 report_lost_exception_v(&stash, why, ap);
262 va_end(ap);
263 }
264}
265
266void restore_exception(struct excinfo *exc, const char *why, ...)
267{
268 va_list ap;
269 struct excinfo stash;
270
271 if (!PyErr_Occurred())
272 RESTORE_EXCINFO(exc);
273 else {
274 va_start(ap, why);
275 STASH_EXCINFO(&stash);
276 report_lost_exception_v(exc, why, ap);
277 RESTORE_EXCINFO(&stash);
278 va_end(ap);
279 }
280}
281
282/*----- Type definitions --------------------------------------------------*/
283
284static const PyTypeObject emptytype = { 0 };
285
286void *newtype(PyTypeObject *metaty,
287 const PyTypeObject *skel,
288 const char *name)
289{
290 PyHeapTypeObject *ty =
291 (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
292 if (!skel) skel = &emptytype;
293 memcpy(ty, skel, sizeof(*skel));
c1756f78
MW
294#define COPY(blah) do { \
295 if (ty->ht_type.tp_as_##blah) { \
296 memcpy(&ty->as_##blah, \
297 ty->ht_type.tp_as_##blah, \
298 sizeof(ty->as_##blah)); \
299 ty->ht_type.tp_as_##blah = &ty->as_##blah; \
300 } \
301 } while (0)
302 COPY(number);
303 COPY(sequence);
304 COPY(mapping);
305 COPY(buffer);
306#undef COPY
307 if (name)
e0a7dece 308 ty->ht_name = TEXT_FROMSTR(name);
c1756f78 309 else if (ty->ht_type.tp_name)
e0a7dece
MW
310 ty->ht_name = TEXT_FROMSTR(ty->ht_type.tp_name);
311 else
312 ty->ht_name = 0;
c1756f78 313 if (ty->ht_name)
e0a7dece 314 ty->ht_type.tp_name = TEXT_STR(ty->ht_name);
1b026fd1 315 ty->ht_slots = 0;
c80de12d
MW
316#ifdef PY3
317 ty->ht_qualname = 0;
318#endif
c1756f78
MW
319 (void)PyObject_INIT(&ty->ht_type, metaty);
320 Py_INCREF(metaty);
321 return (ty);
322}
323
324void typeready(PyTypeObject *ty)
325{
c80de12d
MW
326#ifdef PY3
327 PyHeapTypeObject *hty = (PyHeapTypeObject *)ty;
328 hty->ht_qualname = hty->ht_name;
329#endif
c1756f78
MW
330 PyType_Ready(ty);
331 PyDict_SetItemString(ty->tp_dict, "__module__", modname);
332}
333
747ddb1b
MW
334PyTypeObject *inittype(const PyTypeObject *tyskel,
335 PyTypeObject *base, PyTypeObject *meta)
c1756f78
MW
336{
337 PyTypeObject *ty = newtype(meta, tyskel, 0);
747ddb1b 338 if (base) { ty->tp_base = base; Py_INCREF(base); }
c1756f78
MW
339 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
340 typeready(ty);
341 return (ty);
342}
343
344/*----- Populating modules ------------------------------------------------*/
345
346PyObject *mkexc(PyObject *mod, PyObject *base,
87fa2d56 347 const char *name, const PyMethodDef *mm)
c1756f78
MW
348{
349 PyObject *nameobj = 0;
350 PyObject *dict = 0;
351 PyObject *exc = 0;
352 PyObject *func = 0;
353 PyObject *meth = 0;
354
355 if ((dict = PyDict_New()) == 0) goto fail;
356
357 if (mm) {
358 while (mm->ml_name) {
87fa2d56
MW
359 if ((func = PyCFunction_NewEx((/*unconst*/ PyMethodDef *)mm,
360 0, mod)) == 0 ||
c80de12d
MW
361 (meth = PY23(PyMethod_New(func, 0, exc),
362 PyInstanceMethod_New(func))) == 0 ||
c1756f78
MW
363 PyDict_SetItemString(dict, mm->ml_name, meth))
364 goto fail;
365 Py_DECREF(func); func = 0;
366 Py_DECREF(meth); meth = 0;
367 mm++;
368 }
369 }
370
e0a7dece
MW
371 if ((nameobj = TEXT_FORMAT("%s.%s", PyModule_GetName(mod), name)) == 0 ||
372 (exc = PyErr_NewException(TEXT_STR(nameobj), base, dict)) == 0)
c1756f78
MW
373 goto fail;
374
375done:
376 Py_XDECREF(nameobj);
377 Py_XDECREF(dict);
378 return (exc);
379
380fail:
381 Py_XDECREF(exc);
382 Py_XDECREF(func);
383 Py_XDECREF(meth);
384 exc = 0;
385 goto done;
386}
387
388void setconstants(PyObject *mod, const struct nameval *c)
389{
390 PyObject *x;
391 unsigned long u;
392
393 while (c->name) {
394 u = c->value;
395 if (u <= LONG_MAX) x = PyInt_FromLong(u);
396 else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
397 else x = PyLong_FromUnsignedLong(u);
398 PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
399 c++;
400 }
401}
402
403/*----- Submodules --------------------------------------------------------*/
404
405static PyMethodDef *global_methods;
406static size_t nmethods, methodsz;
407
408void addmethods(const PyMethodDef *m)
409{
410 size_t n, want, newsz;
411
412 for (n = 0; m[n].ml_name; n++);
413 want = nmethods + n + 1;
414 if (want > methodsz) {
415 newsz = methodsz ? 2*methodsz : 16;
416 while (want > newsz) newsz *= 2;
417 if (!global_methods)
418 global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
419 else
420 global_methods = PyObject_Realloc(global_methods,
421 newsz*sizeof(PyMethodDef));
422 assert(global_methods);
423 methodsz = newsz;
424 }
425 memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
426 nmethods += n;
427 global_methods[nmethods].ml_name = 0;
428}
429
430PyMethodDef *donemethods(void) { return (global_methods); }
431
432/*----- Low-level Python interface ----------------------------------------*/
433
434static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
435{
436 PyObject *mod;
437
438 if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
439 return (0);
440 Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
441 RETURN_NONE;
442}
443
444static const PyMethodDef methods[] = {
445#define METHNAME(func) meth_##func
446 METH (_set_home_module, "_set_home_module(MOD)")
447#undef METHNAME
448 { 0 }
449};
450
451void pyke_core_pyinit(void) { addmethods(methods); }
452void pyke_core_pyinsert(PyObject *mod) { ; }
453
454/*----- That's all, folks -------------------------------------------------*/