runtime.c 56.8 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
    O_EXCEPTION_0,
45
    O_EXCEPTION_N,
46
47
    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
79
80
81
    struct {
        py_map_kind_t kind : 1;
        machine_uint_t used : (8 * BYTES_PER_WORD - 1);
    };
Damien's avatar
Damien committed
82
83
84
85
    machine_uint_t alloc;
    py_map_elem_t *table;
} py_map_t;

86
87
88
typedef struct _py_obj_base_t py_obj_base_t;

struct _py_obj_base_t {
Damien's avatar
Damien committed
89
90
91
92
    py_obj_kind_t kind;
    union {
        const char *id;
        qstr u_str;
93
#if MICROPY_ENABLE_FLOAT
94
        float_t u_flt;
Damien's avatar
Damien committed
95
#endif
96
97
98
        struct { // for O_EXCEPTION_0
            qstr id;
        } u_exc0;
99
100
        struct { // for O_EXCEPTION_N
            // TODO make generic object or something
101
            qstr id;
102
103
104
            int n_args;
            const void **args;
        } u_exc_n;
105
106
107
108
109
110
111
112
113
114
115
116
        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
117
118
        struct { // for O_FUN_[012N]
            int n_args;
119
            void *fun;
Damien's avatar
Damien committed
120
121
        } u_fun;
        struct { // for O_FUN_BC
122
            int n_args;
Damien's avatar
Damien committed
123
124
125
            byte *code;
            uint len;
        } u_fun_bc;
126
127
128
129
        struct { // for O_FUN_ASM
            int n_args;
            void *fun;
        } u_fun_asm;
130
131
132
133
134
135
136
137
138
        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
139
140
141
142
        struct { // for O_BOUND_METH
            py_obj_t meth;
            py_obj_t self;
        } u_bound_meth;
143
        struct { // for O_TUPLE, O_LIST
144
145
            machine_uint_t alloc;
            machine_uint_t len;
Damien's avatar
Damien committed
146
            py_obj_t *items;
147
148
149
        } u_tuple_list;
        struct { // for O_TUPLE_IT, O_LIST_IT
            py_obj_base_t *obj;
150
            machine_uint_t cur;
151
        } u_tuple_list_it;
Damien's avatar
Damien committed
152
        struct { // for O_SET
153
154
            machine_uint_t alloc;
            machine_uint_t used;
Damien's avatar
Damien committed
155
156
157
158
            py_obj_t *table;
        } u_set;
        py_map_t u_map; // for O_MAP
        struct { // for O_CLASS
159
            py_map_t *locals;
Damien's avatar
Damien committed
160
        } u_class;
161
162
163
164
        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
165
    };
166
};
Damien's avatar
Damien committed
167

168
169
170
171
172
173
174
175
176
177
178
179
static qstr q_append;
static qstr q_join;
static qstr q_print;
static qstr q_len;
static qstr q___build_class__;
static qstr q___next__;
static qstr q_AttributeError;
static qstr q_IndexError;
static qstr q_KeyError;
static qstr q_NameError;
static qstr q_TypeError;

Damien's avatar
Damien committed
180
181
182
py_obj_t py_const_none;
py_obj_t py_const_false;
py_obj_t py_const_true;
183
py_obj_t py_const_stop_iteration;
Damien's avatar
Damien committed
184

185
// locals and globals need to be pointers because they can be the same in outer module scope
186
187
188
static py_map_t *map_locals;
static py_map_t *map_globals;
static py_map_t map_builtins;
Damien's avatar
Damien committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

// 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->used = 0;
207
    map->alloc = get_doubling_prime_greater_or_equal_to(n + 1);
Damien's avatar
Damien committed
208
    map->table = m_new0(py_map_elem_t, map->alloc);
Damien's avatar
Damien committed
209
210
211
212
213
214
215
216
}

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;
}

Damien's avatar
Damien committed
217
218
219
220
221
222
machine_int_t py_obj_hash(py_obj_t o_in) {
    if (o_in == py_const_false) {
        return 0; // needs to hash to same as the integer 0, since False==0
    } else if (o_in == py_const_true) {
        return 1; // needs to hash to same as the integer 1, since True==1
    } else if (IS_SMALL_INT(o_in)) {
Damien's avatar
Damien committed
223
        return FROM_SMALL_INT(o_in);
Damien's avatar
Damien committed
224
225
    } else if (IS_O(o_in, O_CONST)) {
        return (machine_int_t)o_in;
Damien's avatar
Damien committed
226
227
228
229
230
231
232
233
    } else if (IS_O(o_in, O_STR)) {
        return ((py_obj_base_t*)o_in)->u_str;
    } else {
        assert(0);
        return 0;
    }
}

