blob: 829b147853070c83182cb97d13bb51b0196fdba6 [file] [log] [blame]
Damiend99b0522013-12-21 18:17:45 +00001#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
11typedef 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
18void 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
38const mp_obj_type_t exception_type = {
39 { &mp_const_type },
40 "exception",
Damien George97209d32014-01-07 15:58:30 +000041 .print = exception_print,
Damiend99b0522013-12-21 18:17:45 +000042};
43
44mp_obj_t mp_obj_new_exception(qstr id) {
45 mp_obj_exception_t *o = m_new_obj(mp_obj_exception_t);
46 o->base.type = &exception_type;
47 o->id = id;
48 o->n_args = 0;
49 return o;
50}
51
52mp_obj_t mp_obj_new_exception_msg(qstr id, const char *msg) {
53 mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 1);
54 o->base.type = &exception_type;
55 o->id = id;
56 o->n_args = 1;
57 o->args[0] = msg;
58 return o;
59}
60
61mp_obj_t mp_obj_new_exception_msg_1_arg(qstr id, const char *fmt, const char *a1) {
62 mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 2);
63 o->base.type = &exception_type;
64 o->id = id;
65 o->n_args = 2;
66 o->args[0] = fmt;
67 o->args[1] = a1;
68 return o;
69}
70
71mp_obj_t mp_obj_new_exception_msg_2_args(qstr id, const char *fmt, const char *a1, const char *a2) {
72 mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 3);
73 o->base.type = &exception_type;
74 o->id = id;
75 o->n_args = 3;
76 o->args[0] = fmt;
77 o->args[1] = a1;
78 o->args[2] = a2;
79 return o;
80}
Damienb86e3f92013-12-29 17:17:43 +000081
82qstr mp_obj_exception_get_type(mp_obj_t self_in) {
83 assert(MP_OBJ_IS_TYPE(self_in, &exception_type));
84 mp_obj_exception_t *self = self_in;
85 return self->id;
86}