runtime.c 48 KB
Newer Older
1
2
// in principle, rt_xxx functions are called only by vm/native/viper and make assumptions about args
// py_xxx functions are safer and can be called by anyone
3
// note that rt_assign_xxx are called only from emit*, and maybe we can rename them to reflect this
4

Damien's avatar
Damien committed
5
6
7
8
9
10
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

11
#include "nlr.h"
Damien's avatar
Damien committed
12
#include "misc.h"
13
#include "mpyconfig.h"
Damien's avatar
Damien committed
14
#include "runtime.h"
15
#include "bc.h"
Damien's avatar
Damien committed
16

17
#if 0 // print debugging info
18
19
#define DEBUG_PRINT (1)
#define WRITE_NATIVE (1)
20
21
22
#define DEBUG_printf(args...) printf(args)
#define DEBUG_OP_printf(args...) printf(args)
#else // don't print debugging info
23
#define DEBUG_printf(args...) (void)0
Damien's avatar
Damien committed
24
#define DEBUG_OP_printf(args...) (void)0
25
#endif
Damien's avatar
Damien committed
26
27
28
29
30
31
32
33

typedef machine_int_t py_small_int_t;

#define IS_O(o, k) (((((py_small_int_t)(o)) & 1) == 0) && (((py_obj_base_t*)(o))->kind == (k)))
#define IS_SMALL_INT(o) (((py_small_int_t)(o)) & 1)
#define FROM_SMALL_INT(o) (((py_small_int_t)(o)) >> 1)
#define TO_SMALL_INT(o) ((py_obj_t)(((o) << 1) | 1))

34
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
35
36
37
38
39
40
typedef machine_float_t float_t;
#endif

typedef enum {
    O_CONST,
    O_STR,
41
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
42
43
    O_FLOAT,
#endif
44
45
46
47
    O_EXCEPTION_0,
    O_EXCEPTION_2,
    O_RANGE,
    O_RANGE_IT,
Damien's avatar
Damien committed
48
49
50
51
52
    O_FUN_0,
    O_FUN_1,
    O_FUN_2,
    O_FUN_N,
    O_FUN_BC,
53
    O_FUN_ASM,
54
55
    O_GEN_WRAP,
    O_GEN_INSTANCE,
Damien's avatar
Damien committed
56
    O_BOUND_METH,
57
    O_TUPLE,
Damien's avatar
Damien committed
58
    O_LIST,
59
60
    O_TUPLE_IT,
    O_LIST_IT,
Damien's avatar
Damien committed
61
62
63
    O_SET,
    O_MAP,
    O_CLASS,
64
    O_OBJ,
Damien's avatar
Damien committed
65
66
67
68
69
70
71
72
73
74
75
76
77
} py_obj_kind_t;

typedef enum {
    MAP_QSTR,
    MAP_PY_OBJ,
} py_map_kind_t;

typedef struct _py_map_elem_t {
    py_obj_t key;
    py_obj_t value;
} py_map_elem_t;

typedef struct _py_map_t {
78
    py_map_kind_t kind; // TODO merge this 1-bit field into alloc or used
Damien's avatar
Damien committed
79
80
81
82
83
    machine_uint_t alloc;
    machine_uint_t used;
    py_map_elem_t *table;
} py_map_t;

84
85
86
typedef struct _py_obj_base_t py_obj_base_t;

struct _py_obj_base_t {
Damien's avatar
Damien committed
87
88
89
90
    py_obj_kind_t kind;
    union {
        const char *id;
        qstr u_str;
91
#if MICROPY_ENABLE_FLOAT
92
        float_t u_flt;
Damien's avatar
Damien committed
93
#endif
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
        struct { // for O_EXCEPTION_0
            qstr id;
        } u_exc0;
        struct { // for O_EXCEPTION_2
            // TODO reduce size or make generic object or something
            qstr id;
            const char *fmt;
            const char *s1;
            const char *s2;
        } u_exc2;
        struct { // for O_RANGE
            // TODO make generic object or something
            machine_int_t start;
            machine_int_t stop;
            machine_int_t step;
        } u_range;
        struct { // for O_RANGE_IT
            // TODO make generic object or something
            machine_int_t cur;
            machine_int_t stop;
            machine_int_t step;
        } u_range_it;
Damien's avatar
Damien committed
116
117
        struct { // for O_FUN_[012N]
            int n_args;
118
            void *fun;
Damien's avatar
Damien committed
119
120
        } u_fun;
        struct { // for O_FUN_BC
121
            int n_args;
Damien's avatar
Damien committed
122
123
124
            byte *code;
            uint len;
        } u_fun_bc;
125
126
127
128
        struct { // for O_FUN_ASM
            int n_args;
            void *fun;
        } u_fun_asm;
129
130
131
132
133
134
135
136
137
        struct { // for O_GEN_WRAP
            int n_state;
            py_obj_base_t *fun;
        } u_gen_wrap;
        struct { // for O_GEN_INSTANCE
            py_obj_t *state;
            const byte *ip;
            py_obj_t *sp;
        } u_gen_instance;
Damien's avatar
Damien committed
138
139
140
141
        struct { // for O_BOUND_METH
            py_obj_t meth;
            py_obj_t self;
        } u_bound_meth;
142
        struct { // for O_TUPLE, O_LIST
Damien's avatar
Damien committed
143
144
145
            int alloc;
            int len;
            py_obj_t *items;
146
147
148
149
150
        } u_tuple_list;
        struct { // for O_TUPLE_IT, O_LIST_IT
            py_obj_base_t *obj;
            int cur;
        } u_tuple_list_it;
Damien's avatar
Damien committed
151
152
153
154
155
156
157
        struct { // for O_SET
            int alloc;
            int used;
            py_obj_t *table;
        } u_set;
        py_map_t u_map; // for O_MAP
        struct { // for O_CLASS
158
            py_map_t *locals;
Damien's avatar
Damien committed
159
        } u_class;
160
161
162
163
        struct { // for O_OBJ
            py_obj_base_t *class; // points to a O_CLASS object
            py_map_t *members;
        } u_obj;
Damien's avatar
Damien committed
164
    };
165
};
Damien's avatar
Damien committed
166
167
168
169