Damien's avatar
Damien committed
234
235
236
237
238
239
// this function implements the '==' operator (and so the inverse of '!=')
// from the python language reference:
// "The objects need not have the same type. If both are numbers, they are converted
// to a common type. Otherwise, the == and != operators always consider objects of
// different types to be unequal."
// note also that False==0 and True==1 are true expressions
Damien's avatar
Damien committed
240
241
242
bool py_obj_equal(py_obj_t o1, py_obj_t o2) {
    if (o1 == o2) {
        return true;
Damien's avatar
Damien committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    } else if (IS_SMALL_INT(o1) || IS_SMALL_INT(o2)) {
        if (IS_SMALL_INT(o1) && IS_SMALL_INT(o2)) {
            return false;
        } else {
            if (IS_SMALL_INT(o2)) {
                py_obj_t temp = o1; o1 = o2; o2 = temp;
            }
            // o1 is the SMALL_INT, o2 is not
            py_small_int_t val = FROM_SMALL_INT(o1);
            if (o2 == py_const_false) {
                return val == 0;
            } else if (o2 == py_const_true) {
                return val == 1;
            } else {
                return false;
            }
        }
Damien's avatar
Damien committed
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
    } 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;
Damien's avatar
Damien committed
288
                    map->table = m_new0(py_map_elem_t, map->alloc);
Damien's avatar
Damien committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
                    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
Damien's avatar
Damien committed
307
            /* it seems CPython does not replace the index; try x={True:'true'};x[1]='one';x
Damien's avatar
Damien committed
308
309
310
            if (add_if_not_found) {
                elem->key = index;
            }
Damien's avatar
Damien committed
311
            */
Damien's avatar
Damien committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
            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;
}

334
py_obj_t py_obj_new_int(machine_int_t value) {
Damien's avatar
Damien committed
335
336
337
    return TO_SMALL_INT(value);
}

Damien's avatar
Damien committed
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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;
}

352
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
353
354
355
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;
356
    o->u_flt = val;
Damien's avatar
Damien committed
357
358
359
360
    return (py_obj_t)o;
}
#endif

361
362
363
364
365
366
367
368
369
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);
370
371
372
373
374
375
376
    o->kind = O_EXCEPTION_N;
    o->u_exc_n.id = id;
    o->u_exc_n.n_args = 3;
    o->u_exc_n.args = m_new(const void*, 3);
    o->u_exc_n.args[0] = fmt;
    o->u_exc_n.args[1] = s1;
    o->u_exc_n.args[2] = s2;
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
    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;
}

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
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;
}

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
py_obj_t rt_str_join(py_obj_t self_in, py_obj_t arg) {
    assert(IS_O(self_in, O_STR));
    py_obj_base_t *self = self_in;
    int required_len = strlen(qstr_str(self->u_str));

    // process arg, count required chars
    if (!IS_O(arg, O_TUPLE) && !IS_O(arg, O_LIST)) {
        goto bad_arg;
    }
    py_obj_base_t *tuple_list = arg;
    for (int i = 0; i < tuple_list->u_tuple_list.len; i++) {
        if (!IS_O(tuple_list->u_tuple_list.items[i], O_STR)) {
            goto bad_arg;
        }
        required_len += strlen(qstr_str(((py_obj_base_t*)tuple_list->u_tuple_list.items[i])->u_str));
    }

    // make joined string
    char *joined_str = m_new(char, required_len + 1);
    joined_str[0] = 0;
    for (int i = 0; i < tuple_list->u_tuple_list.len; i++) {
        const char *s2 = qstr_str(((py_obj_base_t*)tuple_list->u_tuple_list.items[i])->u_str);
        if (i > 0) {
            strcat(joined_str, qstr_str(self->u_str));
        }
        strcat(joined_str, s2);
    }
    return py_obj_new_str(qstr_from_str_take(joined_str));

bad_arg:
    nlr_jump(py_obj_new_exception_2(q_TypeError, "?str.join expecting a list of str's", NULL, NULL));
}

448
py_obj_t rt_list_append(py_obj_t self_in, py_obj_t arg) {
Damien's avatar
Damien committed
449
450
    assert(IS_O(self_in, O_LIST));
    py_obj_base_t *self = self_in;
451
452
453
    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
454
    }
