objfun.c 17.5 KB
Newer Older
xbe's avatar
xbe committed
1
#include <stdbool.h>
2
3
4
#include <stdlib.h>
#include <string.h>
#include <assert.h>
5
6
7
8
#ifdef __MINGW32__
// For alloca()
#include <malloc.h>
#endif
9
10
11
12

#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
13
#include "qstr.h"
14
#include "obj.h"
15
#include "objtuple.h"
Paul Sokolovsky's avatar
Paul Sokolovsky committed
16
#include "objfun.h"
Damien George's avatar
Damien George committed
17
#include "runtime0.h"
18
19
20
#include "runtime.h"
#include "bc.h"

21
22
23
#if 0 // print debugging info
#define DEBUG_PRINT (1)
#else // don't print debugging info
24
#define DEBUG_printf(...) (void)0
25
26
#endif

27
28
29
30
31
/******************************************************************************/
/* native functions                                                           */

// mp_obj_fun_native_t defined in obj.h

32
33
34
35
36
37
38
39
40
41
STATIC mp_obj_t fun_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
    switch (op) {
        case MP_BINARY_OP_EQUAL:
            // These objects can be equal only if it's the same underlying structure,
            // we don't even need to check for 2nd arg type.
            return MP_BOOL(lhs_in == rhs_in);
    }
    return NULL;
}

42
STATIC mp_obj_t fun_native_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
43
    assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_native));
44
    mp_obj_fun_native_t *self = self_in;
45

46
    // check number of arguments
47
    mp_arg_check_num(n_args, n_kw, self->n_args_min, self->n_args_max, self->is_kw);
48

49
    if (self->is_kw) {
50
51
        // function allows keywords

52
53
54
        // we create a map directly from the given args array
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
55

56
        return ((mp_fun_kw_t)self->fun)(n_args, args, &kw_args);
57

58
    } else if (self->n_args_min <= 3 && self->n_args_min == self->n_args_max) {
59
60
61
62
63
64
65
66
67
68
69
        // function requires a fixed number of arguments

        // dispatch function call
        switch (self->n_args_min) {
            case 0:
                return ((mp_fun_0_t)self->fun)();

            case 1:
                return ((mp_fun_1_t)self->fun)(args[0]);

            case 2:
70
                return ((mp_fun_2_t)self->fun)(args[0], args[1]);
71

72
            case 3:
73
                return ((mp_fun_3_t)self->fun)(args[0], args[1], args[2]);
74

75
76
77
78
79
80
            default:
                assert(0);
                return mp_const_none;
        }

    } else {
81
        // function takes a variable number of arguments, but no keywords
82

83
        return ((mp_fun_var_t)self->fun)(n_args, args);
84
85
86
    }
}

87
const mp_obj_type_t mp_type_fun_native = {
88
    { &mp_type_type },
89
    .name = MP_QSTR_function,
90
    .call = fun_native_call,
91
    .binary_op = fun_binary_op,
92
93
};

94
// fun must have the correct signature for n_args fixed arguments
Damien George's avatar
Damien George committed
95
mp_obj_t mp_make_function_n(int n_args, void *fun) {
96
    mp_obj_fun_native_t *o = m_new_obj(mp_obj_fun_native_t);
97
    o->base.type = &mp_type_fun_native;
98
    o->is_kw = false;
99
100
    o->n_args_min = n_args;
    o->n_args_max = n_args;
101
102
103
104
    o->fun = fun;
    return o;
}

Damien George's avatar
Damien George committed
105
mp_obj_t mp_make_function_var(int n_args_min, mp_fun_var_t fun) {
106
    mp_obj_fun_native_t *o = m_new_obj(mp_obj_fun_native_t);
107
    o->base.type = &mp_type_fun_native;
108
    o->is_kw = false;
109
    o->n_args_min = n_args_min;
110
    o->n_args_max = MP_OBJ_FUN_ARGS_MAX;
111
112
113
114
115
    o->fun = fun;
    return o;
}

// min and max are inclusive
Damien George's avatar
Damien George committed
116
mp_obj_t mp_make_function_var_between(int n_args_min, int n_args_max, mp_fun_var_t fun) {
117
    mp_obj_fun_native_t *o = m_new_obj(mp_obj_fun_native_t);
118
    o->base.type = &mp_type_fun_native;
119
    o->is_kw = false;
120
121
122
123
124
125
126
127
128
    o->n_args_min = n_args_min;
    o->n_args_max = n_args_max;
    o->fun = fun;
    return o;
}

