chiark / gitweb /
mp.c, catacomb/__init__.py, pyke/: Fix mixed-mode arithmetic involving `float'.
[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 PyObject *enrich_compare(int op, int cmp)
132 {
133   int r = -1;
134
135   switch (op) {
136     case Py_LT: r = cmp <  0; break;
137     case Py_LE: r = cmp <= 0; break;
138     case Py_EQ: r = cmp == 0; break;
139     case Py_NE: r = cmp != 0; break;
140     case Py_GE: r = cmp >= 0; break;
141     case Py_GT: r = cmp >  0; break;
142     default: assert(0);
143   }
144   return (getbool(r));
145 }
146
147 /*----- Saving and restoring exceptions ----------------------------------*/
148
149 void report_lost_exception_v(struct excinfo *exc,
150                              const char *why, va_list ap)
151 {
152   PyObject *hookfn = 0;
153   PyObject *whyobj = 0;
154   PyObject *obj = 0;
155
156   /* Make sure we start out without a pending exception, or this will get
157    * really confusing.
158    */
159   assert(!PyErr_Occurred());
160
161   /* Format the explanation. */
162   if (why) whyobj = TEXT_VFORMAT(why, ap);
163   else { whyobj = Py_None; Py_INCREF(whyobj); }
164
165   /* Find our home module's `lostexchook' function.  This won't work if
166    * there's no module, or the function isn't defined, or it's `None'.
167    */
168   if (!home_module) goto sys;
169   hookfn = PyObject_GetAttrString(home_module, "lostexchook");
170   if (hookfn == Py_None) goto sys;
171   else if (hookfn) ;
172   else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
173   else { PyErr_Clear(); goto sys; }
174
175   /* Call the hook function. */
176   obj = PyObject_CallFunction(hookfn, "(OOOO)",
177                               whyobj, exc->ty, exc->val, exc->tb);
178   if (!obj) goto ouch;
179   goto end;
180
181   /* Something went wrong reporting the problem. */
182 ouch:
183   PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
184   PyErr_Print();
185   /* drop through... */
186
187   /* There was no hook, so try to do something sensible using
188    * `sys.excepthook'.
189    */
190 sys:
191   PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n", TEXT_PTR(whyobj));
192   RESTORE_EXCINFO(exc);
193   PyErr_Print();
194   /* drop through... */
195
196   /* Clean up afterwards. */
197 end:
198   Py_XDECREF(hookfn);
199   Py_XDECREF(whyobj);
200   Py_XDECREF(obj);
201 }
202
203 void report_lost_exception(struct excinfo *exc, const char *why, ...)
204 {
205   va_list ap;
206
207   va_start(ap, why);
208   report_lost_exception_v(exc, why, ap);
209   va_end(ap);
210 }
211
212 void stash_exception(struct excinfo *exc, const char *why, ...)
213 {
214   va_list ap;
215   struct excinfo stash;
216
217   if (!exc->ty)
218     STASH_EXCINFO(exc);
219   else {
220     va_start(ap, why);
221     STASH_EXCINFO(&stash);
222     report_lost_exception_v(&stash, why, ap);
223     va_end(ap);
224   }
225 }
226
227 void restore_exception(struct excinfo *exc, const char *why, ...)
228 {
229   va_list ap;
230   struct excinfo stash;
231
232   if (!PyErr_Occurred())
233     RESTORE_EXCINFO(exc);
234   else {
235     va_start(ap, why);
236     STASH_EXCINFO(&stash);
237     report_lost_exception_v(exc, why, ap);
238     RESTORE_EXCINFO(&stash);
239     va_end(ap);
240   }
241 }
242
243 /*----- Type definitions --------------------------------------------------*/
244
245 static const PyTypeObject emptytype = { 0 };
246
247 void *newtype(PyTypeObject *metaty,
248               const PyTypeObject *skel,
249               const char *name)
250 {
251   PyHeapTypeObject *ty =
252     (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
253   if (!skel) skel = &emptytype;
254   memcpy(ty, skel, sizeof(*skel));
255 #define COPY(blah) do {                                                 \
256     if (ty->ht_type.tp_as_##blah) {                                     \
257       memcpy(&ty->as_##blah,                                            \
258              ty->ht_type.tp_as_##blah,                                  \
259              sizeof(ty->as_##blah));                                    \
260       ty->ht_type.tp_as_##blah = &ty->as_##blah;                        \
261     }                                                                   \
262   } while (0)
263   COPY(number);
264   COPY(sequence);
265   COPY(mapping);
266   COPY(buffer);
267 #undef COPY
268   if (name)
269     ty->ht_name = TEXT_FROMSTR(name);
270   else if (ty->ht_type.tp_name)
271     ty->ht_name = TEXT_FROMSTR(ty->ht_type.tp_name);
272   else
273     ty->ht_name = 0;
274   if (ty->ht_name)
275     ty->ht_type.tp_name = TEXT_STR(ty->ht_name);
276   ty->ht_slots = 0;
277   (void)PyObject_INIT(&ty->ht_type, metaty);
278   Py_INCREF(metaty);
279   return (ty);
280 }
281
282 void typeready(PyTypeObject *ty)
283 {
284   PyType_Ready(ty);
285   PyDict_SetItemString(ty->tp_dict, "__module__", modname);
286 }
287
288 PyTypeObject *inittype(const PyTypeObject *tyskel,
289                        PyTypeObject *base, PyTypeObject *meta)
290 {
291   PyTypeObject *ty = newtype(meta, tyskel, 0);
292   if (base) { ty->tp_base = base; Py_INCREF(base); }
293   ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
294   typeready(ty);
295   return (ty);
296 }
297
298 /*----- Populating modules ------------------------------------------------*/
299
300 PyObject *mkexc(PyObject *mod, PyObject *base,
301                 const char *name, const PyMethodDef *mm)
302 {
303   PyObject *nameobj = 0;
304   PyObject *dict = 0;
305   PyObject *exc = 0;
306   PyObject *func = 0;
307   PyObject *meth = 0;
308
309   if ((dict = PyDict_New()) == 0) goto fail;
310
311   if (mm) {
312     while (mm->ml_name) {
313       if ((func = PyCFunction_NewEx((/*unconst*/ PyMethodDef *)mm,
314                                     0, mod)) == 0 ||
315           (meth = PyMethod_New(func, 0, exc)) == 0 ||
316           PyDict_SetItemString(dict, mm->ml_name, meth))
317         goto fail;
318       Py_DECREF(func); func = 0;
319       Py_DECREF(meth); meth = 0;
320       mm++;
321     }
322   }
323
324   if ((nameobj = TEXT_FORMAT("%s.%s", PyModule_GetName(mod), name)) == 0 ||
325       (exc = PyErr_NewException(TEXT_STR(nameobj), base, dict)) == 0)
326     goto fail;
327
328 done:
329   Py_XDECREF(nameobj);
330   Py_XDECREF(dict);
331   return (exc);
332
333 fail:
334   Py_XDECREF(exc);
335   Py_XDECREF(func);
336   Py_XDECREF(meth);
337   exc = 0;
338   goto done;
339 }
340
341 void setconstants(PyObject *mod, const struct nameval *c)
342 {
343   PyObject *x;
344   unsigned long u;
345
346   while (c->name) {
347     u = c->value;
348     if (u <= LONG_MAX) x = PyInt_FromLong(u);
349     else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
350     else x = PyLong_FromUnsignedLong(u);
351     PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
352     c++;
353   }
354 }
355
356 /*----- Submodules --------------------------------------------------------*/
357
358 static PyMethodDef *global_methods;
359 static size_t nmethods, methodsz;
360
361 void addmethods(const PyMethodDef *m)
362 {
363   size_t n, want, newsz;
364
365   for (n = 0; m[n].ml_name; n++);
366   want = nmethods + n + 1;
367   if (want > methodsz) {
368     newsz = methodsz ? 2*methodsz : 16;
369     while (want > newsz) newsz *= 2;
370     if (!global_methods)
371       global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
372     else
373       global_methods = PyObject_Realloc(global_methods,
374                                         newsz*sizeof(PyMethodDef));
375     assert(global_methods);
376     methodsz = newsz;
377   }
378   memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
379   nmethods += n;
380   global_methods[nmethods].ml_name = 0;
381 }
382
383 PyMethodDef *donemethods(void) { return (global_methods); }
384
385 /*----- Low-level Python interface ----------------------------------------*/
386
387 static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
388 {
389   PyObject *mod;
390
391   if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
392     return (0);
393   Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
394   RETURN_NONE;
395 }
396
397 static const PyMethodDef methods[] = {
398 #define METHNAME(func) meth_##func
399   METH  (_set_home_module, "_set_home_module(MOD)")
400 #undef METHNAME
401   { 0 }
402 };
403
404 void pyke_core_pyinit(void) { addmethods(methods); }
405 void pyke_core_pyinsert(PyObject *mod) { ; }
406
407 /*----- That's all, folks -------------------------------------------------*/