455
    self->u_tuple_list.items[self->u_tuple_list.len++] = arg;
Damien's avatar
Damien committed
456
    return py_const_none; // return None, as per CPython
Damien's avatar
Damien committed
457
458
}

459
460
461
462
463
464
465
466
467
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
468
typedef enum {
469
    PY_CODE_NONE,
Damien's avatar
Damien committed
470
    PY_CODE_BYTE,
471
472
    PY_CODE_NATIVE,
    PY_CODE_INLINE_ASM,
Damien's avatar
Damien committed
473
474
475
476
477
} py_code_kind_t;

typedef struct _py_code_t {
    py_code_kind_t kind;
    int n_args;
478
479
480
    int n_locals;
    int n_stack;
    bool is_generator;
Damien's avatar
Damien committed
481
482
483
484
485
    union {
        struct {
            byte *code;
            uint len;
        } u_byte;
486
487
488
489
        struct {
            py_fun_t fun;
        } u_native;
        struct {
490
            void *fun;
491
        } u_inline_asm;
Damien's avatar
Damien committed
492
493
494
495
496
497
    };
} py_code_t;

static int next_unique_code_id;
static py_code_t *unique_codes;

498
py_obj_t fun_str_join;
Damien's avatar
Damien committed
499
py_obj_t fun_list_append;
500
py_obj_t fun_gen_instance_next;
Damien's avatar
Damien committed
501

Damien's avatar
Damien committed
502
503
504
505
506
507
508
509
py_obj_t py_builtin___repl_print__(py_obj_t o) {
    if (o != py_const_none) {
        py_obj_print(o);
        printf("\n");
    }
    return py_const_none;
}

Damien's avatar
Damien committed
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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;
524
    if (IS_O(o_in, O_TUPLE) || IS_O(o_in, O_LIST)) {
Damien's avatar
Damien committed
525
        py_obj_base_t *o = o_in;
526
        len = o->u_tuple_list.len;
Damien's avatar
Damien committed
527
528
529
530
531
532
533
534
535
    } 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);
}

536
537
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
538
    py_map_t *old_locals = map_locals;
539
    py_map_t *class_locals = py_map_new(MAP_QSTR, 0);
540
    map_locals = class_locals;
541
542
543
544
545
546
547
548

    // 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
549
550
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_CLASS;
551
    o->u_class.locals = class_locals;
Damien's avatar
Damien committed
552
553
554
    return o;
}

555
py_obj_t py_builtin_range(py_obj_t o_arg) {
Damien's avatar
Damien committed
556
    return py_obj_new_range(0, py_get_int(o_arg), 1);
557
558
}

559
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
560
FILE *fp_native = NULL;
561
#endif
Damien's avatar
Damien committed
562

563
void rt_init(void) {
Damien's avatar
Damien committed
564
    q_append = qstr_from_str_static("append");
565
    q_join = qstr_from_str_static("join");
Damien's avatar
Damien committed
566
567
568
    q_print = qstr_from_str_static("print");
    q_len = qstr_from_str_static("len");
    q___build_class__ = qstr_from_str_static("__build_class__");
569
    q___next__ = qstr_from_str_static("__next__");
570
    q_AttributeError = qstr_from_str_static("AttributeError");
571
    q_IndexError = qstr_from_str_static("IndexError");
Damien's avatar
Damien committed
572
    q_KeyError = qstr_from_str_static("KeyError");
573
574
    q_NameError = qstr_from_str_static("NameError");
    q_TypeError = qstr_from_str_static("TypeError");
Damien's avatar
Damien committed
575
576
577
578

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

581
582
583
    // 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
584
585

    py_map_init(&map_builtins, MAP_QSTR, 3);
Damien's avatar
Damien committed
586
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("__repl_print__"), true)->value = rt_make_function_1(py_builtin___repl_print__);
Damien's avatar
Damien committed
587
588
589
    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__);
590
    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
591

Damien's avatar
Damien committed
592
    next_unique_code_id = 2; // 1 is reserved for the __main__ module scope
Damien's avatar
Damien committed
593
594
    unique_codes = NULL;

595
    fun_str_join = rt_make_function_2(rt_str_join);
596
    fun_list_append = rt_make_function_2(rt_list_append);
597
    fun_gen_instance_next = rt_make_function_1(rt_gen_instance_next);
Damien's avatar
Damien committed
598

599
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
600
    fp_native = fopen("out-native", "wb");
601
#endif
Damien's avatar
Damien committed
602
603
}

