This repository was archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_pyexc.cpp
More file actions
732 lines (600 loc) · 19.5 KB
/
Copy path_pyexc.cpp
File metadata and controls
732 lines (600 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/*
PyExc - Python exception manager - 1.1.2 (by awolverp)
*/
#include <Python.h>
#include <unordered_map>
/*
- State
*/
typedef struct
{
std::unordered_map<int, PyObject *>* exceptions;
int last_state;
// Callback
PyObject* callback;
} PyExcState;
#define getstate(o) ((PyExcState *)PyModule_GetState(o))
/*
- Internal Functions
*/
static inline int _internal_pyexc_occurred(PyExcState *state, int state_n) { return state->exceptions->count(state_n); }
static inline int _internal_pyexc_clear(PyExcState *state, int state_n) {
try {
PyObject* value = state->exceptions->at(state_n);
Py_XDECREF(value);
return state->exceptions->erase(state_n);
} catch (...) {
return 0;
}
}
static inline int _internal_pyexc_clear_all(PyExcState *state) {
if (!state->exceptions->size()) {
return 0;
}
for (auto iter = state->exceptions->cbegin(); iter != state->exceptions->cend(); iter++)
{
Py_XDECREF(iter->second);
}
state->exceptions->clear();
return 1;
}
// Don't forget to use Py_XINCREF ...
static inline PyObject* _internal_pyexc_get_exc(PyExcState* state, int state_n) {
try { return state->exceptions->at(state_n); } catch (...) { return Py_None; }
}
static inline int _internal_pyexc_set_exc(PyExcState* state, int state_n, PyObject* exc, int block) {
Py_INCREF(exc);
if (!PyObject_IsInstance(exc, (PyObject *)Py_TYPE(PyExc_BaseException)) && !PyObject_IsInstance(exc, PyExc_BaseException))
{
Py_XDECREF(exc);
return -1;
}
if (_internal_pyexc_occurred(state, state_n)) {
if (block) {
Py_XDECREF(exc);
return 0;
}
_internal_pyexc_clear(state, state_n);
}
state->exceptions->emplace(std::pair<int, PyObject*>(state_n, exc));
state->last_state = state_n;
return 1;
}
static inline void _internal_pyexc_raise_exc(PyExcState* state, int state_n, int clear)
{
int occurred = 0;
Py_BEGIN_ALLOW_THREADS
occurred = _internal_pyexc_occurred(state, state_n);
Py_END_ALLOW_THREADS
if (!occurred)
{
PyErr_SetNone(PyExc_SystemError);
return;
}
PyObject* exc = state->exceptions->at(state_n);
if (PyObject_IsInstance(exc, (PyObject *)Py_TYPE(PyExc_BaseException)))
{
PyErr_SetNone(exc);
}
else if (PyObject_IsInstance(exc, PyExc_BaseException))
{
PyTypeObject *type = Py_TYPE(exc);
PyBaseExceptionObject *value = (PyBaseExceptionObject *)exc;
PyErr_SetObject((PyObject *)type, (PyObject *)value);
}
if (clear) {
Py_BEGIN_ALLOW_THREADS
_internal_pyexc_clear(state, state_n);
Py_END_ALLOW_THREADS
}
}
static inline int _internal_pyexc_print_exc(PyExcState* state, int state_n, int clear)
{
int occurred = 0;
Py_BEGIN_ALLOW_THREADS
occurred = _internal_pyexc_occurred(state, state_n);
Py_END_ALLOW_THREADS
if (!occurred)
{
return 0;
}
PyObject* exc = state->exceptions->at(state_n);
if (PyObject_IsInstance(exc, (PyObject *)Py_TYPE(PyExc_BaseException)))
{
PyErr_SetNone(exc);
}
else if (PyObject_IsInstance(exc, PyExc_BaseException))
{
PyTypeObject *type = Py_TYPE(exc);
PyBaseExceptionObject *value = (PyBaseExceptionObject *)exc;
PyErr_SetObject((PyObject *)type, (PyObject *)value);
}
PyErr_Print();
if (clear) {
Py_BEGIN_ALLOW_THREADS
_internal_pyexc_clear(state, state_n);
Py_END_ALLOW_THREADS
}
return 1;
}
static inline int _internal_pyexc_set_callback(PyExcState* state, PyObject* callback)
{
if (callback == NULL)
return 0;
if (callback == Py_None)
{
Py_BEGIN_ALLOW_THREADS
if (state->callback != NULL)
{
Py_DECREF(state->callback);
state->callback = NULL;
}
Py_END_ALLOW_THREADS
return 1;
}
if (!PyCallable_Check(callback))
return 0;
Py_BEGIN_ALLOW_THREADS
if (state->callback != NULL)
{
Py_DECREF(state->callback);
state->callback = NULL;
}
Py_INCREF(callback);
state->callback = callback;
Py_END_ALLOW_THREADS
return 1;
}
static inline int _internal_pyexc_call_callback(PyExcState* state, int state_n, PyObject* exc)
{
PyObject* callback = NULL;
Py_BEGIN_ALLOW_THREADS
callback = state->callback;
Py_END_ALLOW_THREADS
if (callback == NULL)
return 1;
PyObject* args = Py_BuildValue("(i,O)", state_n, exc);
PyObject* result = PyObject_CallObject(callback, args);
Py_DECREF(args);
if (result == NULL)
return 0;
Py_DECREF(result);
return 1;
}
static inline PyObject* _internal_pyexc_call(PyExcState* state, int state_n, PyObject* func, PyObject* args, PyObject* kwargs)
{
if (func == NULL || !PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError, "func must be callable.");
return NULL;
}
bool clear_args = false;
if (args == NULL) {
args = Py_BuildValue("()");
clear_args = true;
}
if (!PyTuple_Check(args)) {
// exit carefully
if (clear_args) {
Py_DECREF(args);
}
PyErr_SetString(PyExc_TypeError, "args must be tuple.");
return NULL;
}
PyObject* result = PyObject_Call(func, args, kwargs);
if (clear_args) {
Py_DECREF(args);
}
if (result == NULL) {
PyObject *type = PyErr_Occurred();
if (type != NULL) {
_internal_pyexc_set_exc(state, state_n, type, 0);
PyErr_Clear();
}
Py_RETURN_NONE;
}
return result;
}
static inline PyObject* _internal_pyexc_rcall(PyObject* func, PyObject* args, PyObject* kwargs)
{
if (func == NULL || !PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError, "func must be callable.");
return NULL;
}
bool clear_args = false;
if (args == NULL) {
args = Py_BuildValue("()");
clear_args = true;
}
if (!PyTuple_Check(args)) {
// exit carefully
if (clear_args) {
Py_DECREF(args);
}
PyErr_SetString(PyExc_TypeError, "args must be tuple.");
return NULL;
}
PyObject* result = PyObject_Call(func, args, kwargs);
if (clear_args) {
Py_DECREF(args);
}
if (result == NULL) {
PyObject* exc = PyErr_Occurred();
if (exc != NULL) {
result = exc;
Py_INCREF(result);
PyErr_Clear();
}
}
return result;
}
/*
- Functions
*/
/**
* Check is exception occurred on @c state or not.
*
* @param state (int) state number
*
* @return Returns True if exception occurred, otherwise False.
*/
static PyObject *Pyexc_Occurred(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"state", NULL};
int state_n = 0, result = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", keywords, &state_n))
return NULL;
Py_BEGIN_ALLOW_THREADS
PyExcState *state = getstate(self);
result = _internal_pyexc_occurred(state, state_n);
Py_END_ALLOW_THREADS
return PyBool_FromLong((long)result);
}
/**
* Clear exception which is occurred on @c state.
*
* @param state (int) state number
*
* @return Returns True if exception occurred and cleared, otherwise False.
*/
static PyObject *Pyexc_Clear(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"state", NULL};
int state_n = 0, result = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", keywords, &state_n))
return NULL;
Py_BEGIN_ALLOW_THREADS
PyExcState *state = getstate(self);
result = _internal_pyexc_clear(state, state_n);
Py_END_ALLOW_THREADS
return PyBool_FromLong((long)result);
}
/**
* Clear all occurred exceptions.
*
* @return Returns True if any exception occurred and cleared, otherwise False.
*/
static PyObject *Pyexc_ClearAll(PyObject *self, PyObject *__unused_args)
{
int result = 0;
Py_BEGIN_ALLOW_THREADS
PyExcState *state = getstate(self);
result = _internal_pyexc_clear_all(state);
Py_END_ALLOW_THREADS
return PyBool_FromLong((long)result);
}
/**
* @param state (int) state number
*
* @return Returns exception if exception occurred on @c state, otherwise None.
*/
static PyObject *Pyexc_GetExc(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"state", NULL};
int state_n = 0;
PyObject* result = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", keywords, &state_n))
return NULL;
Py_BEGIN_ALLOW_THREADS
PyExcState *state = getstate(self);
result = _internal_pyexc_get_exc(state, state_n);
Py_END_ALLOW_THREADS
Py_XINCREF(result);
return result;
}
/**
* @brief Set exception.
*
* @param exc (PyObject*) Exception type.
* @param state (int) Exception argument.
* @param block (bool) If True and an exception setted, break and returns False. (default False)
*
* @returns Returns True if setted.
*/
static PyObject *Pyexc_SetExc(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"exc", (char *)"state", (char *)"block", NULL};
PyObject *exc = NULL;
int state_n = 0, block = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ip", keywords, &exc, &state_n, &block))
return NULL;
int result = 0;
PyExcState *state = NULL;
Py_BEGIN_ALLOW_THREADS
state = getstate(self);
result = _internal_pyexc_set_exc(state, state_n, exc, block);
Py_END_ALLOW_THREADS
if (result == -1) {
PyErr_SetString(PyExc_TypeError, "a BaseException is required for `exc` argument");
return NULL;
}
if (result == 1)
{
// call callback
int is_fail = _internal_pyexc_call_callback(state, state_n, exc);
if (!is_fail)
return NULL;
}
return PyBool_FromLong((long)result);
}
/**
* @brief Raise occurred exception.
*
* @param state (int) state number
* @param clear (bool) clear state after raise (default True)
*
* @throw If exception occurred, Raise that, otherwise raise SystemError.
*/
static PyObject *Pyexc_RaiseExc(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"state", (char *)"clear", NULL};
int state_n = 0, clear = 1;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ip", keywords, &state_n, &clear))
return NULL;
PyExcState* state;
Py_BEGIN_ALLOW_THREADS
state = getstate(self);
Py_END_ALLOW_THREADS
_internal_pyexc_raise_exc(state, state_n, clear);
return NULL;
}
/**
* @brief Print occurred exception.
*
* @param state (int) state number
* @param clear (bool) clear state after print (default True)
*
* @returns If exception occurred, Print that and return True, otherwise return False.
*/
static PyObject *Pyexc_PrintExc(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"state", (char *)"clear", NULL};
int state_n = 0, clear = 1;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ip", keywords, &state_n, &clear))
return NULL;
PyExcState* state;
Py_BEGIN_ALLOW_THREADS
state = getstate(self);
Py_END_ALLOW_THREADS
return PyBool_FromLong((long)_internal_pyexc_print_exc(state, state_n, clear));
}
/**
* @brief Set callback for setExc function.
*
* @param callback (PyObject*) callable or None object
*
* @return None
*/
static PyObject *Pyexc_SetCallback(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"callback", NULL};
PyObject* callback = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", keywords, &callback))
return NULL;
PyExcState* state = getstate(self);
int result = _internal_pyexc_set_callback(state, callback);
if (result == 0)
{
PyErr_SetString(PyExc_TypeError, "a callable or None object is required");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *Pyexc_Call(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"func", (char *)"state", (char *)"args", (char *)"kwargs", NULL};
PyObject* func = NULL;
int state_n = 0;
PyObject* args_func = NULL;
PyObject* kwargs_func = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|iOO", keywords, &func, &state_n, &args_func, &kwargs_func))
return NULL;
PyExcState* state;
Py_BEGIN_ALLOW_THREADS
state = getstate(self);
Py_END_ALLOW_THREADS
PyObject* result = _internal_pyexc_call(state, state_n, func, args_func, kwargs_func);
return result;
}
static PyObject *Pyexc_RCall(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *keywords[] = {(char *)"func", (char *)"args", (char *)"kwargs", NULL};
PyObject* func = NULL;
PyObject* args_func = NULL;
PyObject* kwargs_func = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO", keywords, &func, &args_func, &kwargs_func))
return NULL;
PyObject* result = _internal_pyexc_rcall(func, args_func, kwargs_func);
return result;
}
static PyObject *Pyexc_LenStates(PyObject *self, PyObject *__unused_args)
{
size_t result = 0;
Py_BEGIN_ALLOW_THREADS
PyExcState *state = getstate(self);
result = state->exceptions->size();
Py_END_ALLOW_THREADS
return PyLong_FromSize_t(result);
}
static PyObject *Pyexc_MaxState(PyObject *self, PyObject *__unused_args)
{
int result = 0;
Py_BEGIN_ALLOW_THREADS
PyExcState *state = getstate(self);
for (auto iter = state->exceptions->cbegin(); iter != state->exceptions->cend(); iter++)
{
int i = iter->first;
if (i > result)
result = i;
}
Py_END_ALLOW_THREADS
return PyLong_FromLong((long)result);
}
static PyObject *Pyexc_States(PyObject *self, PyObject *__unused_args)
{
PyObject *result = NULL;
PyExcState *state = getstate(self);
Py_BEGIN_ALLOW_THREADS
result = PyList_New(state->exceptions->size());
Py_END_ALLOW_THREADS
if (result == NULL)
return NULL;
Py_BEGIN_ALLOW_THREADS
int count = 0;
for (auto iter = state->exceptions->cbegin(); iter != state->exceptions->cend(); iter++)
{
PyObject* rev = Py_BuildValue("i", iter->first);
PyList_SetItem(result, count, rev);
count++;
}
Py_END_ALLOW_THREADS
return result;
}
static PyObject *Pyexc_Version(PyObject *self, PyObject *__unused_args) { return Py_BuildValue("(i,i,i)", 1, 3, 2); }
static PyObject *Pyexc___sizeof__(PyObject *self, PyObject *__unused_args)
{
PyExcState *state = getstate(self);
size_t size = state->exceptions->size();
return PyLong_FromSize_t(
(size_t)(size * sizeof(PyObject*)) + (size * sizeof(int))
);
}
/*
- Module
*/
static void __pyexc_Free(PyObject *self)
{
PyExcState *state = getstate(self);
if (state->callback != NULL)
Py_DECREF(state->callback);
state->callback = NULL;
for (auto iter = state->exceptions->cbegin(); iter != state->exceptions->cend(); iter++)
{
Py_XDECREF(iter->second);
}
delete state->exceptions;
}
static PyMethodDef pyexc_methods[] = {
{
"occurred", (PyCFunction)Pyexc_Occurred, METH_VARARGS | METH_KEYWORDS,
"If an exception is occurred, returns `True`, otherwise `False`."
},
{
"clear", (PyCFunction)Pyexc_Clear, METH_VARARGS | METH_KEYWORDS,
"If an exception is occurred and successfully erased, returns `True`, otherwise `False`."
},
{
"clearAll", (PyCFunction)Pyexc_ClearAll, METH_NOARGS,
"If any exception is occurred and successfully erased, returns `True`, otherwise `False`."
},
{
"getExc", (PyCFunction)Pyexc_GetExc, METH_VARARGS | METH_KEYWORDS,
"Returns the exception which is occurred in `state` scope.\n\nIf any exception not occurred in `state` scope, returns `None`."
},
{
"setExc", (PyCFunction)Pyexc_SetExc, METH_VARARGS | METH_KEYWORDS,
"Set an exception in `state` scope.\n\n" \
"Parameters:\n" \
" exc (`BaseException | Type[BaseException]`):\n" \
" An instance of `BaseException`.\n" \
" state (`int`):\n" \
" scope.\n" \
" block (`bool`):\n" \
" If True and already any exception have occurred in `state` scope, returns `False`.\n\n" \
"Returns:\n" \
"`True` if setted, otherwise `False`."
},
{
"raiseExc", (PyCFunction)Pyexc_RaiseExc, METH_VARARGS | METH_KEYWORDS,
"Raise the exception which is occurred in `state` scope." \
"If any exception not occurred in `state` scope, will raise `SystemError`.\n\n" \
"Parameters:\n" \
" state (`int`):\n" \
" scope.\n" \
" clear (`bool`):\n" \
" will erase the exception after raise - default `True`."
},
{
"printExc", (PyCFunction)Pyexc_PrintExc, METH_VARARGS | METH_KEYWORDS,
"Print the exception which is occurred in `state` scope.\n\n" \
"Parameters:\n" \
" state (`int`):\n" \
" scope.\n" \
" clear (`bool`):\n" \
" will erase the exception after print - default True."
},
{
"setCallback", (PyCFunction)Pyexc_SetCallback, METH_VARARGS | METH_KEYWORDS,
"Set callback function. The callback function will call after each use of `setExc`.\n\n" \
"Callback Function Arguments:\n" \
" state (`int`):\n" \
" scope.\n" \
" exc (`BaseException | Type[BaseException]`):\n" \
" An instance of BaseException."
},
{
"call", (PyCFunction)Pyexc_Call, METH_VARARGS | METH_KEYWORDS,
"Calls `func` with `args` and `kwargs` parameters. " \
"If `func` raised exception, exception will sets in `state` scope and returns `None`.\n\n" \
"Parameters:\n"
" func (`Callable`):\n"
" function.\n"
" state (`int`):\n"
" scope.\n"
" args (`tuple`):\n"
" function args.\n"
" kwargs (`dict`):\n"
" function kwargs.\n"
},
{
"rcall", (PyCFunction)Pyexc_RCall, METH_VARARGS | METH_KEYWORDS,
"Like `pyexc.call` but returns exception instead of set in `state` scope."
},
{
"lenStates", (PyCFunction)Pyexc_LenStates, METH_NOARGS,
"Returns `len(states)`."
},
{
"maxState", (PyCFunction)Pyexc_MaxState, METH_NOARGS,
"Returns the biggest number of states."
},
{"states", (PyCFunction)Pyexc_States, METH_NOARGS, "Returns states."},
{"version", (PyCFunction)Pyexc_Version, METH_NOARGS, "Returns PyExc version as tuple."},
{"__sizeof__", (PyCFunction)Pyexc___sizeof__, METH_NOARGS, "Returns allocated memory size in `Bytes`."},
{NULL, NULL, 0, NULL},
};
struct PyModuleDef pyexc_module = {
PyModuleDef_HEAD_INIT,
.m_name = "pyexc",
.m_doc = "Python exception managing ...",
.m_size = sizeof(PyExcState),
.m_methods = pyexc_methods,
.m_free = (freefunc)__pyexc_Free,
};
PyMODINIT_FUNC PyInit__pyexc() {
PyObject* m = PyModule_Create(&pyexc_module);
if (m == NULL)
return NULL;
PyExcState* state = getstate(m);
state->exceptions = new std::unordered_map<int, PyObject*>;
return m;
}