py_obj_t py_const_none;
py_obj_t py_const_false;
py_obj_t py_const_true;
170
py_obj_t py_const_stop_iteration;
Damien's avatar
Damien committed
171

172
173
174
// locals and globals need to be pointers because they can be the same in outer module scope
py_map_t *map_locals;
py_map_t *map_globals;
Damien's avatar
Damien committed
175
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
py_map_t map_builtins;

// approximatelly doubling primes; made with Mathematica command: Table[Prime[Floor[(1.7)^n]], {n, 3, 24}]
static int doubling_primes[] = {7, 19, 43, 89, 179, 347, 647, 1229, 2297, 4243, 7829, 14347, 26017, 47149, 84947, 152443, 273253, 488399, 869927, 1547173, 2745121, 4861607};

int get_doubling_prime_greater_or_equal_to(int x) {
    for (int i = 0; i < sizeof(doubling_primes) / sizeof(int); i++) {
        if (doubling_primes[i] >= x) {
            return doubling_primes[i];
        }
    }
    // ran out of primes in the table!
    // return something sensible, at least make it odd
    return x | 1;
}

void py_map_init(py_map_t *map, py_map_kind_t kind, int n) {
    map->kind = kind;
    map->alloc = get_doubling_prime_greater_or_equal_to(n + 1);
    map->used = 0;
    map->table = m_new(py_map_elem_t, map->alloc);
    for (int i = 0; i < map->alloc; i++) {
        map->table[i].key = NULL;
        map->table[i].value = NULL;
    }
}

py_map_t *py_map_new(py_map_kind_t kind, int n) {
    py_map_t *map = m_new(py_map_t, 1);
    py_map_init(map, kind, n);
    return map;
}

int py_obj_hash(py_obj_t o_in) {
    if (IS_SMALL_INT(o_in)) {
        return FROM_SMALL_INT(o_in);
    } else if (IS_O(o_in, O_STR)) {
        return ((py_obj_base_t*)o_in)->u_str;
    } else {
        assert(0);
        return 0;
    }
}

bool py_obj_equal(py_obj_t o1, py_obj_t o2) {
    if (o1 == o2) {
        return true;
    } else if (IS_SMALL_INT(o1) && IS_SMALL_INT(o2)) {
        return false;
    } else if (IS_O(o1, O_STR) && IS_O(o2, O_STR)) {
        return ((py_obj_base_t*)o1)->u_str == ((py_obj_base_t*)o2)->u_str;
    } else {
        assert(0);
        return false;
    }
}

py_map_elem_t* py_map_lookup_helper(py_map_t *map, py_obj_t index, bool add_if_not_found) {
    bool is_map_py_obj = (map->kind == MAP_PY_OBJ);
    machine_uint_t hash;
    if (is_map_py_obj) {
        hash = py_obj_hash(index);
    } else {
        hash = (machine_uint_t)index;
    }
    uint pos = hash % map->alloc;
    for (;;) {
        py_map_elem_t *elem = &map->table[pos];
        if (elem->key == NULL) {
            // not in table
            if (add_if_not_found) {
                if (map->used + 1 >= map->alloc) {
                    // not enough room in table, rehash it
                    int old_alloc = map->alloc;
                    py_map_elem_t *old_table = map->table;
                    map->alloc = get_doubling_prime_greater_or_equal_to(map->alloc + 1);
                    map->used = 0;
                    map->table = m_new(py_map_elem_t, map->alloc);
                    for (int i = 0; i < old_alloc; i++) {
                        if (old_table[i].key != NULL) {
                            py_map_lookup_helper(map, old_table[i].key, true)->value = old_table[i].value;
                        }
                    }
                    m_free(old_table);
                    // restart the search for the new element
                    pos = hash % map->alloc;
                } else {
                    map->used += 1;
                    elem->key = index;
                    return elem;
                }
            } else {
                return NULL;
            }
        } else if (elem->key == index || (is_map_py_obj && py_obj_equal(elem->key, index))) {
            // found it
            if (add_if_not_found) {
                elem->key = index;
            }
            return elem;
        } else {
            // not yet found, keep searching in this table
            pos = (pos + 1) % map->alloc;
        }
    }
}