604
void rt_deinit(void) {
605
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
606
607
608
    if (fp_native != NULL) {
        fclose(fp_native);
    }
609
#endif
Damien's avatar
Damien committed
610
611
}

Damien's avatar
Damien committed
612
613
614
615
616
617
int rt_get_unique_code_id(bool is_main_module) {
    if (is_main_module) {
        return 1;
    } else {
        return next_unique_code_id++;
    }
Damien's avatar
Damien committed
618
619
}

620
static void alloc_unique_codes(void) {
Damien's avatar
Damien committed
621
    if (unique_codes == NULL) {
622
        unique_codes = m_new(py_code_t, next_unique_code_id + 10); // XXX hack until we fix the REPL allocation problem
623
624
625
        for (int i = 0; i < next_unique_code_id; i++) {
            unique_codes[i].kind = PY_CODE_NONE;
        }
Damien's avatar
Damien committed
626
    }
627
628
}

629
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) {
630
631
632
633
634
    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;
635
636
637
    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;
638
639
640
641
642
643
644
645
646
    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();

647
    assert(1 <= unique_code_id && unique_code_id < next_unique_code_id);
Damien's avatar
Damien committed
648
649
    unique_codes[unique_code_id].kind = PY_CODE_NATIVE;
    unique_codes[unique_code_id].n_args = n_args;
650
651
652
    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
653
654
    unique_codes[unique_code_id].u_native.fun = fun;

655
#ifdef DEBUG_PRINT
Damien's avatar
Damien committed
656
657
658
659
660
661
662
663
664
665
    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");

666
#ifdef WRITE_NATIVE
Damien's avatar
Damien committed
667
668
    if (fp_native != NULL) {
        fwrite(fun_data, len, 1, fp_native);
669
        fflush(fp_native);
Damien's avatar
Damien committed
670
    }
671
672
#endif
#endif
Damien's avatar
Damien committed
673
674
}

675
676
677
678
679
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
680
    unique_codes[unique_code_id].n_args = n_args;
681
682
683
    unique_codes[unique_code_id].n_locals = 0;
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
684
    unique_codes[unique_code_id].u_inline_asm.fun = fun;
Damien's avatar
Damien committed
685

686
#ifdef DEBUG_PRINT
687
688
689
690
691
692
693
694
695
696
    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");

697
#ifdef WRITE_NATIVE
698
699
700
    if (fp_native != NULL) {
        fwrite(fun_data, len, 1, fp_native);
    }
701
702
#endif
#endif
Damien's avatar
Damien committed
703
704
}

705
706
707
708
709
710
711
712
713
714
715
716
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:
717
            // what about O_CLASS, and an O_OBJ that has a __call__ method?
718
719
720
721
722
723
724
                return true;
            default:
                return false;
        }
    }
}

Damien's avatar
Damien committed
725
726
727
728
729
730
731
732
733
734
735
736
737
738
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";
739
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
740
741
742
            case O_FLOAT:
                return "float";
#endif
743
744
745
746
747
748
            case O_FUN_0:
            case O_FUN_1:
            case O_FUN_2:
            case O_FUN_N:
            case O_FUN_BC:
                return "function";
749
750
            case O_GEN_INSTANCE:
                return "generator";
751
752
            case O_TUPLE:
                return "tuple";
Damien's avatar
Damien committed
753
754
            case O_LIST:
                return "list";
755
756
757
758
            case O_TUPLE_IT:
                return "tuple_iterator";
            case O_LIST_IT:
                return "list_iterator";
Damien's avatar
Damien committed
759
760
761
762
            case O_SET:
                return "set";
            case O_MAP:
                return "dict";
763
764
765
766
767
768
769
            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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
            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;
790
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
791
            case O_FLOAT:
792
                printf("%f", o->u_flt);
Damien's avatar
Damien committed
793
794
                break;
#endif
795
796
797
            case O_EXCEPTION_0:
                printf("%s", qstr_str(o->u_exc0.id));
                break;
798
799
800
            case O_EXCEPTION_N:
                printf("%s: ", qstr_str(o->u_exc_n.id));
                printf(o->u_exc_n.args[0], o->u_exc_n.args[1], o->u_exc_n.args[2]);
801
                break;
802
803
804
            case O_GEN_INSTANCE:
                printf("<generator object 'fun-name' at %p>", o);
                break;
805
806
807
808
809
810
811
812
813
814
815
816
817
            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
818
819
            case O_LIST:
                printf("[");
