objfun.c 17.3 KB
Newer Older
1
2
3
4
5
6
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
7
 * Copyright (c) 2014 Paul Sokolovsky
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

28
29
30
#include <string.h>
#include <assert.h>

31
32
33
34
35
36
37
#include "py/nlr.h"
#include "py/objtuple.h"
#include "py/objfun.h"
#include "py/runtime0.h"
#include "py/runtime.h"
#include "py/bc.h"
#include "py/stackctrl.h"
38

39
40
41
#if 0 // print debugging info
#define DEBUG_PRINT (1)
#else // don't print debugging info
42
#define DEBUG_PRINT (0)
43
#define DEBUG_printf(...) (void)0
44
45
#endif

46
47
48
// Note: the "name" entry in mp_obj_type_t for a function type must be
// MP_QSTR_function because it is used to determine if an object is of generic
// function type.
49

50
51
52
53
54
/******************************************************************************/
/* builtin functions                                                          */

// mp_obj_fun_builtin_t defined in obj.h

55
STATIC mp_obj_t fun_builtin_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
56
57
    assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_builtin));
    mp_obj_fun_builtin_t *self = self_in;
58

59
    // check number of arguments
60
    mp_arg_check_num(n_args, n_kw, self->n_args_min, self->n_args_max, self->is_kw);
61

62
    if (self->is_kw) {
63
64
        // function allows keywords

65
66
67
        // 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);
68

69
        return ((mp_fun_kw_t)self->fun)(n_args, args, &kw_args);
70

71
    } else if (self->n_args_min <= 3 && self->n_args_min == self->n_args_max) {
72
73
74
75
76
77
78
79
80
81
82
        // 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:
83
                return ((mp_fun_2_t)self->fun)(args[0], args[1]);
84

85
            case 3:
86
                return ((mp_fun_3_t)self->fun)(args[0], args[1], args[2]);
87

88
89
90
91
92
93
            default:
                assert(0);
                return mp_const_none;
        }

    } else {
94
        // function takes a variable number of arguments, but no keywords
95

96
        return ((mp_fun_var_t)self->fun)(n_args, args);
97
98
99
    }
}

100
const mp_obj_type_t mp_type_fun_builtin = {
101
    { &mp_type_type },
102
    .name = MP_QSTR_function,
103
    .call = fun_builtin_call,
104
105
106
107
108
};

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

109
const char *mp_obj_code_get_name(const byte *code_info) {
110
111
    mp_decode_uint(&code_info); // skip code_info_size entry
    return qstr_str(mp_decode_uint(&code_info));
112
113
}

Paul Sokolovsky's avatar
Paul Sokolovsky committed
114
115
const char *mp_obj_fun_get_name(mp_const_obj_t fun_in) {
    const mp_obj_fun_bc_t *fun = fun_in;
116
    const byte *code_info = fun->bytecode;
117
118
119
    return mp_obj_code_get_name(code_info);
}

120
121
122
123
124
125
126
#if MICROPY_CPYTHON_COMPAT
STATIC void fun_bc_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t o_in, mp_print_kind_t kind) {
    mp_obj_fun_bc_t *o = o_in;
    print(env, "<function %s at 0x%x>", mp_obj_fun_get_name(o), o);
}
#endif

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

139
140
141
// With this macro you can tune the maximum number of function state bytes
// that will be allocated on the stack.  Any function that needs more
// than this will use the heap.
142
#define VM_MAX_STATE_ON_STACK (10 * sizeof(mp_uint_t))
143
144
145
146

// Set this to enable a simple stack overflow check.
#define VM_DETECT_STACK_OVERFLOW (0)

147
STATIC mp_obj_t fun_bc_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovsky's avatar
Paul Sokolovsky committed
148
    MP_STACK_CHECK();
149

150
    DEBUG_printf("Input n_args: " UINT_FMT ", n_kw: " UINT_FMT "\n", n_args, n_kw);
