cef4f822882d7036aaa1ce0dde7d067ba964be3d
[pyke] / pyke.c
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
33 PyObject *modname;
34 PyObject *home_module;
35
36 /*----- Conversions -------------------------------------------------------*/
37
38 PyObject *getulong(unsigned long w)
39 {
40 if (w <= LONG_MAX) return (PyInt_FromLong(w));
41 else return (PyLong_FromUnsignedLong(w));
42 }
43
44 PyObject *getbool(int b)
45 { if (b) RETURN_TRUE; else RETURN_FALSE; }
46
47 int 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);
65 end:
66 return (0);
67 }
68
69 int 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);
78 end:
79 return (0);
80 }
81
82 int 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);
91 end:
92 return (0);
93 }
94
95 int convbool(PyObject *o, void *pp)
96 {
97 if (!o) VALERR("can't delete");
98 *(int *)pp = PyObject_IsTrue(o);
99 return (1);
100 end:
101 return (0);
102 }
103
104 int convbin(PyObject *o, void *pp)
105 {
106 struct bin *r = pp;
107
108 if (BIN_CHECK(o)) {
109 r->p = BIN_PTR(o);
110 r->sz = BIN_LEN(o);
111 return (1);
112 }
113 if (PyUnicode_Check(o)) {
114 o = _PyUnicode_AsDefaultEncodedString(o, 0);
115 if (!o) return (0);
116 r->p = PyString_AS_STRING(o);
117 r->sz = PyString_GET_SIZE(o);
118 return (1);
119 }
120 return (PyObject_AsReadBuffer(o, &r->p, &r->sz) ? 0 : 1);
121 }
122
123 /*----- Miscellaneous utilities -------------------------------------------*/
124
125 PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
126 {
127 PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
128 return (0);
129 }
130
131 /*----- Saving and restoring exceptions ----------------------------------*/
132
133 void report_lost_exception_v(struct excinfo *exc,
134 const char *why, va_list ap)
135 {
136 PyObject *hookfn = 0;
137 PyObject *whyobj = 0;
138 PyObject *obj = 0;
139
140 /* Make sure we start out without a pending exception, or this will get
141 * really confusing.
142 */
143 assert(!PyErr_Occurred());
144
145 /* Format the explanation. */
146 if (why) whyobj = TEXT_VFORMAT(why, ap);
147 else { whyobj = Py_None; Py_INCREF(whyobj); }
148
149 /* Find our home module's `lostexchook' function. This won't work if
150 * there's no module, or the function isn't defined, or it's `None'.
151 */
152 if (!home_module) goto sys;
153 hookfn = PyObject_GetAttrString(home_module, "lostexchook");
154 if (hookfn == Py_None) goto sys;
155 else if (hookfn) ;
156 else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
157 else { PyErr_Clear(); goto sys; }
158
159 /* Call the hook function. */
160 obj = PyObject_CallFunction(hookfn, "(OOOO)",
161 whyobj, exc->ty, exc->val, exc->tb);
162 if (!obj) goto ouch;
163 goto end;
164
165 /* Something went wrong reporting the problem. */
166 ouch:
167 PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
168 PyErr_Print();
169 /* drop through... */
170
171 /* There was no hook, so try to do something sensible using
172 * `sys.excepthook'.
173 */
174 sys:
175 PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n", TEXT_PTR(whyobj));
176 RESTORE_EXCINFO(exc);
177 PyErr_Print();
178 /* drop through... */
179
180 /* Clean up afterwards. */
181 end:
182 Py_XDECREF(hookfn);
183 Py_XDECREF(whyobj);
184 Py_XDECREF(obj);
185 }
186
187 void report_lost_exception(struct excinfo *exc, const char *why, ...)
188 {
189 va_list ap;
190
191 va_start(ap, why);
192 report_lost_exception_v(exc, why, ap);
193 va_end(ap);
194 }
195
196 void stash_exception(struct excinfo *exc, const char *why, ...)
197 {
198 va_list ap;
199 struct excinfo stash;
200
201 if (!exc->ty)
202 STASH_EXCINFO(exc);
203 else {
204 va_start(ap, why);
205 STASH_EXCINFO(&stash);
206 report_lost_exception_v(&stash, why, ap);
207 va_end(ap);
208 }
209 }
210
211 void restore_exception(struct excinfo *exc, const char *why, ...)
212 {
213 va_list ap;
214 struct excinfo stash;
215
216 if (!PyErr_Occurred())
217 RESTORE_EXCINFO(exc);
218 else {
219 va_start(ap, why);
220 STASH_EXCINFO(&stash);
221 report_lost_exception_v(exc, why, ap);
222 RESTORE_EXCINFO(&stash);
223 va_end(ap);
224 }
225 }
226
227 /*----- Type definitions --------------------------------------------------*/
228
229 static const PyTypeObject emptytype = { 0 };
230
231 void *newtype(PyTypeObject *metaty,
232 const PyTypeObject *skel,
233 const char *name)
234 {
235 PyHeapTypeObject *ty =
236 (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
237 if (!skel) skel = &emptytype;
238 memcpy(ty, skel, sizeof(*skel));
239 #define COPY(blah) do { \
240 if (ty->ht_type.tp_as_##blah) { \
241 memcpy(&ty->as_##blah, \
242 ty->ht_type.tp_as_##blah, \
243 sizeof(ty->as_##blah)); \
244 ty->ht_type.tp_as_##blah = &ty->as_##blah; \
245 } \
246 } while (0)
247 COPY(number);
248 COPY(sequence);
249 COPY(mapping);
250 COPY(buffer);
251 #undef COPY
252 if (name)
253 ty->ht_name = TEXT_FROMSTR(name);
254 else if (ty->ht_type.tp_name)
255 ty->ht_name = TEXT_FROMSTR(ty->ht_type.tp_name);
256 else
257 ty->ht_name = 0;
258 if (ty->ht_name)
259 ty->ht_type.tp_name = TEXT_STR(ty->ht_name);
260 ty->ht_slots = 0;
261 (void)PyObject_INIT(&ty->ht_type, metaty);
262 Py_INCREF(metaty);
263 return (ty);
264 }
265
266 void typeready(PyTypeObject *ty)
267 {
268 PyType_Ready(ty);
269 PyDict_SetItemString(ty->tp_dict, "__module__", modname);
270 }
271
272 PyTypeObject *inittype(const PyTypeObject *tyskel,
273 PyTypeObject *base, PyTypeObject *meta)
274 {
275 PyTypeObject *ty = newtype(meta, tyskel, 0);
276 if (base) { ty->tp_base = base; Py_INCREF(base); }
277 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
278 typeready(ty);
279 return (ty);
280 }
281
282 /*----- Populating modules ------------------------------------------------*/
283
284 PyObject *mkexc(PyObject *mod, PyObject *base,
285 const char *name, const PyMethodDef *mm)
286 {
287 PyObject *nameobj = 0;
288 PyObject *dict = 0;
289 PyObject *exc = 0;
290 PyObject *func = 0;
291 PyObject *meth = 0;
292
293 if ((dict = PyDict_New()) == 0) goto fail;
294
295 if (mm) {
296 while (mm->ml_name) {
297 if ((func = PyCFunction_NewEx((/*unconst*/ PyMethodDef *)mm,
298 0, mod)) == 0 ||
299 (meth = PyMethod_New(func, 0, exc)) == 0 ||
300 PyDict_SetItemString(dict, mm->ml_name, meth))
301 goto fail;
302 Py_DECREF(func); func = 0;
303 Py_DECREF(meth); meth = 0;
304 mm++;
305 }
306 }
307
308 if ((nameobj = TEXT_FORMAT("%s.%s", PyModule_GetName(mod), name)) == 0 ||
309 (exc = PyErr_NewException(TEXT_STR(nameobj), base, dict)) == 0)
310 goto fail;
311
312 done:
313 Py_XDECREF(nameobj);
314 Py_XDECREF(dict);
315 return (exc);
316
317 fail:
318 Py_XDECREF(exc);
319 Py_XDECREF(func);
320 Py_XDECREF(meth);
321 exc = 0;
322 goto done;
323 }
324
325 void setconstants(PyObject *mod, const struct nameval *c)
326 {
327 PyObject *x;
328 unsigned long u;
329
330 while (c->name) {
331 u = c->value;
332 if (u <= LONG_MAX) x = PyInt_FromLong(u);
333 else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
334 else x = PyLong_FromUnsignedLong(u);
335 PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
336 c++;
337 }
338 }
339
340 /*----- Submodules --------------------------------------------------------*/
341
342 static PyMethodDef *global_methods;
343 static size_t nmethods, methodsz;
344
345 void addmethods(const PyMethodDef *m)
346 {
347 size_t n, want, newsz;
348
349 for (n = 0; m[n].ml_name; n++);
350 want = nmethods + n + 1;
351 if (want > methodsz) {
352 newsz = methodsz ? 2*methodsz : 16;
353 while (want > newsz) newsz *= 2;
354 if (!global_methods)
355 global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
356 else
357 global_methods = PyObject_Realloc(global_methods,
358 newsz*sizeof(PyMethodDef));
359 assert(global_methods);
360 methodsz = newsz;
361 }
362 memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
363 nmethods += n;
364 global_methods[nmethods].ml_name = 0;
365 }
366
367 PyMethodDef *donemethods(void) { return (global_methods); }
368
369 /*----- Low-level Python interface ----------------------------------------*/
370
371 static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
372 {
373 PyObject *mod;
374
375 if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
376 return (0);
377 Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
378 RETURN_NONE;
379 }
380
381 static const PyMethodDef methods[] = {
382 #define METHNAME(func) meth_##func
383 METH (_set_home_module, "_set_home_module(MOD)")
384 #undef METHNAME
385 { 0 }
386 };
387
388 void pyke_core_pyinit(void) { addmethods(methods); }
389 void pyke_core_pyinsert(PyObject *mod) { ; }
390
391 /*----- That's all, folks -------------------------------------------------*/