820
                for (int i = 0; i < o->u_tuple_list.len; i++) {
Damien's avatar
Damien committed
821
822
823
                    if (i > 0) {
                        printf(", ");
                    }
824
                    py_obj_print(o->u_tuple_list.items[i]);
Damien's avatar
Damien committed
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
                }
                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:
863
                printf("<? %d>", o->kind);
Damien's avatar
Damien committed
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
                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;
    }
}

889
890
891
892
893
894
895
896
897
898
899
900
901
902
machine_int_t py_get_int(py_obj_t arg) {
    if (arg == py_const_false) {
        return 0;
    } else if (arg == py_const_true) {
        return 1;
    } else if (IS_SMALL_INT(arg)) {
        return FROM_SMALL_INT(arg);
    } else {
        assert(0);
        return 0;
    }
}

machine_float_t py_obj_get_float(py_obj_t arg) {
903
904
905
906
907
    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
908
        return FROM_SMALL_INT(arg);
909
910
    } else if (IS_O(arg, O_FLOAT)) {
        return ((py_obj_base_t*)arg)->u_flt;
Damien's avatar
Damien committed
911
912
913
914
915
916
    } else {
        assert(0);
        return 0;
    }
}

Damien's avatar
Damien committed
917
918
919
920
921
922
923
924
925
qstr py_get_qstr(py_obj_t arg) {
    if (IS_O(arg, O_STR)) {
        return ((py_obj_base_t*)arg)->u_str;
    } else {
        assert(0);
        return 0;
    }
}

926
py_obj_t *py_get_array_fixed_n(py_obj_t o_in, machine_int_t n) {
Damien's avatar
Damien committed
927
928
929
930
931
932
933
934
935
936
937
    if (IS_O(o_in, O_TUPLE) || IS_O(o_in, O_LIST)) {
        py_obj_base_t *o = o_in;
        if (o->u_tuple_list.len != n) {
            nlr_jump(py_obj_new_exception_2(q_IndexError, "requested length %d but object has length %d", (void*)n, (void*)o->u_tuple_list.len));
        }
        return o->u_tuple_list.items;
    } else {
        nlr_jump(py_obj_new_exception_2(q_TypeError, "object '%s' is not a tuple or list", py_obj_get_type_str(o_in), NULL));
    }
}

Damien's avatar
Damien committed
938
939
940
941
942
943
944
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
945
    DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
946
    py_map_elem_t *elem = py_qstr_map_lookup(map_locals, qstr, false);
Damien's avatar
Damien committed
947
    if (elem == NULL) {
948
        elem = py_qstr_map_lookup(map_globals, qstr, false);
Damien's avatar
Damien committed
949
        if (elem == NULL) {
950
951
            elem = py_qstr_map_lookup(&map_builtins, qstr, false);
            if (elem == NULL) {
952
                nlr_jump(py_obj_new_exception_2(q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
953
            }
Damien's avatar
Damien committed
954
955
956
957
958
959
        }
    }
    return elem->value;
}

py_obj_t rt_load_global(qstr qstr) {
960
961
    // logic: search globals, builtins
    DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
962
    py_map_elem_t *elem = py_qstr_map_lookup(map_globals, qstr, false);
963
964
965
    if (elem == NULL) {
        elem = py_qstr_map_lookup(&map_builtins, qstr, false);
        if (elem == NULL) {
966
            nlr_jump(py_obj_new_exception_2(q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
967
968
969
        }
    }
    return elem->value;
Damien's avatar
Damien committed
970
971
}

972
py_obj_t rt_load_build_class(void) {
Damien's avatar
Damien committed
973
974
975
976
977
978
979
980
981
982
    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) {
983
    DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
984
    py_qstr_map_lookup(map_locals, qstr, true)->value = obj;
985
986
987
988
}

void rt_store_global(qstr qstr, py_obj_t obj) {
    DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qstr), obj);
989
    py_qstr_map_lookup(map_globals, qstr, true)->value = obj;
Damien's avatar
Damien committed
990
991
992
993
994
995
996
}

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

997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
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
1015
1016
1017
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) {
1018
        if ((IS_O(lhs, O_TUPLE) || IS_O(lhs, O_LIST))) {
Damien's avatar
Damien committed
1019
            // tuple/list load
1020
1021
            uint index = get_index(lhs, rhs);
            return ((py_obj_base_t*)lhs)->u_tuple_list.items[index];
Damien's avatar
Damien committed
1022
1023
1024
1025
1026
1027
1028
1029
        } else if (IS_O(lhs, O_MAP)) {
            // map load
            py_map_elem_t *elem = py_map_lookup(lhs, rhs, false);
            if (elem == NULL) {
                nlr_jump(py_obj_new_exception_2(q_KeyError, "<value>", NULL, NULL));
            } else {
                return elem->value;
            }
Damien's avatar
Damien committed
1030
1031
1032
1033
        } else {
            assert(0);
        }
    } else if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
