py_exception.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #include "pocketpy/objects/error.h"
  2. #include "pocketpy/pocketpy.h"
  3. #include "pocketpy/common/utils.h"
  4. #include "pocketpy/interpreter/vm.h"
  5. #include "pocketpy/common/sstream.h"
  6. #include "pocketpy/objects/exception.h"
  7. void py_BaseException__stpush(py_Frame* frame,
  8. py_Ref self,
  9. SourceData_ src,
  10. int lineno,
  11. const char* func_name) {
  12. BaseException* ud = py_touserdata(self);
  13. int max_frame_dumps = py_debugger_isattached() ? 31 : 7;
  14. if(ud->stacktrace.length >= max_frame_dumps) return;
  15. BaseExceptionFrame* frame_dump = c11_vector__emplace(&ud->stacktrace);
  16. PK_INCREF(src);
  17. frame_dump->src = src;
  18. frame_dump->lineno = lineno;
  19. frame_dump->name = func_name ? c11_string__new(func_name) : NULL;
  20. if(py_debugger_isattached()) {
  21. if(frame != NULL) {
  22. py_Frame_newlocals(frame, &frame_dump->locals);
  23. py_Frame_newglobals(frame, &frame_dump->globals);
  24. } else {
  25. py_newdict(&frame_dump->locals);
  26. py_newdict(&frame_dump->globals);
  27. }
  28. }
  29. }
  30. static void BaseException__dtor(void* ud) {
  31. BaseException* self = (BaseException*)ud;
  32. c11__foreach(BaseExceptionFrame, &self->stacktrace, it) {
  33. PK_DECREF(it->src);
  34. if(it->name) c11_string__delete(it->name);
  35. }
  36. c11_vector__dtor(&self->stacktrace);
  37. }
  38. static bool _py_BaseException__new__(int argc, py_Ref argv) {
  39. py_Type cls = py_totype(argv);
  40. BaseException* ud = py_newobject(py_retval(), cls, 0, sizeof(BaseException));
  41. py_newnil(&ud->args);
  42. py_newnil(&ud->inner_exc);
  43. c11_vector__ctor(&ud->stacktrace, sizeof(BaseExceptionFrame));
  44. return true;
  45. }
  46. static bool _py_BaseException__init__(int argc, py_Ref argv) {
  47. BaseException* ud = py_touserdata(argv);
  48. py_newnone(py_retval());
  49. if(argc == 1 + 0) return true;
  50. if(argc == 1 + 1) {
  51. py_assign(&ud->args, &argv[1]);
  52. return true;
  53. }
  54. return TypeError("__init__() takes at most 1 arguments but %d were given", argc - 1);
  55. }
  56. static bool _py_BaseException__repr__(int argc, py_Ref argv) {
  57. PY_CHECK_ARGC(1);
  58. BaseException* ud = py_touserdata(argv);
  59. c11_sbuf ss;
  60. c11_sbuf__ctor(&ss);
  61. pk_sprintf(&ss, "%t(", argv->type);
  62. py_Ref args = &ud->args;
  63. if(!py_isnil(args)) {
  64. if(!py_repr(args)) return false;
  65. c11_sbuf__write_sv(&ss, py_tosv(py_retval()));
  66. }
  67. c11_sbuf__write_char(&ss, ')');
  68. c11_sbuf__py_submit(&ss, py_retval());
  69. return true;
  70. }
  71. static bool _py_BaseException__str__(int argc, py_Ref argv) {
  72. PY_CHECK_ARGC(1);
  73. BaseException* ud = py_touserdata(argv);
  74. c11_sbuf ss;
  75. c11_sbuf__ctor(&ss);
  76. py_Ref args = &ud->args;
  77. if(!py_isnil(args)) {
  78. if(argv->type == tp_KeyError) {
  79. if(!py_repr(args)) return false;
  80. } else {
  81. if(!py_str(args)) return false;
  82. }
  83. c11_sbuf__write_sv(&ss, py_tosv(py_retval()));
  84. }
  85. c11_sbuf__py_submit(&ss, py_retval());
  86. return true;
  87. }
  88. static bool BaseException_args(int argc, py_Ref argv) {
  89. BaseException* ud = py_touserdata(argv);
  90. PY_CHECK_ARGC(1);
  91. py_Ref args = &ud->args;
  92. if(!py_isnil(args)) {
  93. py_Ref p = py_newtuple(py_retval(), 1);
  94. p[0] = *args;
  95. } else {
  96. py_newtuple(py_retval(), 0);
  97. }
  98. return true;
  99. }
  100. static bool StopIteration_value(int argc, py_Ref argv) {
  101. BaseException* ud = py_touserdata(argv);
  102. PY_CHECK_ARGC(1);
  103. py_Ref args = &ud->args;
  104. if(py_isnil(args)) {
  105. py_newnone(py_retval());
  106. } else {
  107. py_assign(py_retval(), args);
  108. }
  109. return true;
  110. }
  111. py_Type pk_BaseException__register() {
  112. py_Type type = pk_newtype("BaseException", tp_object, NULL, BaseException__dtor, false, false);
  113. py_bindmagic(type, __new__, _py_BaseException__new__);
  114. py_bindmagic(type, __init__, _py_BaseException__init__);
  115. py_bindmagic(type, __repr__, _py_BaseException__repr__);
  116. py_bindmagic(type, __str__, _py_BaseException__str__);
  117. py_bindproperty(type, "args", BaseException_args, NULL);
  118. return type;
  119. }
  120. py_Type pk_Exception__register() {
  121. py_Type type = pk_newtype("Exception", tp_BaseException, NULL, NULL, false, false);
  122. return type;
  123. }
  124. py_Type pk_StopIteration__register() {
  125. py_Type type = pk_newtype("StopIteration", tp_Exception, NULL, NULL, false, false);
  126. py_bindproperty(type, "value", StopIteration_value, NULL);
  127. return type;
  128. }
  129. //////////////////////////////////////////////////
  130. bool py_checkexc() {
  131. VM* vm = pk_current_vm;
  132. return !py_isnil(&vm->unhandled_exc);
  133. }
  134. bool py_matchexc(py_Type type) {
  135. VM* vm = pk_current_vm;
  136. if(py_isnil(&vm->unhandled_exc)) return false;
  137. bool ok = py_issubclass(vm->unhandled_exc.type, type);
  138. if(ok) vm->last_retval = vm->unhandled_exc;
  139. return ok;
  140. }
  141. void py_clearexc(py_StackRef p0) {
  142. VM* vm = pk_current_vm;
  143. py_newnil(&vm->unhandled_exc);
  144. if(p0) {
  145. c11__rtassert(p0 >= vm->stack.begin && p0 <= vm->stack.sp);
  146. vm->stack.sp = p0;
  147. }
  148. }
  149. static void c11_sbuf__write_exc(c11_sbuf* self, py_Ref exc) {
  150. c11_sbuf__write_cstr(self, "Traceback (most recent call last):\n");
  151. BaseException* ud = py_touserdata(exc);
  152. for(int i = ud->stacktrace.length - 1; i >= 0; i--) {
  153. BaseExceptionFrame* frame = c11__at(BaseExceptionFrame, &ud->stacktrace, i);
  154. SourceData__snapshot(frame->src,
  155. self,
  156. frame->lineno,
  157. NULL,
  158. frame->name ? frame->name->data : NULL);
  159. c11_sbuf__write_char(self, '\n');
  160. }
  161. const char* name = py_tpname(exc->type);
  162. char* message = safe_stringify_exception(exc);
  163. c11_sbuf__write_cstr(self, name);
  164. c11_sbuf__write_cstr(self, ": ");
  165. c11_sbuf__write_cstr(self, message);
  166. PK_FREE(message);
  167. }
  168. char* safe_stringify_exception(py_Ref exc) {
  169. VM* vm = pk_current_vm;
  170. const char* message = "<exception str() failed>";
  171. py_Ref tmp = py_pushtmp();
  172. py_Ref old_unhandled_exc = py_pushtmp();
  173. *tmp = *exc;
  174. *old_unhandled_exc = vm->unhandled_exc;
  175. py_newnil(&vm->unhandled_exc);
  176. py_StackRef p0 = py_peek(0);
  177. bool ok = py_str(tmp);
  178. if(ok) {
  179. if(py_isstr(py_retval())) message = py_tostr(py_retval());
  180. } else {
  181. py_clearexc(p0);
  182. }
  183. vm->unhandled_exc = *old_unhandled_exc;
  184. py_shrink(2);
  185. return c11_strdup(message);
  186. }
  187. void py_printexc() {
  188. char* msg = py_formatexc();
  189. if(!msg) return;
  190. pk_current_vm->callbacks.print(msg);
  191. pk_current_vm->callbacks.print("\n");
  192. PK_FREE(msg);
  193. }
  194. char* py_formatexc() {
  195. VM* vm = pk_current_vm;
  196. if(py_isnil(&vm->unhandled_exc)) return NULL;
  197. char* res = formatexc_internal(&vm->unhandled_exc);
  198. if(py_debugger_isattached()) py_debugger_exceptionbreakpoint(&vm->unhandled_exc);
  199. return res;
  200. }
  201. char* formatexc_internal(py_Ref exc) {
  202. c11__rtassert(exc != NULL);
  203. c11__rtassert(py_issubclass(exc->type, tp_BaseException));
  204. c11_sbuf ss;
  205. c11_sbuf__ctor(&ss);
  206. BaseException* ud = py_touserdata(exc);
  207. py_Ref inner = &ud->inner_exc;
  208. if(py_isnil(inner)) {
  209. c11_sbuf__write_exc(&ss, exc);
  210. } else {
  211. c11_sbuf__write_exc(&ss, inner);
  212. c11_sbuf__write_cstr(
  213. &ss,
  214. "\n\nDuring handling of the above exception, another exception occurred:\n\n");
  215. c11_sbuf__write_exc(&ss, exc);
  216. }
  217. c11_string* res = c11_sbuf__submit(&ss);
  218. char* dup = PK_MALLOC(res->size + 1);
  219. memcpy(dup, res->data, res->size);
  220. dup[res->size] = '\0';
  221. c11_string__delete(res);
  222. return dup;
  223. }
  224. bool py_exception(py_Type type, const char* fmt, ...) {
  225. #ifndef NDEBUG
  226. if(py_checkexc()) {
  227. const char* name = py_tpname(pk_current_vm->unhandled_exc.type);
  228. c11__abort("py_exception(): `%s` was already set!", name);
  229. }
  230. #endif
  231. c11_sbuf buf;
  232. c11_sbuf__ctor(&buf);
  233. va_list args;
  234. va_start(args, fmt);
  235. pk_vsprintf(&buf, fmt, args);
  236. va_end(args);
  237. py_Ref message = py_pushtmp();
  238. c11_sbuf__py_submit(&buf, message);
  239. bool ok = py_tpcall(type, 1, message);
  240. if(!ok) return false;
  241. py_pop();
  242. return py_raise(py_retval());
  243. }
  244. bool py_raise(py_Ref exc) {
  245. assert(py_isinstance(exc, tp_BaseException));
  246. VM* vm = pk_current_vm;
  247. if(vm->top_frame) {
  248. FrameExcInfo* info = Frame__top_exc_info(vm->top_frame);
  249. if(info && !py_isnil(&info->exc)) {
  250. BaseException* ud = py_touserdata(exc);
  251. ud->inner_exc = info->exc;
  252. }
  253. }
  254. assert(py_isnil(&vm->unhandled_exc));
  255. vm->unhandled_exc = *exc;
  256. return false;
  257. }
  258. bool KeyError(py_Ref key) {
  259. bool ok = py_tpcall(tp_KeyError, 1, key);
  260. if(!ok) return false;
  261. return py_raise(py_retval());
  262. }