/******************************************************************************/
/* byte code functions                                                        */

129
#if DEBUG_PRINT
130
STATIC void dump_args(const mp_obj_t *a, int sz) {
131
132
133
134
135
136
    DEBUG_printf("%p: ", a);
    for (int i = 0; i < sz; i++) {
        DEBUG_printf("%p ", a[i]);
    }
    DEBUG_printf("\n");
}
137
138
139
#else
#define dump_args(...) (void)0
#endif
140

141
142
143
144
145
146
147
148
149
150
151
152
153
154
// If it's possible to call a function without allocating new argument array,
// this function returns true, together with pointers to 2 subarrays to be used
// as arguments. Otherwise, it returns false. It is expected that this fucntion
// will be accompanied by another, mp_obj_fun_prepare_full_args(), which will
// instead take pointer to full-length out-array, and will fill it in. Rationale
// being that a caller can try this function and if it succeeds, the function call
// can be made without allocating extra memory. Otherwise, caller can allocate memory
// and try "full" function. These functions are expected to be refactoring of
// code in fun_bc_call() and evenrually replace it.
bool mp_obj_fun_prepare_simple_args(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args,
                            uint *out_args1_len, const mp_obj_t **out_args1, uint *out_args2_len, const mp_obj_t **out_args2) {
    mp_obj_fun_bc_t *self = self_in;

    assert(n_kw == 0);
155
    assert(self->n_kwonly_args == 0);
156
157
158
159
160
161
    assert(self->takes_var_args == 0);
    assert(self->takes_kw_args == 0);

    mp_obj_t *extra_args = self->extra_args + self->n_def_args;
    uint n_extra_args = 0;

162
163
    if (n_args > self->n_pos_args) {
        goto arg_error;
164
    } else {
165
166
        extra_args -= self->n_pos_args - n_args;
        n_extra_args += self->n_pos_args - n_args;
167
168
169
170
171
172
173
174
    }
    *out_args1 = args;
    *out_args1_len = n_args;
    *out_args2 = extra_args;
    *out_args2_len = n_extra_args;
    return true;

arg_error:
175
    nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "function takes %d positional arguments but %d were given", self->n_pos_args, n_args));
176
177
}

178
STATIC mp_obj_t fun_bc_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
179
180
181
182
183
    // This function is pretty complicated.  It's main aim is to be efficient in speed and RAM
    // usage for the common case of positional only args.
    //
    // extra_args layout: def_args, var_arg tuple, kwonly args, var_kw dict

184
185
    DEBUG_printf("Input n_args: %d, n_kw: %d\n", n_args, n_kw);
    DEBUG_printf("Input pos args: ");
186
    dump_args(args, n_args);
187
188
    DEBUG_printf("Input kw args: ");
    dump_args(args + n_args, n_kw * 2);
189
    mp_obj_fun_bc_t *self = self_in;
190
    DEBUG_printf("Func n_def_args: %d\n", self->n_def_args);
191

192
    const mp_obj_t *kwargs = args + n_args;
Damien George's avatar
Damien George committed
193
194
195
    mp_obj_t *extra_args = self->extra_args + self->n_def_args;
    uint n_extra_args = 0;

196
197
    // check positional arguments

198
    if (n_args > self->n_pos_args) {
Damien George's avatar
Damien George committed
199
200
        // given more than enough arguments
        if (!self->takes_var_args) {
201
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
202
                "function takes %d positional arguments but %d were given", self->n_pos_args, n_args));
Damien George's avatar
Damien George committed
203
204
        }
        // put extra arguments in varargs tuple
205
        *extra_args = mp_obj_new_tuple(n_args - self->n_pos_args, args + self->n_pos_args);
Damien George's avatar
Damien George committed
206
        n_extra_args = 1;
207
        n_args = self->n_pos_args;