1034
1035
        py_small_int_t lhs_val = FROM_SMALL_INT(lhs);
        py_small_int_t rhs_val = FROM_SMALL_INT(rhs);
Damien's avatar
Damien committed
1036
1037
        py_small_int_t val;
        switch (op) {
1038
            case RT_BINARY_OP_OR:
1039
            case RT_BINARY_OP_INPLACE_OR: val = lhs_val | rhs_val; break;
1040
            case RT_BINARY_OP_XOR:
1041
            case RT_BINARY_OP_INPLACE_XOR: val = lhs_val ^ rhs_val; break;
1042
            case RT_BINARY_OP_AND:
1043
            case RT_BINARY_OP_INPLACE_AND: val = lhs_val & rhs_val; break;
1044
            case RT_BINARY_OP_LSHIFT:
1045
            case RT_BINARY_OP_INPLACE_LSHIFT: val = lhs_val << rhs_val; break;
1046
            case RT_BINARY_OP_RSHIFT:
1047
            case RT_BINARY_OP_INPLACE_RSHIFT: val = lhs_val >> rhs_val; break;
Damien's avatar
Damien committed
1048
            case RT_BINARY_OP_ADD:
1049
            case RT_BINARY_OP_INPLACE_ADD: val = lhs_val + rhs_val; break;
1050
            case RT_BINARY_OP_SUBTRACT:
1051
            case RT_BINARY_OP_INPLACE_SUBTRACT: val = lhs_val - rhs_val; break;
1052
            case RT_BINARY_OP_MULTIPLY:
1053
            case RT_BINARY_OP_INPLACE_MULTIPLY: val = lhs_val * rhs_val; break;
1054
            case RT_BINARY_OP_FLOOR_DIVIDE:
1055
            case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: val = lhs_val / rhs_val; break;
1056
#if MICROPY_ENABLE_FLOAT
1057
            case RT_BINARY_OP_TRUE_DIVIDE:
1058
            case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: return py_obj_new_float((float_t)lhs_val / (float_t)rhs_val);
Damien's avatar
Damien committed
1059
#endif
1060
1061
1062
1063
1064
1065
1066
            case RT_BINARY_OP_POWER:
            case RT_BINARY_OP_INPLACE_POWER:
                // TODO
                if (rhs_val == 2) {
                    val = lhs_val * lhs_val;
                    break;
                }
Damien's avatar
Damien committed
1067
1068
1069
1070
1071
            default: printf("%d\n", op); assert(0); val = 0;
        }
        if (fit_small_int(val)) {
            return TO_SMALL_INT(val);
        }
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
#if MICROPY_ENABLE_FLOAT
    } else if (IS_O(lhs, O_FLOAT) || IS_O(rhs, O_FLOAT)) {
        float_t lhs_val = py_obj_get_float(lhs);
        float_t rhs_val = py_obj_get_float(rhs);
        float_t val;
        switch (op) {
            case RT_BINARY_OP_ADD:
            case RT_BINARY_OP_INPLACE_ADD: val = lhs_val + rhs_val; break;
            case RT_BINARY_OP_SUBTRACT:
            case RT_BINARY_OP_INPLACE_SUBTRACT: val = lhs_val - rhs_val; break;
            case RT_BINARY_OP_MULTIPLY:
            case RT_BINARY_OP_INPLACE_MULTIPLY: val = lhs_val * rhs_val; break;
            /* TODO floor(?) the value
            case RT_BINARY_OP_FLOOR_DIVIDE:
            case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: val = lhs_val / rhs_val; break;
            */
            case RT_BINARY_OP_TRUE_DIVIDE:
            case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: val = lhs_val / rhs_val; break;
            default: printf("%d\n", op); assert(0); val = 0;
        }
        return py_obj_new_float(val);
#endif
Damien's avatar
Damien committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
    } 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);
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129

    // deal with == and !=
    if (op == RT_COMPARE_OP_EQUAL || op == RT_COMPARE_OP_NOT_EQUAL) {
        if (py_obj_equal(lhs, rhs)) {
            if (op == RT_COMPARE_OP_EQUAL) {
                return py_const_true;
            } else {
                return py_const_false;
            }
        } else {
            if (op == RT_COMPARE_OP_EQUAL) {
                return py_const_false;
            } else {
                return py_const_true;
            }
        }
    }

    // deal with small ints
