objfun.c 18.4 KB
Newer Older
xbe's avatar
xbe committed
1
#include <stdbool.h>
2
3
4
5
6
7
8
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
9
#include "qstr.h"
10
#include "obj.h"
11
#include "objtuple.h"
Damien George's avatar
Damien George committed
12
#include "runtime0.h"
13
14
15
#include "runtime.h"
#include "bc.h"

16
17
18
#if 0 // print debugging info
#define DEBUG_PRINT (1)
#else // don't print debugging info
19
#define DEBUG_printf(...) (void)0
20
21
#endif

22
23
24
25
26
/******************************************************************************/
/* native functions                                                           */

// mp_obj_fun_native_t defined in obj.h

27
STATIC void check_nargs(mp_obj_fun_native_t *self, int n_args, int n_kw) {
Damien George's avatar
Damien George committed
28
    mp_check_nargs(n_args, self->n_args_min, self->n_args_max, n_kw, self->is_kw);
Dave Hylands's avatar
Dave Hylands committed
29
30
}

Damien George's avatar
Damien George committed
31
void mp_check_nargs(int n_args, machine_uint_t n_args_min, machine_uint_t n_args_max, int n_kw, bool is_kw) {
Dave Hylands's avatar
Dave Hylands committed
32
    if (n_kw && !is_kw) {
33
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
34
35
36
                                          "function does not take keyword arguments"));
    }

Dave Hylands's avatar
Dave Hylands committed
37
38
    if (n_args_min == n_args_max) {
        if (n_args != n_args_min) {
39
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
40
                                                     "function takes %d positional arguments but %d were given",
Dave Hylands's avatar
Dave Hylands committed
41
                                                     n_args_min, n_args));
42
43
        }
    } else {
Dave Hylands's avatar
Dave Hylands committed
44
        if (n_args < n_args_min) {
45
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
46
                                                    "<fun name>() missing %d required positional arguments: <list of names of params>",
Dave Hylands's avatar
Dave Hylands committed
47
48
                                                    n_args_min - n_args));
        } else if (n_args > n_args_max) {
49
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
50
                                                     "<fun name> expected at most %d arguments, got %d",
Dave Hylands's avatar
Dave Hylands committed
51
                                                     n_args_max, n_args));
52
53
54
55
        }
    }
}

56
57
58
59
60
61
62
63
64
65
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;
}

66
STATIC mp_obj_t fun_native_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
67
    assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_native));
68
    mp_obj_fun_native_t *self = self_in;
69

70
    // check number of arguments
71
72
    check_nargs(self, n_args, n_kw);

73
    if (self->is_kw) {
74
75
        // function allows keywords

76
77
78
        // 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);
79

80
        return ((mp_fun_kw_t)self->fun)(n_args, args, &kw_args);
81

82
    } else if (self->n_args_min <= 3 && self->n_args_min == self->n_args_max) {
83
84
85
86
87
88
89
90
91
92
93
        // 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:
94
                return ((mp_fun_2_t)self->fun)(args[0], args[1]);
95

96
            case 3:
97
                return ((mp_fun_3_t)self->fun)(args[0], args[1], args[2]);
98

99
100
101
102
103
104
            default:
                assert(0);
                return mp_const_none;
        }

    } else {
105
        // function takes a variable number of arguments, but no keywords
106

107
        return ((mp_fun_var_t)self->fun)(n_args, args);
108
109
110
    }
}

111
const mp_obj_type_t mp_type_fun_native = {
112
    { &mp_type_type },
113
    .name = MP_QSTR_function,
114
    .call = fun_native_call,
115
    .binary_op = fun_binary_op,
116
117
};

118
// fun must have the correct signature for n_args fixed arguments
Damien George's avatar
Damien George committed
119
mp_obj_t mp_make_function_n(int n_args, void *fun) {
120
    mp_obj_fun_native_t *o = m_new_obj(mp_obj_fun_native_t);
121
    o->base.type = &mp_type_fun_native;
122
    o->is_kw = false;
123
124
    o->n_args_min = n_args;
    o->n_args_max = n_args;
125
126
127
128
    o->fun = fun;
    return o;
}

