2013-12-21 13:17:45 -05:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdint.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <assert.h>
|
|
|
|
|
|
|
|
#include "nlr.h"
|
|
|
|
#include "misc.h"
|
|
|
|
#include "mpconfig.h"
|
2014-01-04 10:57:35 -05:00
|
|
|
#include "mpqstr.h"
|
2013-12-21 13:17:45 -05:00
|
|
|
#include "obj.h"
|
|
|
|
#include "runtime.h"
|
|
|
|
#include "map.h"
|
|
|
|
|
|
|
|
typedef struct _mp_obj_class_t {
|
|
|
|
mp_obj_base_t base;
|
|
|
|
mp_map_t *locals;
|
|
|
|
} mp_obj_class_t;
|
|
|
|
|
|
|
|
// args are in reverse order in the array
|
|
|
|
mp_obj_t class_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) {
|
|
|
|
// instantiate an instance of a class
|
|
|
|
|
|
|
|
mp_obj_class_t *self = self_in;
|
|
|
|
|
|
|
|
// make instance
|
|
|
|
mp_obj_t o = mp_obj_new_instance(self_in);
|
|
|
|
|
|
|
|
// look for __init__ function
|
2014-01-08 12:33:12 -05:00
|
|
|
mp_map_elem_t *init_fn = mp_map_lookup(self->locals, MP_OBJ_NEW_QSTR(MP_QSTR___init__), MP_MAP_LOOKUP);
|
2013-12-21 13:17:45 -05:00
|
|
|
|
|
|
|
if (init_fn != NULL) {
|
|
|
|
// call __init__ function
|
|
|
|
mp_obj_t init_ret;
|
|
|
|
if (n_args == 0) {
|
|
|
|
init_ret = rt_call_function_n(init_fn->value, 1, (mp_obj_t*)&o);
|
|
|
|
} else {
|
|
|
|
mp_obj_t *args2 = m_new(mp_obj_t, n_args + 1);
|
|
|
|
memcpy(args2, args, n_args * sizeof(mp_obj_t));
|
|
|
|
args2[n_args] = o;
|
|
|
|
init_ret = rt_call_function_n(init_fn->value, n_args + 1, args2);
|
2013-12-29 14:33:23 -05:00
|
|
|
m_del(mp_obj_t, args2, n_args + 1);
|
2013-12-21 13:17:45 -05:00
|
|
|
}
|
|
|
|
if (init_ret != mp_const_none) {
|
2014-01-04 10:57:35 -05:00
|
|
|
nlr_jump(mp_obj_new_exception_msg_1_arg(MP_QSTR_TypeError, "__init__() should return None, not '%s'", mp_obj_get_type_str(init_ret)));
|
2013-12-21 13:17:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
} else {
|
|
|
|
// TODO
|
|
|
|
if (n_args != 0) {
|
2014-01-04 10:57:35 -05:00
|
|
|
nlr_jump(mp_obj_new_exception_msg_1_arg(MP_QSTR_TypeError, "function takes 0 positional arguments but %d were given", (void*)(machine_int_t)n_args));
|
2013-12-21 13:17:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return o;
|
|
|
|
}
|
|
|
|
|
|
|
|
mp_map_t *mp_obj_class_get_locals(mp_obj_t self_in) {
|
|
|
|
assert(MP_OBJ_IS_TYPE(self_in, &class_type));
|
|
|
|
mp_obj_class_t *self = self_in;
|
|
|
|
return self->locals;
|
|
|
|
}
|
|
|
|
|
|
|
|
const mp_obj_type_t class_type = {
|
|
|
|
{ &mp_const_type },
|
|
|
|
"class",
|
2014-01-07 10:58:30 -05:00
|
|
|
.call_n = class_call_n,
|
2013-12-21 13:17:45 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
mp_obj_t mp_obj_new_class(mp_map_t *class_locals) {
|
|
|
|
mp_obj_class_t *o = m_new_obj(mp_obj_class_t);
|
|
|
|
o->base.type = &class_type;
|
|
|
|
o->locals = class_locals;
|
|
|
|
return o;
|
|
|
|
}
|