Damien's avatar
Damien committed
1130
    if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
        py_small_int_t lhs_val = FROM_SMALL_INT(lhs);
        py_small_int_t rhs_val = FROM_SMALL_INT(rhs);
        int cmp;
        switch (op) {
            case RT_COMPARE_OP_LESS: cmp = lhs_val < rhs_val; break;
            case RT_COMPARE_OP_MORE: cmp = lhs_val > rhs_val; break;
            case RT_COMPARE_OP_LESS_EQUAL: cmp = lhs_val <= rhs_val; break;
            case RT_COMPARE_OP_MORE_EQUAL: cmp = lhs_val >= rhs_val; break;
            default: assert(0); cmp = 0;
        }
        if (cmp) {
            return py_const_true;
        } else {
            return py_const_false;
        }
    }

#if MICROPY_ENABLE_FLOAT
    // deal with floats
    if (IS_O(lhs, O_FLOAT) || IS_O(rhs, O_FLOAT)) {
        float_t lhs_val = py_obj_get_float(lhs);
        float_t rhs_val = py_obj_get_float(rhs);
Damien's avatar
Damien committed
1153
1154
        int cmp;
        switch (op) {
1155
1156
1157
1158
            case RT_COMPARE_OP_LESS: cmp = lhs_val < rhs_val; break;
            case RT_COMPARE_OP_MORE: cmp = lhs_val > rhs_val; break;
            case RT_COMPARE_OP_LESS_EQUAL: cmp = lhs_val <= rhs_val; break;
            case RT_COMPARE_OP_MORE_EQUAL: cmp = lhs_val >= rhs_val; break;
Damien's avatar
Damien committed
1159
1160
1161
1162
1163
1164
1165
1166
            default: assert(0); cmp = 0;
        }
        if (cmp) {
            return py_const_true;
        } else {
            return py_const_false;
        }
    }
1167
#endif
1168
1169

    // not implemented
Damien's avatar
Damien committed
1170
1171
1172
1173
1174
    assert(0);
    return py_const_none;
}

py_obj_t rt_make_function_from_id(int unique_code_id) {
1175
1176
    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
1177
1178
1179
1180
1181
1182
        // 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) {
1183
1184
1185
1186
1187
1188
        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
1189
1190
1191
1192
1193
1194
1195
1196
1197
        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;
1198
1199
1200
1201
        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
1202
1203
1204
1205
            break;
        default:
            assert(0);
    }
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216

    // 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
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
    return o;
}

py_obj_t rt_make_function_0(py_fun_0_t fun) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_FUN_0;
    o->u_fun.fun = fun;
    return o;
}

py_obj_t rt_make_function_1(py_fun_1_t fun) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_FUN_1;
    o->u_fun.fun = fun;
    return o;
}

py_obj_t rt_make_function_2(py_fun_2_t fun) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_FUN_2;
    o->u_fun.fun = fun;
    return o;
}

py_obj_t rt_make_function(int n_args, py_fun_t code) {
    // assumes code is a pointer to a py_fun_t (i think this is safe...)
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_FUN_N;
    o->u_fun.n_args = n_args;
1246
    o->u_fun.fun = code;
Damien's avatar
Damien committed
1247
1248
1249
    return o;
}

1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
py_obj_t rt_call_function_0(py_obj_t fun) {
    return rt_call_function_n(fun, 0, NULL);
}

py_obj_t rt_call_function_1(py_obj_t fun, py_obj_t arg) {
    return rt_call_function_n(fun, 1, &arg);
}

py_obj_t rt_call_function_2(py_obj_t fun, py_obj_t arg1, py_obj_t arg2) {
    py_obj_t args[2];
    args[1] = arg1;
    args[0] = arg2;
    return rt_call_function_n(fun, 2, args);
}

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);

