blob: 22b8c58126018e1f07ddb0f2977509b0ae40a9bd [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",
41 exception_print, // print
Damien George71c51812014-01-04 20:21:15 +000042 NULL, // make_new
Damiend99b0522013-12-21 18:17:45 +000043 NULL, // call_n
44 NULL, // unary_op
45 NULL, // binary_op
46 NULL, // getiter
47 NULL, // iternext
Paul Sokolovsky860ffb02014-01-05 22:34:09 +020048 .methods = {{NULL, NULL},},
Damiend99b0522013-12-21 18:17:45 +000049};
50
51mp_obj_t mp_obj_new_exception(qstr id) {
52 mp_obj_exception_t *o = m_new_obj(mp_obj_exception_t);
53 o->base.type = &exception_type;
54 o->id = id;
55 o->n_args = 0;
56 return o;
57}
58
59mp_obj_t mp_obj_new_exception_msg(qstr id, const char *msg) {
60 mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 1);
61 o->base.type = &exception_type;
62 o->id = id;
63 o->n_args = 1;
64 o->args[0] = msg;
65 return o;
66}
67
68mp_obj_t mp_obj_new_exception_msg_1_arg(qstr id, const char *fmt, const char *a1) {
69 mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 2);
70 o->base.type = &exception_type;
71 o->id = id;
72 o->n_args = 2;
73 o->args[0] = fmt;
74 o->args[1] = a1;
75 return o;
76}
77
78mp_obj_t mp_obj_new_exception_msg_2_args(qstr id, const char *fmt, const char *a1, const char *a2) {
79 mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, 3);
80 o->base.type = &exception_type;
81 o->id = id;
82 o->n_args = 3;
83 o->args[0] = fmt;
84 o->args[1] = a1;
85 o->args[2] = a2;
86 return o;
87}
Damienb86e3f92013-12-29 17:17:43 +000088
89qstr mp_obj_exception_get_type(mp_obj_t self_in) {
90 assert(MP_OBJ_IS_TYPE(self_in, &exception_type));
91 mp_obj_exception_t *self = self_in;
92 return self->id;
93}