py_map_elem_t* py_qstr_map_lookup(py_map_t *map, qstr index, bool add_if_not_found) {
    py_obj_t o = (py_obj_t)(machine_uint_t)index;
    return py_map_lookup_helper(map, o, add_if_not_found);
}

py_map_elem_t* py_map_lookup(py_obj_t o, py_obj_t index, bool add_if_not_found) {
    assert(IS_O(o, O_MAP));
    return py_map_lookup_helper(&((py_obj_base_t *)o)->u_map, index, add_if_not_found);
}

static bool fit_small_int(py_small_int_t o) {
    return true;
}

py_obj_t py_obj_new_const(const char *id) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_CONST;
    o->id = id;
    return (py_obj_t)o;
}

py_obj_t py_obj_new_str(qstr qstr) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_STR;
    o->u_str = qstr;
    return (py_obj_t)o;
}

310
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
311
312
313
py_obj_t py_obj_new_float(float_t val) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_FLOAT;
314
    o->u_flt = val;
Damien's avatar
Damien committed
315
316
317
318
    return (py_obj_t)o;
}
#endif

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
351
352
353
354
py_obj_t py_obj_new_exception_0(qstr id) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_EXCEPTION_0;
    o->u_exc0.id = id;
    return (py_obj_t)o;
}

py_obj_t py_obj_new_exception_2(qstr id, const char *fmt, const char *s1, const char *s2) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_EXCEPTION_2;
    o->u_exc2.id = id;
    o->u_exc2.fmt = fmt;
    o->u_exc2.s1 = s1;
    o->u_exc2.s2 = s2;
    return (py_obj_t)o;
}

// range is a class and instances are immutable sequence objects
py_obj_t py_obj_new_range(int start, int stop, int step) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_RANGE;
    o->u_range.start = start;
    o->u_range.stop = stop;
    o->u_range.step = step;
    return o;
}

py_obj_t py_obj_new_range_iterator(int cur, int stop, int step) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_RANGE_IT;
    o->u_range_it.cur = cur;
    o->u_range_it.stop = stop;
    o->u_range_it.step = step;
    return o;
}

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
py_obj_t py_obj_new_tuple_iterator(py_obj_base_t *tuple, int cur) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_TUPLE_IT;
    o->u_tuple_list_it.obj = tuple;
    o->u_tuple_list_it.cur = cur;
    return o;
}

py_obj_t py_obj_new_list_iterator(py_obj_base_t *list, int cur) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_LIST_IT;
    o->u_tuple_list_it.obj = list;
    o->u_tuple_list_it.cur = cur;
    return o;
}

py_obj_t rt_list_append(py_obj_t self_in, py_obj_t arg) {
Damien's avatar
Damien committed
372
373
    assert(IS_O(self_in, O_LIST));
    py_obj_base_t *self = self_in;
374
375
376
    if (self->u_tuple_list.len >= self->u_tuple_list.alloc) {
        self->u_tuple_list.alloc *= 2;
        self->u_tuple_list.items = m_renew(py_obj_t, self->u_tuple_list.items, self->u_tuple_list.alloc);
Damien's avatar
Damien committed
377
    }
378
    self->u_tuple_list.items[self->u_tuple_list.len++] = arg;
Damien's avatar
Damien committed
379
380
381
    return arg;
}

382
383
384
385
386
387
388
389
390
py_obj_t rt_gen_instance_next(py_obj_t self_in) {
    py_obj_t ret = rt_iternext(self_in);
    if (ret == py_const_stop_iteration) {
        nlr_jump(py_obj_new_exception_0(qstr_from_str_static("StopIteration")));
    } else {
        return ret;
    }
}

Damien's avatar
Damien committed
391
392
393
394
static qstr q_append;
static qstr q_print;
static qstr q_len;
static qstr q___build_class__;
395
static qstr q___next__;
396
static qstr q_AttributeError;
397
static qstr q_IndexError;
398
399
static qstr q_NameError;
static qstr q_TypeError;
Damien's avatar
Damien committed
400
401