1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
// convert a Python object to a sensible value for inline asm
machine_uint_t rt_convert_obj_for_inline_asm(py_obj_t obj) {
    // TODO for byte_array, pass pointer to the array
    if (IS_SMALL_INT(obj)) {
        return FROM_SMALL_INT(obj);
    } else if (obj == py_const_none) {
        return 0;
    } else if (obj == py_const_false) {
        return 0;
    } else if (obj == py_const_true) {
        return 1;
    } else {
        py_obj_base_t *o = obj;
        switch (o->kind) {
            case O_STR:
                // pointer to the string (it's probably constant though!)
                return (machine_uint_t)qstr_str(o->u_str);

1288
#if MICROPY_ENABLE_FLOAT
1289
1290
1291
            case O_FLOAT:
                // convert float to int (could also pass in float registers)
                return (machine_int_t)o->u_flt;
1292
#endif
1293

1294
            case O_TUPLE:
1295
            case O_LIST:
1296
1297
                // pointer to start of tuple/list (could pass length, but then could use len(x) for that)
                return (machine_uint_t)o->u_tuple_list.items;
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310

            default:
                // just pass along a pointer to the object
                return (machine_uint_t)obj;
        }
    }
}

// convert a return value from inline asm to a sensible Python object
py_obj_t rt_convert_val_from_inline_asm(machine_uint_t val) {
    return TO_SMALL_INT(val);
}

1311
1312
1313
// args are in reverse order in the array
py_obj_t rt_call_function_n(py_obj_t fun, int n_args, const py_obj_t *args) {
    int n_args_fun = 0;
Damien's avatar
Damien committed
1314
1315
    if (IS_O(fun, O_FUN_0)) {
        py_obj_base_t *o = fun;
1316
1317
1318
1319
1320
        if (n_args != 0) {
            n_args_fun = 0;
            goto bad_n_args;
        }
        DEBUG_OP_printf("calling native %p()\n", o->u_fun.fun);
Damien's avatar
Damien committed
1321
        return ((py_fun_0_t)o->u_fun.fun)();
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342

    } else if (IS_O(fun, O_FUN_1)) {
        py_obj_base_t *o = fun;
        if (n_args != 1) {
            n_args_fun = 1;
            goto bad_n_args;
        }
        DEBUG_OP_printf("calling native %p(%p)\n", o->u_fun.fun, args[0]);
        return ((py_fun_1_t)o->u_fun.fun)(args[0]);

    } else if (IS_O(fun, O_FUN_2)) {
        py_obj_base_t *o = fun;
        if (n_args != 2) {
            n_args_fun = 2;
            goto bad_n_args;
        }
        DEBUG_OP_printf("calling native %p(%p, %p)\n", o->u_fun.fun, args[1], args[0]);
        return ((py_fun_2_t)o->u_fun.fun)(args[1], args[0]);

    // TODO O_FUN_N

Damien's avatar
Damien committed
1343
1344
    } else if (IS_O(fun, O_FUN_BC)) {
        py_obj_base_t *o = fun;
1345
1346
1347
1348
1349
        if (n_args != o->u_fun_bc.n_args) {
            n_args_fun = o->u_fun_bc.n_args;
            goto bad_n_args;
        }
        DEBUG_OP_printf("calling byte code %p(n_args=%d)\n", o->u_fun_bc.code, n_args);
1350
        return py_execute_byte_code(o->u_fun_bc.code, args, n_args);
1351

1352
1353
    } else if (IS_O(fun, O_FUN_ASM)) {
        py_obj_base_t *o = fun;
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
        if (n_args != o->u_fun_asm.n_args) {
            n_args_fun = o->u_fun_asm.n_args;
            goto bad_n_args;
        }
        DEBUG_OP_printf("calling inline asm %p(n_args=%d)\n", o->u_fun_asm.fun, n_args);
        machine_uint_t ret;
        if (n_args == 0) {
            ret = ((inline_asm_fun_0_t)o->u_fun_asm.fun)();
        } else if (n_args == 1) {
            ret = ((inline_asm_fun_1_t)o->u_fun_asm.fun)(rt_convert_obj_for_inline_asm(args[0]));
        } else if (n_args == 2) {
            ret = ((inline_asm_fun_2_t)o->u_fun_asm.fun)(rt_convert_obj_for_inline_asm(args[1]), rt_convert_obj_for_inline_asm(args[0]));
        } else if (n_args == 3) {
            ret = ((inline_asm_fun_3_t)o->u_fun_asm.fun)(rt_convert_obj_for_inline_asm(args[2]), rt_convert_obj_for_inline_asm(args[1]), rt_convert_obj_for_inline_asm(args[0]));
        } else {
            assert(0);
            ret = 0;
        }
        return rt_convert_val_from_inline_asm(ret);

1374
1375
1376
1377
1378
1379
1380
1381
1382