151
152
153
154
155
156
157
    DEBUG_printf("Input pos args: ");
    dump_args(args, n_args);
    DEBUG_printf("Input kw args: ");
    dump_args(args + n_args, n_kw * 2);
    mp_obj_fun_bc_t *self = self_in;
    DEBUG_printf("Func n_def_args: %d\n", self->n_def_args);

158
159
160
161
    // skip code-info block
    const byte *code_info = self->bytecode;
    mp_uint_t code_info_size = mp_decode_uint(&code_info);
    const byte *ip = self->bytecode + code_info_size;
162

163
164
165
166
    // bytecode prelude: skip arg names
    ip += (self->n_pos_args + self->n_kwonly_args) * sizeof(mp_obj_t);

    // bytecode prelude: state size and exception stack size
167
168
    mp_uint_t n_state = mp_decode_uint(&ip);
    mp_uint_t n_exc_stack = mp_decode_uint(&ip);
169
170
171
172
173
174

#if VM_DETECT_STACK_OVERFLOW
    n_state += 1;
#endif

    // allocate state for locals and stack
175
    mp_uint_t state_size = n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t);
176
177
178
179
180
181
182
183
184
185
    mp_code_state *code_state;
    if (state_size > VM_MAX_STATE_ON_STACK) {
        code_state = m_new_obj_var(mp_code_state, byte, state_size);
    } else {
        code_state = alloca(sizeof(mp_code_state) + state_size);
    }

    code_state->n_state = n_state;
    code_state->ip = ip;
    mp_setup_code_state(code_state, self_in, n_args, n_kw, args);
186
187
188
189

    // execute the byte code with the correct globals context
    mp_obj_dict_t *old_globals = mp_globals_get();
    mp_globals_set(self->globals);
190
    mp_vm_return_kind_t vm_return_kind = mp_execute_bytecode(code_state, MP_OBJ_NULL);
191
    mp_globals_set(old_globals);
192
193
194
195
196
197
198
199
200
201
202

#if VM_DETECT_STACK_OVERFLOW
    if (vm_return_kind == MP_VM_RETURN_NORMAL) {
        if (code_state->sp < code_state->state) {
            printf("VM stack underflow: " INT_FMT "\n", code_state->sp - code_state->state);
            assert(0);
        }
    }
    // We can't check the case when an exception is returned in state[n_state - 1]
    // and there are no arguments, because in this case our detection slot may have
    // been overwritten by the returned exception (which is allowed).
203
    if (!(vm_return_kind == MP_VM_RETURN_EXCEPTION && self->n_pos_args + self->n_kwonly_args == 0)) {
204
205
        // Just check to see that we have at least 1 null object left in the state.
        bool overflow = true;
206
        for (mp_uint_t i = 0; i < n_state - self->n_pos_args - self->n_kwonly_args; i++) {
207
208
209
210
211
212
213
214
215
216
217
218
            if (code_state->state[i] == MP_OBJ_NULL) {
                overflow = false;
                break;
            }
        }
        if (overflow) {
            printf("VM stack overflow state=%p n_state+1=" UINT_FMT "\n", code_state->state, n_state);
            assert(0);
        }
    }
#endif

219
    mp_obj_t result;
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    switch (vm_return_kind) {
        case MP_VM_RETURN_NORMAL:
            // return value is in *sp
            result = *code_state->sp;
            break;

        case MP_VM_RETURN_EXCEPTION:
            // return value is in state[n_state - 1]
            result = code_state->state[n_state - 1];
            break;

        case MP_VM_RETURN_YIELD: // byte-code shouldn't yield
        default:
            assert(0);
            result = mp_const_none;
            vm_return_kind = MP_VM_RETURN_NORMAL;
            break;
    }

    // free the state if it was allocated on the heap
    if (state_size > VM_MAX_STATE_ON_STACK) {
        m_del_var(mp_code_state, byte, state_size, code_state);
    }