typedef enum {
402
    PY_CODE_NONE,
Damien's avatar
Damien committed
403
    PY_CODE_BYTE,
404
405
    PY_CODE_NATIVE,
    PY_CODE_INLINE_ASM,
Damien's avatar
Damien committed
406
407
408
409
410
} py_code_kind_t;

typedef struct _py_code_t {
    py_code_kind_t kind;
    int n_args;
411
412
413
    int n_locals;
    int n_stack;
    bool is_generator;
Damien's avatar
Damien committed
414
415
416
417
418
    union {
        struct {
            byte *code;
            uint len;
        } u_byte;
419
420
421
422
        struct {
            py_fun_t fun;
        } u_native;
        struct {
423
            void *fun;
424
        } u_inline_asm;
Damien's avatar
Damien committed
425
426
427
428
429
430
431
    };
} py_code_t;

static int next_unique_code_id;
static py_code_t *unique_codes;

py_obj_t fun_list_append;
432
py_obj_t fun_gen_instance_next;
Damien's avatar
Damien committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447

py_obj_t py_builtin_print(py_obj_t o) {
    if (IS_O(o, O_STR)) {
        // special case, print string raw
        printf("%s\n", qstr_str(((py_obj_base_t*)o)->u_str));
    } else {
        // print the object Python style
        py_obj_print(o);
        printf("\n");
    }
    return py_const_none;
}

py_obj_t py_builtin_len(py_obj_t o_in) {
    py_small_int_t len = 0;
448
    if (IS_O(o_in, O_TUPLE) || IS_O(o_in, O_LIST)) {
Damien's avatar
Damien committed
449
        py_obj_base_t *o = o_in;
450
        len = o->u_tuple_list.len;
Damien's avatar
Damien committed
451
452
453
454
455
456
457
458
459
    } else if (IS_O(o_in, O_MAP)) {
        py_obj_base_t *o = o_in;
        len = o->u_map.used;
    } else {
        assert(0);
    }
    return TO_SMALL_INT(len);
}

460
461
py_obj_t py_builtin___build_class__(py_obj_t o_class_fun, py_obj_t o_class_name) {
    // we differ from CPython: we set the new __locals__ object here
462
    py_map_t *old_locals = map_locals;
463
    py_map_t *class_locals = py_map_new(MAP_QSTR, 0);
464
    map_locals = class_locals;
465
466
467
468
469
470
471
472

    // call the class code
    rt_call_function_1(o_class_fun, (py_obj_t)0xdeadbeef);

    // restore old __locals__ object
    map_locals = old_locals;

    // create and return the new class
Damien's avatar
Damien committed
473
474
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_CLASS;
475
    o->u_class.locals = class_locals;
Damien's avatar
Damien committed
476
477
478
    return o;
}

479
480
481
482
py_obj_t py_builtin_range(py_obj_t o_arg) {
    return py_obj_new_range(0, rt_get_int(o_arg), 1);
}

483
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
484
FILE *fp_native = NULL;
485
#endif
Damien's avatar
Damien committed
486
487
488
489
490
491

void rt_init() {
    q_append = qstr_from_str_static("append");
    q_print = qstr_from_str_static("print");
    q_len = qstr_from_str_static("len");
    q___build_class__ = qstr_from_str_static("__build_class__");
492
    q___next__ = qstr_from_str_static("__next__");
493
    q_AttributeError = qstr_from_str_static("AttributeError");
494
    q_IndexError = qstr_from_str_static("IndexError");
495
496
    q_NameError = qstr_from_str_static("NameError");
    q_TypeError = qstr_from_str_static("TypeError");
Damien's avatar
Damien committed
497
498
499
500

    py_const_none = py_obj_new_const("None");
    py_const_false = py_obj_new_const("False");
    py_const_true = py_obj_new_const("True");
501
    py_const_stop_iteration = py_obj_new_const("StopIteration");
Damien's avatar
Damien committed
502

503
504
505
    // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
    map_locals = map_globals = py_map_new(MAP_QSTR, 1);
    py_qstr_map_lookup(map_globals, qstr_from_str_static("__name__"), true)->value = py_obj_new_str(qstr_from_str_static("__main__"));
Damien's avatar
Damien committed
506
507
508
509
510

    py_map_init(&map_builtins, MAP_QSTR, 3);
    py_qstr_map_lookup(&map_builtins, q_print, true)->value = rt_make_function_1(py_builtin_print);
    py_qstr_map_lookup(&map_builtins, q_len, true)->value = rt_make_function_1(py_builtin_len);
    py_qstr_map_lookup(&map_builtins, q___build_class__, true)->value = rt_make_function_2(py_builtin___build_class__);
511
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("range"), true)->value = rt_make_function_1(py_builtin_range);
Damien's avatar
Damien committed
512
513
514
515

    next_unique_code_id = 1;
    unique_codes = NULL;

516
    fun_list_append = rt_make_function_2(rt_list_append);
