objclosure.c 1.32 KB
Newer Older
1
2
#include <stdlib.h>
#include <stdint.h>
Damien George's avatar
Damien George committed
3
#include <string.h>
4
5
6
7
8
9
10
11
12
13
14
#include <assert.h>

#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
#include "obj.h"
#include "runtime.h"

typedef struct _mp_obj_closure_t {
    mp_obj_base_t base;
    mp_obj_t fun;
Damien George's avatar
Damien George committed
15
16
    uint n_closed;
    mp_obj_t *closed;
17
18
} mp_obj_closure_t;

Damien George's avatar
Damien George committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// args are in reverse order in the array
mp_obj_t closure_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) {
    mp_obj_closure_t *self = self_in;

    // concatenate args and closed-over-vars, in reverse order
    // TODO perhaps cache this array so we don't need to create it each time we are called
    mp_obj_t *args2 = m_new(mp_obj_t, self->n_closed + n_args);
    memcpy(args2, args, n_args * sizeof(mp_obj_t));
    for (int i = 0; i < self->n_closed; i++) {
        args2[n_args + i] = self->closed[self->n_closed - 1 - i];
    }

    // call the function with the new vars array
    return rt_call_function_n(self->fun, n_args + self->n_closed, args2);
}

35
36
37
const mp_obj_type_t closure_type = {
    { &mp_const_type },
    "closure",
38
    .call_n = closure_call_n,
39
40
41
42
43
44
};

mp_obj_t mp_obj_new_closure(mp_obj_t fun, mp_obj_t closure_tuple) {
    mp_obj_closure_t *o = m_new_obj(mp_obj_closure_t);
    o->base.type = &closure_type;
    o->fun = fun;
Damien George's avatar
Damien George committed
45
    mp_obj_tuple_get(closure_tuple, &o->n_closed, &o->closed);
46
47
    return o;
}