py: add variable argument exception constructor function.

Addresses issue #104.
This commit is contained in:
Damien George
2014-01-08 18:11:23 +00:00
parent 199b9e04eb
commit 6c73ca1e75
8 changed files with 63 additions and 30 deletions

View File

@@ -1,6 +1,7 @@
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include "nlr.h"
@@ -79,6 +80,37 @@ mp_obj_t mp_obj_new_exception_msg_2_args(qstr id, const char *fmt, const char *a
return o;
}
mp_obj_t mp_obj_new_exception_msg_varg(qstr id, const char *fmt, ...) {
// count number of arguments by number of % signs, excluding %%
int n_args = 1; // count fmt
for (const char *s = fmt; *s; s++) {
if (*s == '%') {
if (s[1] == '%') {
s += 1;
} else {
n_args += 1;
}
}
}
// make exception object
mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, n_args);
o->base.type = &exception_type;
o->id = id;
o->n_args = n_args;
o->args[0] = fmt;
// extract args and store them
va_list ap;
va_start(ap, fmt);
for (int i = 1; i < n_args; i++) {
o->args[i] = va_arg(ap, void*);
}
va_end(ap);
return o;
}
qstr mp_obj_exception_get_type(mp_obj_t self_in) {
assert(MP_OBJ_IS_TYPE(self_in, &exception_type));
mp_obj_exception_t *self = self_in;