517
    fun_gen_instance_next = rt_make_function_1(rt_gen_instance_next);
Damien's avatar
Damien committed
518

519
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
520
    fp_native = fopen("out-native", "wb");
521
#endif
Damien's avatar
Damien committed
522
523
524
}

void rt_deinit() {
525
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
526
527
528
    if (fp_native != NULL) {
        fclose(fp_native);
    }
529
#endif
Damien's avatar
Damien committed
530
531
532
533
534
535
}

int rt_get_new_unique_code_id() {
    return next_unique_code_id++;
}

536
static void alloc_unique_codes() {
Damien's avatar
Damien committed
537
538
    if (unique_codes == NULL) {
        unique_codes = m_new(py_code_t, next_unique_code_id);
539
540
541
        for (int i = 0; i < next_unique_code_id; i++) {
            unique_codes[i].kind = PY_CODE_NONE;
        }
Damien's avatar
Damien committed
542
    }
543
544
}

545
void rt_assign_byte_code(int unique_code_id, byte *code, uint len, int n_args, int n_locals, int n_stack, bool is_generator) {
546
547
548
549
550
    alloc_unique_codes();

    assert(unique_code_id < next_unique_code_id);
    unique_codes[unique_code_id].kind = PY_CODE_BYTE;
    unique_codes[unique_code_id].n_args = n_args;
551
552
553
    unique_codes[unique_code_id].n_locals = n_locals;
    unique_codes[unique_code_id].n_stack = n_stack;
    unique_codes[unique_code_id].is_generator = is_generator;
554
555
556
557
558
559
560
561
562
    unique_codes[unique_code_id].u_byte.code = code;
    unique_codes[unique_code_id].u_byte.len = len;

    DEBUG_printf("assign byte code: id=%d code=%p len=%u n_args=%d\n", unique_code_id, code, len, n_args);
}

void rt_assign_native_code(int unique_code_id, py_fun_t fun, uint len, int n_args) {
    alloc_unique_codes();

563
    assert(1 <= unique_code_id && unique_code_id < next_unique_code_id);
Damien's avatar
Damien committed
564
565
    unique_codes[unique_code_id].kind = PY_CODE_NATIVE;
    unique_codes[unique_code_id].n_args = n_args;
566
567
568
    unique_codes[unique_code_id].n_locals = 0;
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
Damien's avatar
Damien committed
569
570
    unique_codes[unique_code_id].u_native.fun = fun;

571
#ifdef DEBUG_PRINT
Damien's avatar
Damien committed
572
573
574
575
576
577
578
579
580
581
    DEBUG_printf("assign native code: id=%d fun=%p len=%u n_args=%d\n", unique_code_id, fun, len, n_args);
    byte *fun_data = (byte*)(((machine_uint_t)fun) & (~1)); // need to clear lower bit in case it's thumb code
    for (int i = 0; i < 128 && i < len; i++) {
        if (i > 0 && i % 16 == 0) {
            DEBUG_printf("\n");
        }
        DEBUG_printf(" %02x", fun_data[i]);
    }
    DEBUG_printf("\n");

582
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
583
584
    if (fp_native != NULL) {
        fwrite(fun_data, len, 1, fp_native);
585
        fflush(fp_native);
Damien's avatar
Damien committed
586
    }
587
588
#endif
#endif
Damien's avatar
Damien committed
589
590
}

591
592
593
594
595
void rt_assign_inline_asm_code(int unique_code_id, py_fun_t fun, uint len, int n_args) {
    alloc_unique_codes();

    assert(1 <= unique_code_id && unique_code_id < next_unique_code_id);
    unique_codes[unique_code_id].kind = PY_CODE_INLINE_ASM;
Damien's avatar
Damien committed
596
    unique_codes[unique_code_id].n_args = n_args;
597
598
599
    unique_codes[unique_code_id].n_locals = 0;
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
600
    unique_codes[unique_code_id].u_inline_asm.fun = fun;
Damien's avatar
Damien committed
601

602
#ifdef DEBUG_PRINT
603
604
605
606
607
608
609
610
611
612
    DEBUG_printf("assign inline asm code: id=%d fun=%p len=%u n_args=%d\n", unique_code_id, fun, len, n_args);
    byte *fun_data = (byte*)(((machine_uint_t)fun) & (~1)); // need to clear lower bit in case it's thumb code
    for (int i = 0; i < 128 && i < len; i++) {
        if (i > 0 && i % 16 == 0) {
            DEBUG_printf("\n");
        }
        DEBUG_printf(" %02x", fun_data[i]);
    }
    DEBUG_printf("\n");

613
#ifdef WRITE_NATIVE
614
615
616
    if (fp_native != NULL) {
        fwrite(fun_data, len, 1, fp_native);
    }
617
618
#endif
#endif
Damien's avatar
Damien committed
619
620
}