208
    } else {
Damien George's avatar
Damien George committed
209
        if (self->takes_var_args) {
210
            DEBUG_printf("passing empty tuple as *args\n");
Damien George's avatar
Damien George committed
211
212
213
            *extra_args = mp_const_empty_tuple;
            n_extra_args = 1;
        }
214
215
216
        // Apply processing and check below only if we don't have kwargs,
        // otherwise, kw handling code below has own extensive checks.
        if (n_kw == 0) {
217
            if (n_args >= self->n_pos_args - self->n_def_args) {
218
                // given enough arguments, but may need to use some default arguments
219
220
                extra_args -= self->n_pos_args - n_args;
                n_extra_args += self->n_pos_args - n_args;
221
            } else {
222
223
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
                    "function takes at least %d positional arguments but %d were given",
224
                    self->n_pos_args - self->n_def_args, n_args));
225
226
            }
        }
227
    }
Damien George's avatar
Damien George committed
228

229
230
    // check keyword arguments

231
    if (n_kw != 0) {
232
233
234
235
236
        // We cannot use dynamically-sized array here, because GCC indeed
        // deallocates it on leaving defining scope (unlike most static stack allocs).
        // So, we have 2 choices: allocate it unconditionally at the top of function
        // (wastes stack), or use alloca which is guaranteed to dealloc on func exit.
        //mp_obj_t flat_args[self->n_args];
237
238
        mp_obj_t *flat_args = alloca((self->n_pos_args + self->n_kwonly_args) * sizeof(mp_obj_t));
        for (int i = self->n_pos_args + self->n_kwonly_args - 1; i >= 0; i--) {
239
240
241
242
            flat_args[i] = MP_OBJ_NULL;
        }
        memcpy(flat_args, args, sizeof(*args) * n_args);
        DEBUG_printf("Initial args: ");
243
        dump_args(flat_args, self->n_pos_args + self->n_kwonly_args);
244
245
246
247

        mp_obj_t dict = MP_OBJ_NULL;
        if (self->takes_kw_args) {
            dict = mp_obj_new_dict(n_kw); // TODO: better go conservative with 0?
248
249
        }
        for (uint i = 0; i < n_kw; i++) {
250
            qstr arg_name = MP_OBJ_QSTR_VALUE(kwargs[2 * i]);
251
            for (uint j = 0; j < self->n_pos_args + self->n_kwonly_args; j++) {
252
253
                if (arg_name == self->args[j]) {
                    if (flat_args[j] != MP_OBJ_NULL) {
254
                        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
255
256
257
258
259
260
261
262
                            "function got multiple values for argument '%s'", qstr_str(arg_name)));
                    }
                    flat_args[j] = kwargs[2 * i + 1];
                    goto continue2;
                }
            }
            // Didn't find name match with positional args
            if (!self->takes_kw_args) {
263
                nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "function does not take keyword arguments"));
264
            }
265
            mp_obj_dict_store(dict, kwargs[2 * i], kwargs[2 * i + 1]);
266
267
268
continue2:;
        }
        DEBUG_printf("Args with kws flattened: ");
269
        dump_args(flat_args, self->n_pos_args + self->n_kwonly_args);
270

271
272
        // Now fill in defaults for positional args
        mp_obj_t *d = &flat_args[self->n_pos_args - 1];
273
        mp_obj_t *s = &self->extra_args[self->n_def_args - 1];
274
        for (int i = self->n_def_args; i > 0; i--, d--, s--) {
275
            if (*d == MP_OBJ_NULL) {
276
                *d = *s;
277
278
279
            }
        }
        DEBUG_printf("Args after filling defaults: ");
280
        dump_args(flat_args, self->n_pos_args + self->n_kwonly_args);
281

282
        // Check that all mandatory positional args are specified
283
284
        while (d >= flat_args) {
            if (*d-- == MP_OBJ_NULL) {
285
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
286
287
288
289
                    "function missing required positional argument #%d", d - flat_args));
            }
        }

290
291
292
293
294
295
296
297
        // Check that all mandatory keyword args are specified
        for (int i = 0; i < self->n_kwonly_args; i++) {
            if (flat_args[self->n_pos_args + i] == MP_OBJ_NULL) {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
                    "function missing required keyword argument '%s'", qstr_str(self->args[self->n_pos_args + i])));
            }
        }

298
        args = flat_args;
299
        n_args = self->n_pos_args + self->n_kwonly_args;
300
301
302
303

        if (self->takes_kw_args) {
            extra_args[n_extra_args] = dict;
            n_extra_args += 1;
304
305
306
        }
    } else {
        // no keyword arguments given
307
308
309
310
        if (self->n_kwonly_args != 0) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
                "function missing keyword-only argument"));
        }
