Damien | d99b052 | 2013-12-21 18:17:45 +0000 | [diff] [blame] | 1 | #include <stdlib.h> |
| 2 | #include <stdint.h> |
| 3 | #include <string.h> |
| 4 | #include <assert.h> |
| 5 | |
| 6 | #include "nlr.h" |
| 7 | #include "misc.h" |
| 8 | #include "mpconfig.h" |
| 9 | #include "obj.h" |
| 10 | |
| 11 | typedef struct mp_obj_exception_t { |
| 12 | mp_obj_base_t base; |
| 13 | qstr id; |
| 14 | int n_args; |
| 15 | const void *args[]; |
| 16 | } mp_obj_exception_t; |
| 17 | |
| 18 | void exception_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t o_in) { |
| 19 | mp_obj_exception_t *o = o_in; |
| 20 | switch (o->n_args) { |
| 21 | case 0: |
| 22 | print(env, "%s", qstr_str(o->id)); |
| 23 | break; |
| 24 | case 1: |
| 25 | print(env, "%s: %s", qstr_str(o->id), (const char*)o->args[0]); |
| 26 | break; |
| 27 | case 2: |
| 28 | print(env, "%s: ", qstr_str(o->id)); |
| 29 | print(env, (const char*)o->args[0], o->args[1]); |
| 30 | break; |
| 31 | default: // here we just assume at least 3 args, but only use first 3 |
| 32 | print(env, "%s: ", qstr_str(o->id)); |
| 33 | print(env, (const char*)o->args[0], o->args[1], o->args[2]); |
| 34 | break; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | const mp_obj_type_t exception_type = { |
| 39 | { &mp_const_type }, |
| 40 | "exception", |
| 41 | exception_print, // print |
| 42 | NULL, // call_n |
| 43 | NULL, // unary_op |
| 44 | NULL, // binary_op |
| 45 | NULL, // getiter |
| 46 | NULL, // iternext |
| 47 | {{NULL, NULL},}, // method list |
| 48 | }; |
| 49 | |
| 50 | mp_obj_t mp_obj_new_exception(qstr id) { |
| 51 | mp_obj_exception_t *o = m_new_obj(mp_obj_exception_t); |
| 52 | o->base.type = &exception_type; |
| 53 | o->id = id; |
| 54 | o->n_args = 0; |
| 55 | return o; |
| 56 | } |
| 57 | |
| 58 | mp_obj_t mp_obj_new_exception_msg(qstr id, const char *msg) { |
| 59 | mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 1); |
| 60 | o->base.type = &exception_type; |
| 61 | o->id = id; |
| 62 | o->n_args = 1; |
| 63 | o->args[0] = msg; |
| 64 | return o; |
| 65 | } |
| 66 | |
| 67 | mp_obj_t mp_obj_new_exception_msg_1_arg(qstr id, const char *fmt, const char *a1) { |
| 68 | mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 2); |
| 69 | o->base.type = &exception_type; |
| 70 | o->id = id; |
| 71 | o->n_args = 2; |
| 72 | o->args[0] = fmt; |
| 73 | o->args[1] = a1; |
| 74 | return o; |
| 75 | } |
| 76 | |
| 77 | mp_obj_t mp_obj_new_exception_msg_2_args(qstr id, const char *fmt, const char *a1, const char *a2) { |
| 78 | mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 3); |
| 79 | o->base.type = &exception_type; |
| 80 | o->id = id; |
| 81 | o->n_args = 3; |
| 82 | o->args[0] = fmt; |
| 83 | o->args[1] = a1; |
| 84 | o->args[2] = a2; |
| 85 | return o; |
| 86 | } |