621
622
623
624
625
626
627
628
629
630
631
632
bool py_obj_is_callable(py_obj_t o_in) {
    if (IS_SMALL_INT(o_in)) {
        return false;
    } else {
        py_obj_base_t *o = o_in;
        switch (o->kind) {
            case O_FUN_0:
            case O_FUN_1:
            case O_FUN_2:
            case O_FUN_N:
            case O_FUN_BC:
            case O_FUN_ASM:
633
            // what about O_CLASS, and an O_OBJ that has a __call__ method?
634
635
636
637
638
639
640
                return true;
            default:
                return false;
        }
    }
}

Damien's avatar
Damien committed
641
642
643
644
645
646
647
648
649
650
651
652
653
654
const char *py_obj_get_type_str(py_obj_t o_in) {
    if (IS_SMALL_INT(o_in)) {
        return "int";
    } else {
        py_obj_base_t *o = o_in;
        switch (o->kind) {
            case O_CONST:
                if (o == py_const_none) {
                    return "NoneType";
                } else {
                    return "bool";
                }
            case O_STR:
                return "str";
655
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
656
657
658
            case O_FLOAT:
                return "float";
#endif
659
660
661
662
663
664
            case O_FUN_0:
            case O_FUN_1:
            case O_FUN_2:
            case O_FUN_N:
            case O_FUN_BC:
                return "function";
665
666
            case O_GEN_INSTANCE:
                return "generator";
667
668
            case O_TUPLE:
                return "tuple";
Damien's avatar
Damien committed
669
670
            case O_LIST:
                return "list";
671
672
673
674
            case O_TUPLE_IT:
                return "tuple_iterator";
            case O_LIST_IT:
                return "list_iterator";
Damien's avatar
Damien committed
675
676
677
678
            case O_SET:
                return "set";
            case O_MAP:
                return "dict";
679
680
681
682
683
684
685
            case O_OBJ:
            {
                py_map_elem_t *qn = py_qstr_map_lookup(o->u_obj.class->u_class.locals, qstr_from_str_static("__qualname__"), false);
                assert(qn != NULL);
                assert(IS_O(qn->value, O_STR));
                return qstr_str(((py_obj_base_t*)qn->value)->u_str);
            }
Damien's avatar
Damien committed
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
            default:
                assert(0);
                return "UnknownType";
        }
    }
}

void py_obj_print(py_obj_t o_in) {
    if (IS_SMALL_INT(o_in)) {
        printf("%d", (int)FROM_SMALL_INT(o_in));
    } else {
        py_obj_base_t *o = o_in;
        switch (o->kind) {
            case O_CONST:
                printf("%s", o->id);
                break;
            case O_STR:
                // TODO need to escape chars etc
                printf("'%s'", qstr_str(o->u_str));
                break;
706
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
707
            case O_FLOAT:
708
                printf("%f", o->u_flt);
Damien's avatar
Damien committed
709
710
                break;
#endif
711
712
713
            case O_EXCEPTION_0:
                printf("%s", qstr_str(o->u_exc0.id));
                break;
714
715
716
717
            case O_EXCEPTION_2:
                printf("%s: ", qstr_str(o->u_exc2.id));
                printf(o->u_exc2.fmt, o->u_exc2.s1, o->u_exc2.s2);
                break;
718
719
720
            case O_GEN_INSTANCE:
                printf("<generator object 'fun-name' at %p>", o);
                break;
721
722
723
724
725
726
727
728
729
730
731
732
733
            case O_TUPLE:
                printf("(");
                for (int i = 0; i < o->u_tuple_list.len; i++) {
                    if (i > 0) {
                        printf(", ");
                    }
                    py_obj_print(o->u_tuple_list.items[i]);
                }
                if (o->u_tuple_list.len == 1) {
                    printf(",");
                }
                printf(")");
                break;
Damien's avatar
Damien committed
734
735
            case O_LIST:
                printf("[");
736
                for (int i = 0; i < o->u_tuple_list.len; i++) {
Damien's avatar
Damien committed
737
738
739
                    if (i > 0) {
                        printf(", ");
                    }
740
                    py_obj_print(o->u_tuple_list.items[i]);
Damien's avatar
Damien committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
                }
                printf("]");
                break;
            case O_SET:
            {
                bool first = true;
                printf("{");
                for (int i = 0; i < o->u_set.alloc; i++) {
                    if (o->u_set.table[i] != NULL) {
                        if (!first) {
                            printf(", ");
                        }
                        first = false;
                        py_obj_print(o->u_set.table[i]);
                    }
                }
                printf("}");
                break;
            }
            case O_MAP:
            {
                bool first = true;
                printf("{");
                for (int i = 0; i < o->u_map.alloc; i++) {
                    if (o->u_map.table[i].key != NULL) {
                        if (!first) {
                            printf(", ");
                        }
                        first = false;
                        py_obj_print(o->u_map.table[i].key);
                        printf(": ");
                        py_obj_print(o->u_map.table[i].value);
                    }
                }
                printf("}");
                break;
            }
            default:
779
                printf("<? %d>", o->kind);
Damien's avatar
Damien committed
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
                assert(0);
        }
    }
}