311
312
313
314
        if (self->takes_kw_args) {
            extra_args[n_extra_args] = mp_obj_new_dict(0);
            n_extra_args += 1;
        }
315
    }
316

317
    mp_obj_dict_t *old_globals = mp_globals_get();
Damien George's avatar
Damien George committed
318
    mp_globals_set(self->globals);
319
    mp_obj_t result;
320
321
322
    DEBUG_printf("Calling: args=%p, n_args=%d, extra_args=%p, n_extra_args=%d\n", args, n_args, extra_args, n_extra_args);
    dump_args(args, n_args);
    dump_args(extra_args, n_extra_args);
323
    mp_vm_return_kind_t vm_return_kind = mp_execute_byte_code(self->bytecode, args, n_args, extra_args, n_extra_args, &result);
Damien George's avatar
Damien George committed
324
    mp_globals_set(old_globals);
325

326
327
328
    if (vm_return_kind == MP_VM_RETURN_NORMAL) {
        return result;
    } else { // MP_VM_RETURN_EXCEPTION
329
        nlr_raise(result);
330
    }
331
332
}

333
const mp_obj_type_t mp_type_fun_bc = {
334
    { &mp_type_type },
335
    .name = MP_QSTR_function,
336
    .call = fun_bc_call,
337
    .binary_op = fun_binary_op,
338
339
};

340
mp_obj_t mp_obj_new_fun_bc(uint scope_flags, qstr *args, uint n_pos_args, uint n_kwonly_args, mp_obj_t def_args_in, const byte *code) {
Damien George's avatar
Damien George committed
341
342
    uint n_def_args = 0;
    uint n_extra_args = 0;
343
344
    mp_obj_tuple_t *def_args = def_args_in;
    if (def_args != MP_OBJ_NULL) {
345
        assert(MP_OBJ_IS_TYPE(def_args, &mp_type_tuple));
346
        n_def_args = def_args->len;
Damien George's avatar
Damien George committed
347
348
349
350
        n_extra_args = def_args->len;
    }
    if ((scope_flags & MP_SCOPE_FLAG_VARARGS) != 0) {
        n_extra_args += 1;
351
    }
352
353
354
    if ((scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0) {
        n_extra_args += 1;
    }
Damien George's avatar
Damien George committed
355
    mp_obj_fun_bc_t *o = m_new_obj_var(mp_obj_fun_bc_t, mp_obj_t, n_extra_args);
356
    o->base.type = &mp_type_fun_bc;
Damien George's avatar
Damien George committed
357
    o->globals = mp_globals_get();
358
    o->args = args;
359
360
    o->n_pos_args = n_pos_args;
    o->n_kwonly_args = n_kwonly_args;
361
    o->n_def_args = n_def_args;
Damien George's avatar
Damien George committed
362
363
    o->takes_var_args = (scope_flags & MP_SCOPE_FLAG_VARARGS) != 0;
    o->takes_kw_args = (scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0;
364
    o->bytecode = code;
365
    memset(o->extra_args, 0, n_extra_args * sizeof(mp_obj_t));
366
    if (def_args != MP_OBJ_NULL) {
Damien George's avatar
Damien George committed
367
        memcpy(o->extra_args, def_args->items, n_def_args * sizeof(mp_obj_t));
368
    }
369
370
371
372
373
374
    if ((scope_flags & MP_SCOPE_FLAG_VARARGS) != 0) {
        o->extra_args[n_def_args] = MP_OBJ_NULL;
    }
    if ((scope_flags & MP_SCOPE_FLAG_VARARGS) != 0) {
        o->extra_args[n_extra_args - 1] = MP_OBJ_NULL;
    }
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
    return o;
}

/******************************************************************************/
/* inline assembler functions                                                 */

typedef struct _mp_obj_fun_asm_t {
    mp_obj_base_t base;
    int n_args;
    void *fun;
} mp_obj_fun_asm_t;

typedef machine_uint_t (*inline_asm_fun_0_t)();
typedef machine_uint_t (*inline_asm_fun_1_t)(machine_uint_t);
typedef machine_uint_t (*inline_asm_fun_2_t)(machine_uint_t, machine_uint_t);
typedef machine_uint_t (*inline_asm_fun_3_t)(machine_uint_t, machine_uint_t, machine_uint_t);

// convert a Micro Python object to a sensible value for inline asm
393
STATIC machine_uint_t convert_obj_for_inline_asm(mp_obj_t obj) {
394
395
396
397
398
399
400
401
402
    // TODO for byte_array, pass pointer to the array
    if (MP_OBJ_IS_SMALL_INT(obj)) {
        return MP_OBJ_SMALL_INT_VALUE(obj);
    } else if (obj == mp_const_none) {
        return 0;
    } else if (obj == mp_const_false) {
        return 0;
    } else if (obj == mp_const_true) {
        return 1;
403
    } else if (MP_OBJ_IS_STR(obj)) {
404
        // pointer to the string (it's probably constant though!)
405
406
        uint l;
        return (machine_uint_t)mp_obj_str_get_data(obj, &l);
407
408
409
    } else {
        mp_obj_type_t *type = mp_obj_get_type(obj);
        if (0) {
410
#if MICROPY_ENABLE_FLOAT
411
412
413
        } else if (type == &mp_type_float) {
            // convert float to int (could also pass in float registers)
            return (machine_int_t)mp_obj_float_get(obj);
414
#endif
415
416
417
418
419
420
421
422
423
424
425
426
427
        } else if (type == &mp_type_tuple) {
            // pointer to start of tuple (could pass length, but then could use len(x) for that)
            uint len;
            mp_obj_t *items;
            mp_obj_tuple_get(obj, &len, &items);
            return (machine_uint_t)items;
        } else if (type == &mp_type_list) {
            // pointer to start of list (could pass length, but then could use len(x) for that)
            uint len;
            mp_obj_t *items;
            mp_obj_list_get(obj, &len, &items);
            return (machine_uint_t)items;
        } else {
428
            mp_buffer_info_t bufinfo;
429
            if (mp_get_buffer(obj, &bufinfo, MP_BUFFER_WRITE)) {
430
431
432
433
434
435
                // supports the buffer protocol, return a pointer to the data
                return (machine_uint_t)bufinfo.buf;
            } else {
                // just pass along a pointer to the object
                return (machine_uint_t)obj;
            }
436
        }
437
438
439
440
    }
}

// convert a return value from inline asm to a sensible Micro Python object
441
STATIC mp_obj_t convert_val_from_inline_asm(machine_uint_t val) {
442
443
444
    return MP_OBJ_NEW_SMALL_INT(val);
}

445
STATIC mp_obj_t fun_asm_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
446
447
448
    mp_obj_fun_asm_t *self = self_in;

    if (n_args != self->n_args) {
449
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "function takes %d positional arguments but %d were given", self->n_args, n_args));
450
    }