Damien George's avatar
Damien George committed
129
mp_obj_t mp_make_function_var(int n_args_min, mp_fun_var_t fun) {
130
    mp_obj_fun_native_t *o = m_new_obj(mp_obj_fun_native_t);
131
    o->base.type = &mp_type_fun_native;
132
    o->is_kw = false;
133
    o->n_args_min = n_args_min;
134
    o->n_args_max = MP_OBJ_FUN_ARGS_MAX;
135
136
137
138
139
    o->fun = fun;
    return o;
}

// min and max are inclusive
Damien George's avatar
Damien George committed
140
mp_obj_t mp_make_function_var_between(int n_args_min, int n_args_max, mp_fun_var_t fun) {
141
    mp_obj_fun_native_t *o = m_new_obj(mp_obj_fun_native_t);
142
    o->base.type = &mp_type_fun_native;
143
    o->is_kw = false;
144
145
146
147
148
149
150
151
152
153
154
    o->n_args_min = n_args_min;
    o->n_args_max = n_args_max;
    o->fun = fun;
    return o;
}

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

typedef struct _mp_obj_fun_bc_t {
    mp_obj_base_t base;
155
    mp_obj_dict_t *globals; // the context within which this function was defined
156
157
158
159
    machine_uint_t n_args : 15;         // number of arguments this function takes
    machine_uint_t n_def_args : 15;     // number of default arguments
    machine_uint_t takes_var_args : 1;  // set if this function takes variable args
    machine_uint_t takes_kw_args : 1;   // set if this function takes keyword args
160
    const byte *bytecode;   // bytecode for the function
161
    qstr *args;             // argument names (needed to resolve positional args passed as keywords)
162
    mp_obj_t extra_args[];  // values of default args (if any), plus a slot at the end for var args and/or kw args (if it takes them)
163
164
} mp_obj_fun_bc_t;

165
#if DEBUG_PRINT
166
STATIC void dump_args(const mp_obj_t *a, int sz) {
167
168
169
170
171
172
    DEBUG_printf("%p: ", a);
    for (int i = 0; i < sz; i++) {
        DEBUG_printf("%p ", a[i]);
    }
    DEBUG_printf("\n");
}
173
174
175
#else
#define dump_args(...) (void)0
#endif
176

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// 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);
    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;

    if (n_args > self->n_args) {
            goto arg_error;
    } else {
        extra_args -= self->n_args - n_args;
        n_extra_args += self->n_args - n_args;
    }
    *out_args1 = args;
    *out_args1_len = n_args;
    *out_args2 = extra_args;
    *out_args2_len = n_extra_args;
    return true;

arg_error:
210
    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));
211
212
}

213
STATIC mp_obj_t fun_bc_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
214
215
    DEBUG_printf("Input n_args: %d, n_kw: %d\n", n_args, n_kw);
    DEBUG_printf("Input pos args: ");
216
    dump_args(args, n_args);
217
218
    DEBUG_printf("Input kw args: ");
    dump_args(args + n_args, n_kw * 2);
219
    mp_obj_fun_bc_t *self = self_in;
220
    DEBUG_printf("Func n_def_args: %d\n", self->n_def_args);
221

222
    const mp_obj_t *kwargs = args + n_args;
Damien George's avatar
Damien George committed
223
224
225
    mp_obj_t *extra_args = self->extra_args + self->n_def_args;
    uint n_extra_args = 0;

226

227
228
    // check positional arguments

Damien George's avatar
Damien George committed
229
230
231
    if (n_args > self->n_args) {
        // given more than enough arguments
        if (!self->takes_var_args) {
232
233
            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));
Damien George's avatar
Damien George committed
234
235
236
237
238
        }
        // put extra arguments in varargs tuple
        *extra_args = mp_obj_new_tuple(n_args - self->n_args, args + self->n_args);
        n_extra_args = 1;
        n_args = self->n_args;