int rt_is_true(py_obj_t arg) {
    DEBUG_OP_printf("is true %p\n", arg);
    if (IS_SMALL_INT(arg)) {
        if (FROM_SMALL_INT(arg) == 0) {
            return 0;
        } else {
            return 1;
        }
    } else if (arg == py_const_none) {
        return 0;
    } else if (arg == py_const_false) {
        return 0;
    } else if (arg == py_const_true) {
        return 1;
    } else {
        assert(0);
        return 0;
    }
}

int rt_get_int(py_obj_t arg) {
806
807
808
809
810
    if (arg == py_const_false) {
        return 0;
    } else if (arg == py_const_true) {
        return 1;
    } else if (IS_SMALL_INT(arg)) {
Damien's avatar
Damien committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
        return FROM_SMALL_INT(arg);
    } else {
        assert(0);
        return 0;
    }
}

py_obj_t rt_load_const_str(qstr qstr) {
    DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
    return py_obj_new_str(qstr);
}

py_obj_t rt_load_name(qstr qstr) {
    // logic: search locals, globals, builtins
825
    DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
826
    py_map_elem_t *elem = py_qstr_map_lookup(map_locals, qstr, false);
Damien's avatar
Damien committed
827
    if (elem == NULL) {
828
        elem = py_qstr_map_lookup(map_globals, qstr, false);
Damien's avatar
Damien committed
829
        if (elem == NULL) {
830
831
            elem = py_qstr_map_lookup(&map_builtins, qstr, false);
            if (elem == NULL) {
832
                nlr_jump(py_obj_new_exception_2(q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
833
            }
Damien's avatar
Damien committed
834
835
836
837
838
839
        }
    }
    return elem->value;
}

py_obj_t rt_load_global(qstr qstr) {
840
841
    // logic: search globals, builtins
    DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
842
    py_map_elem_t *elem = py_qstr_map_lookup(map_globals, qstr, false);
843
844
845
    if (elem == NULL) {
        elem = py_qstr_map_lookup(&map_builtins, qstr, false);
        if (elem == NULL) {
846
            nlr_jump(py_obj_new_exception_2(q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
847
848
849
        }
    }
    return elem->value;
Damien's avatar
Damien committed
850
851
852
853
854
855
856
857
858
859
860
861
862
}

py_obj_t rt_load_build_class() {
    DEBUG_OP_printf("load_build_class\n");
    py_map_elem_t *elem = py_qstr_map_lookup(&map_builtins, q___build_class__, false);
    if (elem == NULL) {
        printf("name doesn't exist: __build_class__\n");
        assert(0);
    }
    return elem->value;
}

void rt_store_name(qstr qstr, py_obj_t obj) {
863
    DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
864
    py_qstr_map_lookup(map_locals, qstr, true)->value = obj;
865
866
867
868
}

void rt_store_global(qstr qstr, py_obj_t obj) {
    DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qstr), obj);
869
    py_qstr_map_lookup(map_globals, qstr, true)->value = obj;
Damien's avatar
Damien committed
870
871
872
873
874
875
876
}

py_obj_t rt_unary_op(int op, py_obj_t arg) {
    assert(0);
    return py_const_none;
}

877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
uint get_index(py_obj_base_t *base, py_obj_t index) {
    // assumes base is O_TUPLE or O_LIST
    // TODO False and True are considered 0 and 1 for indexing purposes
    int len = base->u_tuple_list.len;
    if (IS_SMALL_INT(index)) {
        int i = FROM_SMALL_INT(index);
        if (i < 0) {
            i += len;
        }
        if (i < 0 || i >= len) {
            nlr_jump(py_obj_new_exception_2(q_IndexError, "%s index out of range", py_obj_get_type_str(base), NULL));
        }
        return i;
    } else {
        nlr_jump(py_obj_new_exception_2(q_TypeError, "%s indices must be integers, not %s", py_obj_get_type_str(base), py_obj_get_type_str(index)));
    }
}

Damien's avatar
Damien committed
895
896
897
py_obj_t rt_binary_op(int op, py_obj_t lhs, py_obj_t rhs) {
    DEBUG_OP_printf("binary %d %p %p\n", op, lhs, rhs);
    if (op == RT_BINARY_OP_SUBSCR) {
898
899
900
        if ((IS_O(lhs, O_TUPLE) || IS_O(lhs, O_LIST))) {
            uint index = get_index(lhs, rhs);
            return ((py_obj_base_t*)lhs)->u_tuple_list.items[index];
Damien's avatar
Damien committed
901
902
903
904
905
906
907
908
        } else {
            assert(0);
        }
    } else if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
        py_small_int_t val;
        switch (op) {
            case RT_BINARY_OP_ADD:
            case RT_BINARY_OP_INPLACE_ADD: val = FROM_SMALL_INT(lhs) + FROM_SMALL_INT(rhs); break;
909
910
            case RT_BINARY_OP_SUBTRACT:
            case RT_BINARY_OP_INPLACE_SUBTRACT: val = FROM_SMALL_INT(lhs) - FROM_SMALL_INT(rhs); break;
Damien's avatar
Damien committed
911
912
            case RT_BINARY_OP_MULTIPLY: val = FROM_SMALL_INT(lhs) * FROM_SMALL_INT(rhs); break;
            case RT_BINARY_OP_FLOOR_DIVIDE: val = FROM_SMALL_INT(lhs) / FROM_SMALL_INT(rhs); break;
913
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
            case RT_BINARY_OP_TRUE_DIVIDE: return py_obj_new_float((float_t)FROM_SMALL_INT(lhs) / (float_t)FROM_SMALL_INT(rhs));
#endif
            default: printf("%d\n", op); assert(0); val = 0;
        }
        if (fit_small_int(val)) {
            return TO_SMALL_INT(val);
        }
    } else if (IS_O(lhs, O_STR) && IS_O(rhs, O_STR)) {
        const char *lhs_str = qstr_str(((py_obj_base_t*)lhs)->u_str);
        const char *rhs_str = qstr_str(((py_obj_base_t*)rhs)->u_str);
        char *val;
        switch (op) {
            case RT_BINARY_OP_ADD:
            case RT_BINARY_OP_INPLACE_ADD: val = m_new(char, strlen(lhs_str) + strlen(rhs_str) + 1); strcpy(val, lhs_str); strcat(val, rhs_str); break;
            default: printf("%d\n", op); assert(0); val = NULL;
        }
        return py_obj_new_str(qstr_from_str_take(val));
    }
    assert(0);
    return py_const_none;
}

py_obj_t rt_compare_op(int op, py_obj_t lhs, py_obj_t rhs) {
    DEBUG_OP_printf("compare %d %p %p\n", op, lhs, rhs);
    if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
        int cmp;
        switch (op) {
            case RT_COMPARE_OP_LESS: cmp = FROM_SMALL_INT(lhs) < FROM_SMALL_INT(rhs); break;
            case RT_COMPARE_OP_MORE: cmp = FROM_SMALL_INT(lhs) > FROM_SMALL_INT(rhs); break;
            default: assert(0); cmp = 0;
        }
        if (cmp) {
            return py_const_true;
        } else {
            return py_const_false;
        }
    }
    assert(0);
    return py_const_none;
}