244
245
246
    if (vm_return_kind == MP_VM_RETURN_NORMAL) {
        return result;
    } else { // MP_VM_RETURN_EXCEPTION
247
        nlr_raise(result);
248
    }
249
250
}

251
const mp_obj_type_t mp_type_fun_bc = {
252
    { &mp_type_type },
253
    .name = MP_QSTR_function,
254
255
256
#if MICROPY_CPYTHON_COMPAT
    .print = fun_bc_print,
#endif
257
    .call = fun_bc_call,
258
259
};

260
mp_obj_t mp_obj_new_fun_bc(mp_uint_t scope_flags, mp_uint_t n_pos_args, mp_uint_t n_kwonly_args, mp_obj_t def_args_in, mp_obj_t def_kw_args, const byte *code) {
261
262
    mp_uint_t n_def_args = 0;
    mp_uint_t n_extra_args = 0;
263
264
    mp_obj_tuple_t *def_args = def_args_in;
    if (def_args != MP_OBJ_NULL) {
265
        assert(MP_OBJ_IS_TYPE(def_args, &mp_type_tuple));
266
        n_def_args = def_args->len;
Damien George's avatar
Damien George committed
267
268
        n_extra_args = def_args->len;
    }
269
270
271
    if (def_kw_args != MP_OBJ_NULL) {
        n_extra_args += 1;
    }
Damien George's avatar
Damien George committed
272
    mp_obj_fun_bc_t *o = m_new_obj_var(mp_obj_fun_bc_t, mp_obj_t, n_extra_args);
273
    o->base.type = &mp_type_fun_bc;
Damien George's avatar
Damien George committed
274
    o->globals = mp_globals_get();
275
276
    o->n_pos_args = n_pos_args;
    o->n_kwonly_args = n_kwonly_args;
277
    o->n_def_args = n_def_args;
278
    o->has_def_kw_args = def_kw_args != MP_OBJ_NULL;
Damien George's avatar
Damien George committed
279
280
    o->takes_var_args = (scope_flags & MP_SCOPE_FLAG_VARARGS) != 0;
    o->takes_kw_args = (scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0;
281
    o->bytecode = code;
282
    if (def_args != MP_OBJ_NULL) {
283
        memcpy(o->extra_args, def_args->items, n_def_args * sizeof(mp_obj_t));
284
285
    }
    if (def_kw_args != MP_OBJ_NULL) {
286
        o->extra_args[n_def_args] = def_kw_args;
287
    }
288
289
290
    return o;
}

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/******************************************************************************/
/* native functions                                                           */

#if MICROPY_EMIT_NATIVE

typedef struct _mp_obj_fun_native_t {
    mp_obj_base_t base;
    mp_uint_t n_args;
    void *fun_data; // GC must be able to trace this pointer
    // TODO add mp_map_t *globals
} mp_obj_fun_native_t;

typedef mp_obj_t (*native_fun_0_t)();
typedef mp_obj_t (*native_fun_1_t)(mp_obj_t);
typedef mp_obj_t (*native_fun_2_t)(mp_obj_t, mp_obj_t);
typedef mp_obj_t (*native_fun_3_t)(mp_obj_t, mp_obj_t, mp_obj_t);

308
STATIC mp_obj_t fun_native_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
    mp_obj_fun_native_t *self = self_in;

    mp_arg_check_num(n_args, n_kw, self->n_args, self->n_args, false);

    void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data);

    switch (n_args) {
        case 0:
            return ((native_fun_0_t)fun)();

        case 1:
            return ((native_fun_1_t)fun)(args[0]);

        case 2:
            return ((native_fun_2_t)fun)(args[0], args[1]);

        case 3:
            return ((native_fun_3_t)fun)(args[0], args[1], args[2]);

        default:
            assert(0);
            return mp_const_none;
    }
}