451
    if (n_kw != 0) {
452
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "function does not take keyword arguments"));
453
    }
454
455
456
457
458
459
460

    machine_uint_t ret;
    if (n_args == 0) {
        ret = ((inline_asm_fun_0_t)self->fun)();
    } else if (n_args == 1) {
        ret = ((inline_asm_fun_1_t)self->fun)(convert_obj_for_inline_asm(args[0]));
    } else if (n_args == 2) {
461
        ret = ((inline_asm_fun_2_t)self->fun)(convert_obj_for_inline_asm(args[0]), convert_obj_for_inline_asm(args[1]));
462
    } else if (n_args == 3) {
463
        ret = ((inline_asm_fun_3_t)self->fun)(convert_obj_for_inline_asm(args[0]), convert_obj_for_inline_asm(args[1]), convert_obj_for_inline_asm(args[2]));
464
465
466
467
468
469
470
471
    } else {
        assert(0);
        ret = 0;
    }

    return convert_val_from_inline_asm(ret);
}

472
STATIC const mp_obj_type_t mp_type_fun_asm = {
473
    { &mp_type_type },
474
    .name = MP_QSTR_function,
475
    .call = fun_asm_call,
476
    .binary_op = fun_binary_op,
477
478
479
480
};

mp_obj_t mp_obj_new_fun_asm(uint n_args, void *fun) {
    mp_obj_fun_asm_t *o = m_new_obj(mp_obj_fun_asm_t);
481
    o->base.type = &mp_type_fun_asm;
482
483
484
485
    o->n_args = n_args;
    o->fun = fun;
    return o;
}