*.c: Use the new `Py_TYPE' and `Py_SIZE' macros; define them if necessary.
[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));
c1756f78
MW
221#define COPY(blah) do { \
222 if (ty->ht_type.tp_as_##blah) { \
223 memcpy(&ty->as_##blah, \
224 ty->ht_type.tp_as_##blah, \
225 sizeof(ty->as_##blah)); \
226 ty->ht_type.tp_as_##blah = &ty->as_##blah; \
227 } \
228 } while (0)
229 COPY(number);
230 COPY(sequence);
231 COPY(mapping);
232 COPY(buffer);
233#undef COPY
234 if (name)
235 ty->ht_name = PyString_FromString(name);
236 else if (ty->ht_type.tp_name)
237 ty->ht_name = PyString_FromString(ty->ht_type.tp_name);
238 if (ty->ht_name)
239 ty->ht_type.tp_name = PyString_AS_STRING(ty->ht_name);
1b026fd1 240 ty->ht_slots = 0;
c1756f78
MW
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
747ddb1b
MW
252PyTypeObject *inittype(const PyTypeObject *tyskel,
253 PyTypeObject *base, PyTypeObject *meta)
c1756f78
MW
254{
255 PyTypeObject *ty = newtype(meta, tyskel, 0);
747ddb1b 256 if (base) { ty->tp_base = base; Py_INCREF(base); }
c1756f78
MW
257 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
258 typeready(ty);
259 return (ty);
260}
261
262/*----- Populating modules ------------------------------------------------*/
263
264PyObject *mkexc(PyObject *mod, PyObject *base,
87fa2d56 265 const char *name, const PyMethodDef *mm)
c1756f78
MW
266{
267 PyObject *nameobj = 0;
268 PyObject *dict = 0;
269 PyObject *exc = 0;
270 PyObject *func = 0;
271 PyObject *meth = 0;
272
273 if ((dict = PyDict_New()) == 0) goto fail;
274
275 if (mm) {
276 while (mm->ml_name) {
87fa2d56
MW
277 if ((func = PyCFunction_NewEx((/*unconst*/ PyMethodDef *)mm,
278 0, mod)) == 0 ||
c1756f78
MW
279 (meth = PyMethod_New(func, 0, exc)) == 0 ||
280 PyDict_SetItemString(dict, mm->ml_name, meth))
281 goto fail;
282 Py_DECREF(func); func = 0;
283 Py_DECREF(meth); meth = 0;
284 mm++;
285 }
286 }
287
288 if ((nameobj = PyString_FromFormat("%s.%s",
289 PyModule_GetName(mod),
290 name)) == 0 ||
291 (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
292 base, dict)) == 0)
293 goto fail;
294
295done:
296 Py_XDECREF(nameobj);
297 Py_XDECREF(dict);
298 return (exc);
299
300fail:
301 Py_XDECREF(exc);
302 Py_XDECREF(func);
303 Py_XDECREF(meth);
304 exc = 0;
305 goto done;
306}
307
308void setconstants(PyObject *mod, const struct nameval *c)
309{
310 PyObject *x;
311 unsigned long u;
312
313 while (c->name) {
314 u = c->value;
315 if (u <= LONG_MAX) x = PyInt_FromLong(u);
316 else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
317 else x = PyLong_FromUnsignedLong(u);
318 PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
319 c++;
320 }
321}
322
323/*----- Submodules --------------------------------------------------------*/
324
325static PyMethodDef *global_methods;
326static size_t nmethods, methodsz;
327
328void addmethods(const PyMethodDef *m)
329{
330 size_t n, want, newsz;
331
332 for (n = 0; m[n].ml_name; n++);
333 want = nmethods + n + 1;
334 if (want > methodsz) {
335 newsz = methodsz ? 2*methodsz : 16;
336 while (want > newsz) newsz *= 2;
337 if (!global_methods)
338 global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
339 else
340 global_methods = PyObject_Realloc(global_methods,
341 newsz*sizeof(PyMethodDef));
342 assert(global_methods);
343 methodsz = newsz;
344 }
345 memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
346 nmethods += n;
347 global_methods[nmethods].ml_name = 0;
348}
349
350PyMethodDef *donemethods(void) { return (global_methods); }
351
352/*----- Low-level Python interface ----------------------------------------*/
353
354static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
355{
356 PyObject *mod;
357
358 if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
359 return (0);
360 Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
361 RETURN_NONE;
362}
363
364static const PyMethodDef methods[] = {
365#define METHNAME(func) meth_##func
366 METH (_set_home_module, "_set_home_module(MOD)")
367#undef METHNAME
368 { 0 }
369};
370
371void pyke_core_pyinit(void) { addmethods(methods); }
372void pyke_core_pyinsert(PyObject *mod) { ; }
373
374/*----- That's all, folks -------------------------------------------------*/