STATIC const mp_obj_type_t mp_type_fun_native = {
    { &mp_type_type },
    .name = MP_QSTR_function,
    .call = fun_native_call,
};

mp_obj_t mp_obj_new_fun_native(mp_uint_t n_args, void *fun_data) {
    assert(0 <= n_args && n_args <= 3);
    mp_obj_fun_native_t *o = m_new_obj(mp_obj_fun_native_t);
    o->base.type = &mp_type_fun_native;
    o->n_args = n_args;
    o->fun_data = fun_data;
    return o;
}

#endif // MICROPY_EMIT_NATIVE

351
352
353
354
355
356
357
/******************************************************************************/
/* viper functions                                                            */

#if MICROPY_EMIT_NATIVE

typedef struct _mp_obj_fun_viper_t {
    mp_obj_base_t base;
358
359
    mp_uint_t n_args;
    void *fun_data; // GC must be able to trace this pointer
360
361
362
363
364
365
366
367
    mp_uint_t type_sig;
} mp_obj_fun_viper_t;

typedef mp_uint_t (*viper_fun_0_t)();
typedef mp_uint_t (*viper_fun_1_t)(mp_uint_t);
typedef mp_uint_t (*viper_fun_2_t)(mp_uint_t, mp_uint_t);
typedef mp_uint_t (*viper_fun_3_t)(mp_uint_t, mp_uint_t, mp_uint_t);

368
STATIC mp_obj_t fun_viper_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
369
370
371
372
    mp_obj_fun_viper_t *self = self_in;

    mp_arg_check_num(n_args, n_kw, self->n_args, self->n_args, false);

373
374
    void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data);

375
376
    mp_uint_t ret;
    if (n_args == 0) {
377
        ret = ((viper_fun_0_t)fun)();
378
    } else if (n_args == 1) {
379
        ret = ((viper_fun_1_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 2));
380
    } else if (n_args == 2) {
381
        ret = ((viper_fun_2_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 2), mp_convert_obj_to_native(args[1], self->type_sig >> 4));
382
    } else if (n_args == 3) {
383
        ret = ((viper_fun_3_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 2), mp_convert_obj_to_native(args[1], self->type_sig >> 4), mp_convert_obj_to_native(args[2], self->type_sig >> 6));
384
385
386
387
388
    } else {
        assert(0);
        ret = 0;
    }

389
    return mp_convert_native_to_obj(ret, self->type_sig);
390
391
392
393
394
395
396
397
}

STATIC const mp_obj_type_t mp_type_fun_viper = {
    { &mp_type_type },
    .name = MP_QSTR_function,
    .call = fun_viper_call,
};

398
mp_obj_t mp_obj_new_fun_viper(mp_uint_t n_args, void *fun_data, mp_uint_t type_sig) {
399
400
401
    mp_obj_fun_viper_t *o = m_new_obj(mp_obj_fun_viper_t);
    o->base.type = &mp_type_fun_viper;
    o->n_args = n_args;
402
    o->fun_data = fun_data;
403
404
405
406
407
408
    o->type_sig = type_sig;
    return o;
}

#endif // MICROPY_EMIT_NATIVE

409
410
411
/******************************************************************************/
/* inline assembler functions                                                 */

412
413
#if MICROPY_EMIT_INLINE_THUMB

414
415
typedef struct _mp_obj_fun_asm_t {
    mp_obj_base_t base;
416
417
    mp_uint_t n_args;
    void *fun_data; // GC must be able to trace this pointer
418
419
} mp_obj_fun_asm_t;

420
421
422
423
typedef mp_uint_t (*inline_asm_fun_0_t)();
typedef mp_uint_t (*inline_asm_fun_1_t)(mp_uint_t);
typedef mp_uint_t (*inline_asm_fun_2_t)(mp_uint_t, mp_uint_t);
typedef mp_uint_t (*inline_asm_fun_3_t)(mp_uint_t, mp_uint_t, mp_uint_t);
424
425