239
    } else {
Damien George's avatar
Damien George committed
240
        if (self->takes_var_args) {
241
            DEBUG_printf("passing empty tuple as *args\n");
Damien George's avatar
Damien George committed
242
243
244
            *extra_args = mp_const_empty_tuple;
            n_extra_args = 1;
        }
245
246
247
248
249
250
251
252
        // 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) {
            if (n_args >= self->n_args - self->n_def_args) {
                // given enough arguments, but may need to use some default arguments
                extra_args -= self->n_args - n_args;
                n_extra_args += self->n_args - n_args;
            } else {
253
254
255
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
                    "function takes at least %d positional arguments but %d were given",
                    self->n_args - self->n_def_args, n_args));
256
257
            }
        }
258
    }
Damien George's avatar
Damien George committed
259

260
261
    // check keyword arguments

262
    if (n_kw != 0) {
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        // 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];
        mp_obj_t *flat_args = alloca(self->n_args * sizeof(mp_obj_t));
        for (int i = self->n_args - 1; i >= 0; i--) {
            flat_args[i] = MP_OBJ_NULL;
        }
        memcpy(flat_args, args, sizeof(*args) * n_args);
        DEBUG_printf("Initial args: ");
        dump_args(flat_args, self->n_args);

        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?
279
280
        }
        for (uint i = 0; i < n_kw; i++) {
281
282
283
284
            qstr arg_name = MP_OBJ_QSTR_VALUE(kwargs[2 * i]);
            for (uint j = 0; j < self->n_args; j++) {
                if (arg_name == self->args[j]) {
                    if (flat_args[j] != MP_OBJ_NULL) {
285
                        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
286
287
288
289
290
291
292
293
                            "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) {
294
                nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "function does not take keyword arguments"));
295
            }
296
            mp_obj_dict_store(dict, kwargs[2 * i], kwargs[2 * i + 1]);
297
298
299
300
301
302
303
304
continue2:;
        }
        DEBUG_printf("Args with kws flattened: ");
        dump_args(flat_args, self->n_args);

        // Now fill in defaults
        mp_obj_t *d = &flat_args[self->n_args - 1];
        mp_obj_t *s = &self->extra_args[self->n_def_args - 1];
305
        for (int i = self->n_def_args; i > 0; i--, d--, s--) {
306
            if (*d == MP_OBJ_NULL) {
307
                *d = *s;
308
309
310
311
312
313
314
315
            }
        }
        DEBUG_printf("Args after filling defaults: ");
        dump_args(flat_args, self->n_args);

        // Now check that all mandatory args specified
        while (d >= flat_args) {
            if (*d-- == MP_OBJ_NULL) {
316
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
317
318
319
320
321
322
323
324
325
326
                    "function missing required positional argument #%d", d - flat_args));
            }
        }

        args = flat_args;
        n_args = self->n_args;

        if (self->takes_kw_args) {
            extra_args[n_extra_args] = dict;
            n_extra_args += 1;
327
328
329
330
331
332
333
        }
    } else {
        // no keyword arguments given
        if (self->takes_kw_args) {
            extra_args[n_extra_args] = mp_obj_new_dict(0);
            n_extra_args += 1;
        }
334
    }
335

336
    mp_obj_dict_t *old_globals = mp_globals_get();
Damien George's avatar
Damien George committed
337
    mp_globals_set(self->globals);
338
    mp_obj_t result;
339
340
341
    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);
342
    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
343
    mp_globals_set(old_globals);
344

345
346
347
    if (vm_return_kind == MP_VM_RETURN_NORMAL) {
        return result;
    } else { // MP_VM_RETURN_EXCEPTION
348
        nlr_raise(result);
349
    }
350
351
}

352
const mp_obj_type_t mp_type_fun_bc = {
353
    { &mp_type_type },
354
    .name = MP_QSTR_function,
355
    .call = fun_bc_call,
356
    .binary_op = fun_binary_op,
357
358
};