py_obj_t rt_make_function_from_id(int unique_code_id) {
956
957
    DEBUG_OP_printf("make_function_from_id %d\n", unique_code_id);
    if (unique_code_id < 1 || unique_code_id >= next_unique_code_id) {
Damien's avatar
Damien committed
958
959
960
961
962
963
        // illegal code id
        return py_const_none;
    }
    py_code_t *c = &unique_codes[unique_code_id];
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    switch (c->kind) {
964
965
966
967
968
969
        case PY_CODE_BYTE:
            o->kind = O_FUN_BC;
            o->u_fun_bc.n_args = c->n_args;
            o->u_fun_bc.code = c->u_byte.code;
            o->u_fun_bc.len = c->u_byte.len;
            break;
Damien's avatar
Damien committed
970
971
972
973
974
975
976
977
978
        case PY_CODE_NATIVE:
            switch (c->n_args) {
                case 0: o->kind = O_FUN_0; break;
                case 1: o->kind = O_FUN_1; break;
                case 2: o->kind = O_FUN_2; break;
                default: assert(0);
            }
            o->u_fun.fun = c->u_native.fun;
            break;
979
980
981
982
        case PY_CODE_INLINE_ASM:
            o->kind = O_FUN_ASM;
            o->u_fun_asm.n_args = c->n_args;
            o->u_fun_asm.fun = c->u_inline_asm.fun;
Damien's avatar
Damien committed
983
984
985
986
            break;
        default:
            assert(0);
    }
987
988
989
990
991
992
993
994
995
996
997

    // check for generator functions and if so wrap in generator object
    if (c->is_generator) {
        py_obj_base_t *o2 = m_new(py_obj_base_t, 1);
        o2->kind = O_GEN_WRAP;
        // we have at least 3 locals so the bc can write back fast[0,1,2] safely; should improve how this is done
        o2->u_gen_wrap.n_state = (c->n_locals < 3 ? 3 : c->n_locals) + c->n_stack;
        o2->u_gen_wrap.fun = o;
        o = o2;
    }

Damien's avatar
Damien committed
998
999
1000
    return o;
}

For faster browsing, not all history is shown. View entire blame