// convert a Micro Python object to a sensible value for inline asm
426
STATIC mp_uint_t convert_obj_for_inline_asm(mp_obj_t obj) {
427
428
429
430
431
432
433
434
435
    // 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;
436
    } else if (MP_OBJ_IS_STR(obj)) {
437
        // pointer to the string (it's probably constant though!)
438
        mp_uint_t l;
439
        return (mp_uint_t)mp_obj_str_get_data(obj, &l);
440
441
442
    } else {
        mp_obj_type_t *type = mp_obj_get_type(obj);
        if (0) {
443
#if MICROPY_PY_BUILTINS_FLOAT
444
445
        } else if (type == &mp_type_float) {
            // convert float to int (could also pass in float registers)
446
            return (mp_int_t)mp_obj_float_get(obj);
447
#endif
448
449
        } else if (type == &mp_type_tuple) {
            // pointer to start of tuple (could pass length, but then could use len(x) for that)
450
            mp_uint_t len;
451
452
            mp_obj_t *items;
            mp_obj_tuple_get(obj, &len, &items);
453
            return (mp_uint_t)items;
454
455
        } else if (type == &mp_type_list) {
            // pointer to start of list (could pass length, but then could use len(x) for that)
456
            mp_uint_t len;
457
458
            mp_obj_t *items;
            mp_obj_list_get(obj, &len, &items);
459
            return (mp_uint_t)items;
460
        } else {
461
            mp_buffer_info_t bufinfo;
462
            if (mp_get_buffer(obj, &bufinfo, MP_BUFFER_WRITE)) {
463
                // supports the buffer protocol, return a pointer to the data
464
                return (mp_uint_t)bufinfo.buf;
465
466
            } else {
                // just pass along a pointer to the object
467
                return (mp_uint_t)obj;
468
            }
469
        }
470
471
472
473
    }
}

// convert a return value from inline asm to a sensible Micro Python object
474
STATIC mp_obj_t convert_val_from_inline_asm(mp_uint_t val) {
475
476
477
    return MP_OBJ_NEW_SMALL_INT(val);
}

478
STATIC mp_obj_t fun_asm_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
479
480
    mp_obj_fun_asm_t *self = self_in;

481
    mp_arg_check_num(n_args, n_kw, self->n_args, self->n_args, false);
482

483
484
    void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data);

485
    mp_uint_t ret;
486
    if (n_args == 0) {
487
        ret = ((inline_asm_fun_0_t)fun)();
488
    } else if (n_args == 1) {
489
        ret = ((inline_asm_fun_1_t)fun)(convert_obj_for_inline_asm(args[0]));
490
    } else if (n_args == 2) {
491
        ret = ((inline_asm_fun_2_t)fun)(convert_obj_for_inline_asm(args[0]), convert_obj_for_inline_asm(args[1]));
492
    } else if (n_args == 3) {
493
        ret = ((inline_asm_fun_3_t)fun)(convert_obj_for_inline_asm(args[0]), convert_obj_for_inline_asm(args[1]), convert_obj_for_inline_asm(args[2]));
494
495
496
497
498
499
500
501
    } else {
        assert(0);
        ret = 0;
    }

    return convert_val_from_inline_asm(ret);
}

502
STATIC const mp_obj_type_t mp_type_fun_asm = {
503
    { &mp_type_type },
504
    .name = MP_QSTR_function,
505
    .call = fun_asm_call,
506
507
};

508
mp_obj_t mp_obj_new_fun_asm(mp_uint_t n_args, void *fun_data) {
509
    mp_obj_fun_asm_t *o = m_new_obj(mp_obj_fun_asm_t);
510
    o->base.type = &mp_type_fun_asm;
511
    o->n_args = n_args;
512
    o->fun_data = fun_data;
513
514
    return o;
}
515
516

#endif // MICROPY_EMIT_INLINE_THUMB