359
mp_obj_t mp_obj_new_fun_bc(uint scope_flags, qstr *args, uint n_args, mp_obj_t def_args_in, const byte *code) {
Damien George's avatar
Damien George committed
360
361
    uint n_def_args = 0;
    uint n_extra_args = 0;
362
363
    mp_obj_tuple_t *def_args = def_args_in;
    if (def_args != MP_OBJ_NULL) {
364
        assert(MP_OBJ_IS_TYPE(def_args, &mp_type_tuple));
365
        n_def_args = def_args->len;
Damien George's avatar
Damien George committed
366
367
368
369
        n_extra_args = def_args->len;
    }
    if ((scope_flags & MP_SCOPE_FLAG_VARARGS) != 0) {
        n_extra_args += 1;
370
    }
371
372
373
    if ((scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0) {
        n_extra_args += 1;
    }
Damien George's avatar
Damien George committed
374
    mp_obj_fun_bc_t *o = m_new_obj_var(mp_obj_fun_bc_t, mp_obj_t, n_extra_args);
375
    o->base.type = &mp_type_fun_bc;
Damien George's avatar
Damien George committed
376
    o->globals = mp_globals_get();
377
    o->args = args;
378
    o->n_args = n_args;
379
    o->n_def_args = n_def_args;
Damien George's avatar
Damien George committed
380
381
    o->takes_var_args = (scope_flags & MP_SCOPE_FLAG_VARARGS) != 0;
    o->takes_kw_args = (scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0;
382
    o->bytecode = code;
383
    if (def_args != MP_OBJ_NULL) {
Damien George's avatar
Damien George committed
384
        memcpy(o->extra_args, def_args->items, n_def_args * sizeof(mp_obj_t));
385
    }
386
387
388
    return o;
}

389
void mp_obj_fun_bc_get(mp_obj_t self_in, int *n_args, const byte **code) {
390
    assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_bc));
391
392
393
394
395
    mp_obj_fun_bc_t *self = self_in;
    *n_args = self->n_args;
    *code = self->bytecode;
}

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/******************************************************************************/
/* 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
411
STATIC machine_uint_t convert_obj_for_inline_asm(mp_obj_t obj) {
412
413
414
415
416
417
418
419
420
    // 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;
421
    } else if (MP_OBJ_IS_STR(obj)) {
422
        // pointer to the string (it's probably constant though!)
423
424
        uint l;
        return (machine_uint_t)mp_obj_str_get_data(obj, &l);
425
426
427
    } else {
        mp_obj_type_t *type = mp_obj_get_type(obj);
        if (0) {
428
#if MICROPY_ENABLE_FLOAT
429
430
431
        } 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);
432
#endif
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
        } 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 if (type->buffer_p.get_buffer != NULL) {
            // supports the buffer protocol, get a pointer to the data
            buffer_info_t bufinfo;
            type->buffer_p.get_buffer(obj, &bufinfo, BUFFER_READ);
            return (machine_uint_t)bufinfo.buf;
        } else {
            // just pass along a pointer to the object
            return (machine_uint_t)obj;
        }
454
455
456
457
    }
}

// convert a return value from inline asm to a sensible Micro Python object
458
STATIC mp_obj_t convert_val_from_inline_asm(machine_uint_t val) {
459
460
461
    return MP_OBJ_NEW_SMALL_INT(val);
}

462
STATIC mp_obj_t fun_asm_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
463
464
465
    mp_obj_fun_asm_t *self = self_in;

    if (n_args != self->n_args) {
466
        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));
467
    }
468
    if (n_kw != 0) {
469
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "function does not take keyword arguments"));
470
    }
471
472
473
474
475
476
477

    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) {
478
        ret = ((inline_asm_fun_2_t)self->fun)(convert_obj_for_inline_asm(args[0]), convert_obj_for_inline_asm(args[1]));
479
    } else if (n_args == 3) {
480
        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]));
481
482
483
484
485
486
487
488
    } else {
        assert(0);
        ret = 0;
    }

    return convert_val_from_inline_asm(ret);
}

489
STATIC const mp_obj_type_t mp_type_fun_asm = {
490
    { &mp_type_type },
491
    .name = MP_QSTR_function,
492
    .call = fun_asm_call,
493
    .binary_op = fun_binary_op,
494
495
496
497
};

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);
498
    o->base.type = &mp_type_fun_asm;
499
500
501
502
    o->n_args = n_args;
    o->fun = fun;
    return o;
}