runtime.c 76.5 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
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
8
#include <stdarg.h>
Damien's avatar
Damien committed
9
10
11
#include <string.h>
#include <assert.h>

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

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

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

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

typedef enum {
    O_CONST,
    O_STR,
42
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
43
    O_FLOAT,
Damien's avatar
Damien committed
44
    O_COMPLEX,
Damien's avatar
Damien committed
45
#endif
Damien's avatar
Damien committed
46
    O_CELL,
47
    O_EXCEPTION_0,
48
    O_EXCEPTION_N,
49
50
    O_RANGE,
    O_RANGE_IT,
Damien's avatar
Damien committed
51
52
53
54
    O_FUN_0,
    O_FUN_1,
    O_FUN_2,
    O_FUN_N,
55
    O_FUN_VAR,
Damien's avatar
Damien committed
56
    O_FUN_BC,
57
    O_FUN_ASM,
58
59
    O_GEN_WRAP,
    O_GEN_INSTANCE,
Damien's avatar
Damien committed
60
    O_BOUND_METH,
Damien's avatar
Damien committed
61
    O_CLOSURE,
62
    O_TUPLE,
Damien's avatar
Damien committed
63
    O_LIST,
64
65
    O_TUPLE_IT,
    O_LIST_IT,
Damien's avatar
Damien committed
66
67
68
    O_SET,
    O_MAP,
    O_CLASS,
69
    O_OBJ,
Damien's avatar
Damien committed
70
    O_USER,
Damien's avatar
Damien committed
71
72
73
74
75
76
77
78
79
80
81
82
83
} 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 {
84
85
86
87
    struct {
        py_map_kind_t kind : 1;
        machine_uint_t used : (8 * BYTES_PER_WORD - 1);
    };
Damien's avatar
Damien committed
88
89
90
91
    machine_uint_t alloc;
    py_map_elem_t *table;
} py_map_t;

92
93
94
typedef struct _py_obj_base_t py_obj_base_t;

struct _py_obj_base_t {
Damien's avatar
Damien committed
95
96
97
98
    py_obj_kind_t kind;
    union {
        const char *id;
        qstr u_str;
99
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
100
101
102
103
104
        py_float_t u_float; // for O_FLOAT
        struct { // for O_COMPLEX
            py_float_t real;
            py_float_t imag;
        } u_complex;
Damien's avatar
Damien committed
105
#endif
Damien's avatar
Damien committed
106
        py_obj_t u_cell; // for O_CELL
107
108
109
        struct { // for O_EXCEPTION_0
            qstr id;
        } u_exc0;
110
111
        struct { // for O_EXCEPTION_N
            // TODO make generic object or something
112
            qstr id;
113
114
115
            int n_args;
            const void **args;
        } u_exc_n;
116
117
118
119
120
121
122
123
124
125
126
127
        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;
128
        struct { // for O_FUN_[012N], O_FUN_VAR
Damien's avatar
Damien committed
129
            int n_args;
130
            void *fun;
Damien's avatar
Damien committed
131
132
        } u_fun;
        struct { // for O_FUN_BC
133
            int n_args;
134
            uint n_state;
Damien's avatar
Damien committed
135
136
            byte *code;
        } u_fun_bc;
137
138
139
140
        struct { // for O_FUN_ASM
            int n_args;
            void *fun;
        } u_fun_asm;
141
142
143
144
145
146
147
148
149
        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
150
151
152
153
        struct { // for O_BOUND_METH
            py_obj_t meth;
            py_obj_t self;
        } u_bound_meth;
Damien's avatar
Damien committed
154
155
156
157
        struct { // for O_CLOSURE
            py_obj_t fun;
            py_obj_t vars;
        } u_closure;
158
        struct { // for O_TUPLE, O_LIST
159
160
            machine_uint_t alloc;
            machine_uint_t len;
Damien's avatar
Damien committed
161
            py_obj_t *items;
162
163
164
        } u_tuple_list;
        struct { // for O_TUPLE_IT, O_LIST_IT
            py_obj_base_t *obj;
165
            machine_uint_t cur;
166
        } u_tuple_list_it;
Damien's avatar
Damien committed
167
        struct { // for O_SET
168
169
            machine_uint_t alloc;
            machine_uint_t used;
Damien's avatar
Damien committed
170
171
172
173
            py_obj_t *table;
        } u_set;
        py_map_t u_map; // for O_MAP
        struct { // for O_CLASS
174
            py_map_t *locals;
Damien's avatar
Damien committed
175
        } u_class;
176
177
178
179
        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
180
181
182
183
184
        struct { // for O_USER
            const py_user_info_t *info;
            machine_uint_t data1;
            machine_uint_t data2;
        } u_user;
Damien's avatar
Damien committed
185
    };
186
};
Damien's avatar
Damien committed
187

188
static qstr q_append;
189
190
static qstr q_pop;
static qstr q_sort;
191
static qstr q_join;
192
static qstr q_format;
193
194
195
196
197
198
199
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
200
static qstr q_SyntaxError;
201
static qstr q_ValueError;
202

Damien's avatar
Damien committed
203
204
205
py_obj_t py_const_none;
py_obj_t py_const_false;
py_obj_t py_const_true;
206
py_obj_t py_const_stop_iteration;
Damien's avatar
Damien committed
207

208
// locals and globals need to be pointers because they can be the same in outer module scope
209
210
211
static py_map_t *map_locals;
static py_map_t *map_globals;
static py_map_t map_builtins;
Damien's avatar
Damien committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

// 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;
230
    map->alloc = get_doubling_prime_greater_or_equal_to(n + 1);
Damien's avatar
Damien committed
231
    map->table = m_new0(py_map_elem_t, map->alloc);
Damien's avatar
Damien committed
232
233
234
235
236
237
238
239
}

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
240
241
242
243
244
245
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
246
        return FROM_SMALL_INT(o_in);
Damien's avatar
Damien committed
247
248
    } else if (IS_O(o_in, O_CONST)) {
        return (machine_int_t)o_in;
Damien's avatar
Damien committed
249
250
251
252
253
254
255
256
    } 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
257
258
259
260
261
262
// 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
263
264
265
bool py_obj_equal(py_obj_t o1, py_obj_t o2) {
    if (o1 == o2) {
        return true;
Damien's avatar
Damien committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    } 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
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
310
    } 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
311
                    map->table = m_new0(py_map_elem_t, map->alloc);
Damien's avatar
Damien committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
                    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
330
            /* it seems CPython does not replace the index; try x={True:'true'};x[1]='one';x
Damien's avatar
Damien committed
331
332
333
            if (add_if_not_found) {
                elem->key = index;
            }
Damien's avatar
Damien committed
334
            */
Damien's avatar
Damien committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
            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;
}

357
py_obj_t py_obj_new_int(machine_int_t value) {
Damien's avatar
Damien committed
358
359
360
    return TO_SMALL_INT(value);
}

Damien's avatar
Damien committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
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;
}

375
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
376
py_obj_t py_obj_new_float(py_float_t val) {
Damien's avatar
Damien committed
377
378
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_FLOAT;
Damien's avatar
Damien committed
379
380
381
382
383
384
385
386
387
    o->u_float = val;
    return (py_obj_t)o;
}

py_obj_t py_obj_new_complex(py_float_t real, py_float_t imag) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_COMPLEX;
    o->u_complex.real = real;
    o->u_complex.imag = imag;
Damien's avatar
Damien committed
388
389
390
391
    return (py_obj_t)o;
}
#endif

Damien's avatar
Damien committed
392
393
394
395
396
397
398
py_obj_t py_obj_new_cell(py_obj_t val) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_CELL;
    o->u_cell = val;
    return (py_obj_t)o;
}

399
400
401
402
403
404
405
406
407
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);
408
409
410
411
412
413
414
    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;
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
    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;
}

437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
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;
}

Damien's avatar
Damien committed
453
454
455
456
457
458
459
460
461
462
463
464
py_obj_t py_obj_new_user(const py_user_info_t *info, machine_uint_t data1, machine_uint_t data2) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_USER;
    // TODO should probably parse the info to turn strings to qstr's, and wrap functions in O_FUN_N objects
    // that'll take up some memory.  maybe we can lazily do the O_FUN_N: leave it a ptr to a C function, and
    // only when the method is looked-up do we change that to the O_FUN_N object.
    o->u_user.info = info;
    o->u_user.data1 = data1;
    o->u_user.data2 = data2;
    return o;
}

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
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";
#if MICROPY_ENABLE_FLOAT
            case O_FLOAT:
                return "float";
#endif
            case O_FUN_0:
            case O_FUN_1:
            case O_FUN_2:
            case O_FUN_N:
487
            case O_FUN_VAR:
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
            case O_FUN_BC:
                return "function";
            case O_GEN_INSTANCE:
                return "generator";
            case O_TUPLE:
                return "tuple";
            case O_LIST:
                return "list";
            case O_TUPLE_IT:
                return "tuple_iterator";
            case O_LIST_IT:
                return "list_iterator";
            case O_SET:
                return "set";
            case O_MAP:
                return "dict";
            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);
            }
            case O_USER:
                return o->u_user.info->type_name;
            default:
                assert(0);
                return "UnknownType";
        }
    }
}

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

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

#if MICROPY_ENABLE_FLOAT
machine_float_t py_obj_get_float(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 if (IS_O(arg, O_FLOAT)) {
        return ((py_obj_base_t*)arg)->u_float;
    } else {
        assert(0);
        return 0;
    }
}

void py_obj_get_complex(py_obj_t arg, py_float_t *real, py_float_t *imag) {
    if (arg == py_const_false) {
        *real = 0;
        *imag = 0;
    } else if (arg == py_const_true) {
        *real = 1;
        *imag = 0;
    } else if (IS_SMALL_INT(arg)) {
        *real = FROM_SMALL_INT(arg);
        *imag = 0;
    } else if (IS_O(arg, O_FLOAT)) {
        *real = ((py_obj_base_t*)arg)->u_float;
        *imag = 0;
    } else if (IS_O(arg, O_COMPLEX)) {
        *real = ((py_obj_base_t*)arg)->u_complex.real;
        *imag = ((py_obj_base_t*)arg)->u_complex.imag;
    } else {
        assert(0);
        *real = 0;
        *imag = 0;
    }
}
#endif

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

Damien's avatar
Damien committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
py_obj_t py_obj_get_cell(py_obj_t cell) {
    if (IS_O(cell, O_CELL)) {
        return ((py_obj_base_t*)cell)->u_cell;
    } else {
        assert(0);
        return py_const_none;
    }
}

void py_obj_set_cell(py_obj_t cell, py_obj_t val) {
    if (IS_O(cell, O_CELL)) {
        ((py_obj_base_t*)cell)->u_cell = val;
    } else {
        assert(0);
    }
}

619
620
621
622
623
624
625
626
627
628
629
630
py_obj_t *py_obj_get_array_fixed_n(py_obj_t o_in, machine_int_t n) {
    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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
void py_user_get_data(py_obj_t o, machine_uint_t *data1, machine_uint_t *data2) {
    assert(IS_O(o, O_USER));
    if (data1 != NULL) {
        *data1 = ((py_obj_base_t*)o)->u_user.data1;
    }
    if (data2 != NULL) {
        *data2 = ((py_obj_base_t*)o)->u_user.data2;
    }
}

void py_user_set_data(py_obj_t o, machine_uint_t data1, machine_uint_t data2) {
    assert(IS_O(o, O_USER));
    ((py_obj_base_t*)o)->u_user.data1 = data1;
    ((py_obj_base_t*)o)->u_user.data2 = data2;
}

647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
void printf_wrapper(void *env, const char *fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
}

void vstr_printf_wrapper(void *env, const char *fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vstr_vprintf(env, fmt, args);
    va_end(args);
}

void py_obj_print_helper(void (*print)(void *env, const char *fmt, ...), void *env, py_obj_t o_in) {
    if (IS_SMALL_INT(o_in)) {
        print(env, "%d", (int)FROM_SMALL_INT(o_in));
    } else {
        py_obj_base_t *o = o_in;
        switch (o->kind) {
            case O_CONST:
                print(env, "%s", o->id);
                break;
            case O_STR:
                // TODO need to escape chars etc
                print(env, "'%s'", qstr_str(o->u_str));
                break;
#if MICROPY_ENABLE_FLOAT
            case O_FLOAT:
                print(env, "%.8g", o->u_float);
                break;
            case O_COMPLEX:
                if (o->u_complex.real == 0) {
                    print(env, "%.8gj", o->u_complex.imag);
                } else {
                    print(env, "(%.8g+%.8gj)", o->u_complex.real, o->u_complex.imag);
                }
                break;
#endif
            case O_EXCEPTION_0:
                print(env, "%s", qstr_str(o->u_exc0.id));
                break;
            case O_EXCEPTION_N:
                print(env, "%s: ", qstr_str(o->u_exc_n.id));
                print(env, o->u_exc_n.args[0], o->u_exc_n.args[1], o->u_exc_n.args[2]);
                break;
            case O_GEN_INSTANCE:
                print(env, "<generator object 'fun-name' at %p>", o);
                break;
            case O_TUPLE:
                print(env, "(");
                for (int i = 0; i < o->u_tuple_list.len; i++) {
                    if (i > 0) {
                        print(env, ", ");
                    }
                    py_obj_print_helper(print, env, o->u_tuple_list.items[i]);
                }
                if (o->u_tuple_list.len == 1) {
                    print(env, ",");
                }
                print(env, ")");
                break;
            case O_LIST:
                print(env, "[");
                for (int i = 0; i < o->u_tuple_list.len; i++) {
                    if (i > 0) {
                        print(env, ", ");
                    }
                    py_obj_print_helper(print, env, o->u_tuple_list.items[i]);
                }
                print(env, "]");
                break;
            case O_SET:
            {
                bool first = true;
                print(env, "{");
                for (int i = 0; i < o->u_set.alloc; i++) {
                    if (o->u_set.table[i] != NULL) {
                        if (!first) {
                            print(env, ", ");
                        }
                        first = false;
                        py_obj_print_helper(print, env, o->u_set.table[i]);
                    }
                }
                print(env, "}");
                break;
            }
            case O_MAP:
            {
                bool first = true;
                print(env, "{");
                for (int i = 0; i < o->u_map.alloc; i++) {
                    if (o->u_map.table[i].key != NULL) {
                        if (!first) {
                            print(env, ", ");
                        }
                        first = false;
                        py_obj_print_helper(print, env, o->u_map.table[i].key);
                        print(env, ": ");
                        py_obj_print_helper(print, env, o->u_map.table[i].value);
                    }
                }
                print(env, "}");
                break;
            }
            case O_USER:
                o->u_user.info->print(o_in);
                break;
            default:
                print(env, "<? %d>", o->kind);
                assert(0);
        }
    }
}

763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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));
}

796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
py_obj_t rt_str_format(int n_args, const py_obj_t* args) {
    assert(IS_O(args[0], O_STR));
    py_obj_base_t *self = args[0];

    const char *str = qstr_str(self->u_str);
    int arg_i = 1;
    vstr_t *vstr = vstr_new();
    for (; *str; str++) {
        if (*str == '{') {
            str++;
            if (*str == '{') {
                vstr_add_char(vstr, '{');
            } else if (*str == '}') {
                if (arg_i >= n_args) {
                    nlr_jump(py_obj_new_exception_2(q_IndexError, "tuple index out of range", NULL, NULL));
                }
                py_obj_print_helper(vstr_printf_wrapper, vstr, args[arg_i]);
                arg_i++;
            }
        } else {
            vstr_add_char(vstr, *str);
        }
    }

    return py_obj_new_str(qstr_from_str_take(vstr->buf));
}

823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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)));
    }
}

841
py_obj_t rt_list_append(py_obj_t self_in, py_obj_t arg) {
Damien's avatar
Damien committed
842
843
    assert(IS_O(self_in, O_LIST));
    py_obj_base_t *self = self_in;
844
845
846
    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
847
    }
848
    self->u_tuple_list.items[self->u_tuple_list.len++] = arg;
Damien's avatar
Damien committed
849
    return py_const_none; // return None, as per CPython
Damien's avatar
Damien committed
850
851
}

852
853
854
855
856
857
858
859
860
861
862
863
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
889
890
891
892
py_obj_t rt_list_pop(py_obj_t self_in, py_obj_t arg) {
    assert(IS_O(self_in, O_LIST));
    py_obj_base_t *self = self_in;
    uint index = get_index(self, arg);
    py_obj_t ret = self->u_tuple_list.items[index];
    self->u_tuple_list.len -= 1;
    memcpy(self->u_tuple_list.items + index, self->u_tuple_list.items + index + 1, (self->u_tuple_list.len - index) * sizeof(py_obj_t));
    return ret;
}

// TODO make this conform to CPython's definition of sort
static void py_quicksort(py_obj_t *head, py_obj_t *tail, py_obj_t key_fn) {
    while (head < tail) {
        py_obj_t *h = head - 1;
        py_obj_t *t = tail;
        py_obj_t v = rt_call_function_1(key_fn, tail[0]); // get pivot using key_fn
        for (;;) {
            do ++h; while (rt_compare_op(RT_COMPARE_OP_LESS, rt_call_function_1(key_fn, h[0]), v) == py_const_true);
            do --t; while (h < t && rt_compare_op(RT_COMPARE_OP_LESS, v, rt_call_function_1(key_fn, t[0])) == py_const_true);
            if (h >= t) break;
            py_obj_t x = h[0];
            h[0] = t[0];
            t[0] = x;
        }
        py_obj_t x = h[0];
        h[0] = tail[0];
        tail[0] = x;
        py_quicksort(head, t, key_fn);
        head = h + 1;
    }
}

py_obj_t rt_list_sort(py_obj_t self_in, py_obj_t key_fn) {
    assert(IS_O(self_in, O_LIST));
    py_obj_base_t *self = self_in;
    if (self->u_tuple_list.len > 1) {
        py_quicksort(self->u_tuple_list.items, self->u_tuple_list.items + self->u_tuple_list.len - 1, key_fn);
    }
    return py_const_none; // return None, as per CPython
}

893
894
895
896
897
898
899
900
901
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
902
typedef enum {
903
    PY_CODE_NONE,
Damien's avatar
Damien committed
904
    PY_CODE_BYTE,
905
906
    PY_CODE_NATIVE,
    PY_CODE_INLINE_ASM,
Damien's avatar
Damien committed
907
908
909
910
911
} py_code_kind_t;

typedef struct _py_code_t {
    py_code_kind_t kind;
    int n_args;
912
    int n_locals;
Damien's avatar
Damien committed
913
    int n_cells;
914
915
    int n_stack;
    bool is_generator;
Damien's avatar
Damien committed
916
917
918
919
920
    union {
        struct {
            byte *code;
            uint len;
        } u_byte;
921
922
923
924
        struct {
            py_fun_t fun;
        } u_native;
        struct {
925
            void *fun;
926
        } u_inline_asm;
Damien's avatar
Damien committed
927
928
929
930
931
932
    };
} py_code_t;

static int next_unique_code_id;
static py_code_t *unique_codes;

933
py_obj_t fun_str_join;
934
py_obj_t fun_str_format;
Damien's avatar
Damien committed
935
py_obj_t fun_list_append;
936
937
py_obj_t fun_list_pop;
py_obj_t fun_list_sort;
938
py_obj_t fun_gen_instance_next;
Damien's avatar
Damien committed
939

Damien's avatar
Damien committed
940
941
942
943
944
945
946
947
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;
}

948
949
950
951
952
953
954
955
956
957
958
959
py_obj_t py_builtin_print(int n_args, const py_obj_t* args) {
    for (int i = 0; i < n_args; i++) {
        if (i > 0) {
            printf(" ");
        }
        if (IS_O(args[i], O_STR)) {
            // special case, print string raw
            printf("%s", qstr_str(((py_obj_base_t*)args[i])->u_str));
        } else {
            // print the object Python style
            py_obj_print(args[i]);
        }
Damien's avatar
Damien committed
960
    }
961
    printf("\n");
Damien's avatar
Damien committed
962
963
964
965
966
    return py_const_none;
}

py_obj_t py_builtin_len(py_obj_t o_in) {
    py_small_int_t len = 0;
967
968
969
970
    if (IS_O(o_in, O_STR)) {
        py_obj_base_t *o = o_in;
        len = strlen(qstr_str(o->u_str));
    } else if (IS_O(o_in, O_TUPLE) || IS_O(o_in, O_LIST)) {
Damien's avatar
Damien committed
971
        py_obj_base_t *o = o_in;
972
        len = o->u_tuple_list.len;
Damien's avatar
Damien committed
973
974
975
976
977
978
979
980
981
    } 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);
}

Damien's avatar
Damien committed
982
983
984
985
986
987
988
py_obj_t py_builtin_abs(py_obj_t o_in) {
    if (IS_SMALL_INT(o_in)) {
        py_small_int_t val = FROM_SMALL_INT(o_in);
        if (val < 0) {
            val = -val;
        }
        return TO_SMALL_INT(val);
989
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
990
991
992
993
994
995
996
997
998
999
    } else if (IS_O(o_in, O_FLOAT)) {
        py_obj_base_t *o = o_in;
        // TODO check for NaN etc
        if (o->u_float < 0) {
            return py_obj_new_float(-o->u_float);
        } else {
            return o_in;
        }
    } else if (IS_O(o_in, O_COMPLEX)) {
        py_obj_base_t *o = o_in;
1000
1001
        return py_obj_new_float(machine_sqrt(o->u_complex.real*o->u_complex.real + o->u_complex.imag*o->u_complex.imag));
#endif
Damien's avatar
Damien committed
1002
1003
1004
1005
1006
1007
    } else {
        assert(0);
        return py_const_none;
    }
}

1008
1009
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
1010
    py_map_t *old_locals = map_locals;
1011
    py_map_t *class_locals = py_map_new(MAP_QSTR, 0);
1012
    map_locals = class_locals;
1013
1014
1015
1016
1017
1018
1019
1020

    // 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
1021
1022
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_CLASS;
1023
    o->u_class.locals = class_locals;
Damien's avatar
Damien committed
1024
1025
1026
    return o;
}

1027
1028
1029
1030
1031
1032
1033
py_obj_t py_builtin_range(int n_args, const py_obj_t* args) {
    switch (n_args) {
        case 1: return py_obj_new_range(0, py_obj_get_int(args[0]), 1);
        case 2: return py_obj_new_range(py_obj_get_int(args[0]), py_obj_get_int(args[1]), 1);
        case 3: return py_obj_new_range(py_obj_get_int(args[0]), py_obj_get_int(args[1]), py_obj_get_int(args[2]));
        default: nlr_jump(py_obj_new_exception_2(q_TypeError, "range expected at most 3 arguments, got %d", (void*)(machine_int_t)n_args, NULL));
    }
1034
1035
}

1036
1037
#ifdef WRITE_CODE
FILE *fp_write_code = NULL;
1038
#endif
Damien's avatar
Damien committed
1039

1040
void rt_init(void) {
Damien's avatar
Damien committed
1041
    q_append = qstr_from_str_static("append");
1042
1043
    q_pop = qstr_from_str_static("pop");
    q_sort = qstr_from_str_static("sort");
1044
    q_join = qstr_from_str_static("join");
1045
    q_format = qstr_from_str_static("format");
Damien's avatar
Damien committed
1046
    q___build_class__ = qstr_from_str_static("__build_class__");
1047
    q___next__ = qstr_from_str_static("__next__");
1048
    q_AttributeError = qstr_from_str_static("AttributeError");
1049
    q_IndexError = qstr_from_str_static("IndexError");
Damien's avatar
Damien committed
1050
    q_KeyError = qstr_from_str_static("KeyError");
1051
1052
    q_NameError = qstr_from_str_static("NameError");
    q_TypeError = qstr_from_str_static("TypeError");
Damien's avatar
Damien committed
1053
    q_SyntaxError = qstr_from_str_static("SyntaxError");
1054
    q_ValueError = qstr_from_str_static("ValueError");
Damien's avatar
Damien committed
1055
1056
1057
1058

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

1061
1062
1063
    // 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
1064
1065

    py_map_init(&map_builtins, MAP_QSTR, 3);
Damien's avatar
Damien committed
1066
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("__repl_print__"), true)->value = rt_make_function_1(py_builtin___repl_print__);
1067
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("print"), true)->value = rt_make_function_var(0, py_builtin_print);
1068
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("len"), true)->value = rt_make_function_1(py_builtin_len);
Damien's avatar
Damien committed
1069
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("abs"), true)->value = rt_make_function_1(py_builtin_abs);
Damien's avatar
Damien committed
1070
    py_qstr_map_lookup(&map_builtins, q___build_class__, true)->value = rt_make_function_2(py_builtin___build_class__);
1071
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("range"), true)->value = rt_make_function_var(1, py_builtin_range);
Damien's avatar
Damien committed
1072

Damien's avatar
Damien committed
1073
    next_unique_code_id = 2; // 1 is reserved for the __main__ module scope
Damien's avatar
Damien committed
1074
1075
    unique_codes = NULL;

1076
    fun_str_join = rt_make_function_2(rt_str_join);
1077
    fun_str_format = rt_make_function_var(1, rt_str_format);
1078
    fun_list_append = rt_make_function_2(rt_list_append);
1079
1080
    fun_list_pop = rt_make_function_2(rt_list_pop);
    fun_list_sort = rt_make_function_2(rt_list_sort);
1081
    fun_gen_instance_next = rt_make_function_1(rt_gen_instance_next);
Damien's avatar
Damien committed
1082

1083
1084
#ifdef WRITE_CODE
    fp_write_code = fopen("out-code", "wb");
1085
#endif
Damien's avatar
Damien committed
1086
1087
}

1088
void rt_deinit(void) {
1089
1090
1091
#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fclose(fp_write_code);
Damien's avatar
Damien committed
1092
    }
1093
#endif
Damien's avatar
Damien committed
1094
1095
}

Damien's avatar
Damien committed
1096
1097
1098
1099
1100
1101
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
1102
1103
}

1104
static void alloc_unique_codes(void) {
Damien's avatar
Damien committed
1105
    if (unique_codes == NULL) {
1106
        unique_codes = m_new(py_code_t, next_unique_code_id + 10); // XXX hack until we fix the REPL allocation problem
1107
1108
1109
        for (int i = 0; i < next_unique_code_id; i++) {
            unique_codes[i].kind = PY_CODE_NONE;
        }
Damien's avatar
Damien committed
1110
    }
1111
1112
}

Damien's avatar
Damien committed
1113
void rt_assign_byte_code(int unique_code_id, byte *code, uint len, int n_args, int n_locals, int n_cells, int n_stack, bool is_generator) {
1114
1115
1116
1117
1118
    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;
1119
    unique_codes[unique_code_id].n_locals = n_locals;
Damien's avatar
Damien committed
1120
    unique_codes[unique_code_id].n_cells = n_cells;
1121
1122
    unique_codes[unique_code_id].n_stack = n_stack;
    unique_codes[unique_code_id].is_generator = is_generator;
1123
1124
1125
    unique_codes[unique_code_id].u_byte.code = code;
    unique_codes[unique_code_id].u_byte.len = len;

Damien's avatar
Damien committed
1126
    //printf("byte code: %d bytes\n", len);
1127
1128

#ifdef DEBUG_PRINT
1129
    DEBUG_printf("assign byte code: id=%d code=%p len=%u n_args=%d\n", unique_code_id, code, len, n_args);
1130
1131
1132
1133
1134
1135
1136
    for (int i = 0; i < 128 && i < len; i++) {
        if (i > 0 && i % 16 == 0) {
            DEBUG_printf("\n");
        }
        DEBUG_printf(" %02x", code[i]);
    }
    DEBUG_printf("\n");
1137
1138
    extern void py_show_byte_code(const byte *code, int len);
    py_show_byte_code(code, len);
1139
1140
1141
1142
1143
1144
1145
1146

#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fwrite(code, len, 1, fp_write_code);
        fflush(fp_write_code);
    }
#endif
#endif
1147
1148
1149
1150
1151
}

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

1152
    assert(1 <= unique_code_id && unique_code_id < next_unique_code_id);
Damien's avatar
Damien committed
1153
1154
    unique_codes[unique_code_id].kind = PY_CODE_NATIVE;
    unique_codes[unique_code_id].n_args = n_args;
1155
    unique_codes[unique_code_id].n_locals = 0;
Damien's avatar
Damien committed
1156
    unique_codes[unique_code_id].n_cells = 0;
1157
1158
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
Damien's avatar
Damien committed
1159
1160
    unique_codes[unique_code_id].u_native.fun = fun;

1161
1162
    printf("native code: %d bytes\n", len);

1163
#ifdef DEBUG_PRINT
Damien's avatar
Damien committed
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
    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");

1174
1175
1176
1177
#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fwrite(fun_data, len, 1, fp_write_code);
        fflush(fp_write_code);
Damien's avatar
Damien committed
1178
    }
1179
1180
#endif
#endif
Damien's avatar
Damien committed
1181
1182
}

1183
1184
1185
1186
1187
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
1188
    unique_codes[unique_code_id].n_args = n_args;
1189
    unique_codes[unique_code_id].n_locals = 0;
Damien's avatar
Damien committed
1190
    unique_codes[unique_code_id].n_cells = 0;
1191
1192
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
1193
    unique_codes[unique_code_id].u_inline_asm.fun = fun;
Damien's avatar
Damien committed
1194

1195
#ifdef DEBUG_PRINT
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
    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");

1206
1207
1208
#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fwrite(fun_data, len, 1, fp_write_code);
1209
    }
1210
1211
#endif
#endif
Damien's avatar
Damien committed
1212
1213
}

1214
1215
1216
1217
1218
1219
1220
1221
1222
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:
1223
            case O_FUN_VAR:
1224
1225
1226
            case O_FUN_N:
            case O_FUN_BC:
            case O_FUN_ASM:
1227
            // what about O_CLASS, and an O_OBJ that has a __call__ method?
1228
1229
1230
1231
1232
1233
1234
                return true;
            default:
                return false;
        }
    }
}

Damien's avatar
Damien committed
1235
void py_obj_print(py_obj_t o_in) {
1236
    py_obj_print_helper(printf_wrapper, NULL, o_in);
Damien's avatar
Damien committed
1237
1238
}

Damien's avatar
Damien committed
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
#define PARSE_DEC_IN_INTG (1)
#define PARSE_DEC_IN_FRAC (2)
#define PARSE_DEC_IN_EXP  (3)

py_obj_t rt_load_const_dec(qstr qstr) {
#if MICROPY_ENABLE_FLOAT
    DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
    const char *s = qstr_str(qstr);
    int in = PARSE_DEC_IN_INTG;
    py_float_t dec_val = 0;
    bool exp_neg = false;
    int exp_val = 0;
    int exp_extra = 0;
    bool imag = false;
    for (; *s; s++) {
        int dig = *s;
        if ('0' <= dig && dig <= '9') {
            dig -= '0';
            if (in == PARSE_DEC_IN_EXP) {
                exp_val = 10 * exp_val + dig;
            } else {
                dec_val = 10 * dec_val + dig;
                if (in == PARSE_DEC_IN_FRAC) {
                    exp_extra -= 1;
                }
            }
        } else if (in == PARSE_DEC_IN_INTG && dig == '.') {
            in = PARSE_DEC_IN_FRAC;
        } else if (in != PARSE_DEC_IN_EXP && (dig == 'E' || dig == 'e')) {
            in = PARSE_DEC_IN_EXP;
            if (s[1] == '+') {
                s++;
            } else if (s[1] == '-') {
                s++;
                exp_neg = true;
            }
        } else if (dig == 'J' || dig == 'j') {
            s++;
            imag = true;
            break;
        } else {
            // unknown character
            break;
        }
    }
    if (*s != 0) {
        nlr_jump(py_obj_new_exception_2(q_SyntaxError, "invalid syntax for number", NULL, NULL));
    }
    if (exp_neg) {
        exp_val = -exp_val;
    }
    exp_val += exp_extra;
    for (; exp_val > 0; exp_val--) {
        dec_val *= 10;
    }
    for (; exp_val < 0; exp_val++) {
        dec_val *= 0.1;
    }
    if (imag) {
        return py_obj_new_complex(0, dec_val);
    } else {
        return py_obj_new_float(dec_val);
    }
#else
    nlr_jump(py_obj_new_exception_2(q_SyntaxError, "decimal numbers not supported", NULL, NULL));
#endif
}

Damien's avatar
Damien committed
1307
1308
1309
1310
1311
1312
1313
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
1314
    DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
1315
    py_map_elem_t *elem = py_qstr_map_lookup(map_locals, qstr, false);
Damien's avatar
Damien committed
1316
    if (elem == NULL) {
1317
        elem = py_qstr_map_lookup(map_globals, qstr, false);
Damien's avatar
Damien committed
1318
        if (elem == NULL) {
1319
1320
            elem = py_qstr_map_lookup(&map_builtins, qstr, false);
            if (elem == NULL) {
1321
                nlr_jump(py_obj_new_exception_2(q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
1322
            }
Damien's avatar
Damien committed
1323
1324
1325
1326
1327
1328
        }
    }
    return elem->value;
}

py_obj_t rt_load_global(qstr qstr) {
1329
1330
    // logic: search globals, builtins
    DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
1331
    py_map_elem_t *elem = py_qstr_map_lookup(map_globals, qstr, false);
1332
1333
1334
    if (elem == NULL) {
        elem = py_qstr_map_lookup(&map_builtins, qstr, false);
        if (elem == NULL) {
1335
            nlr_jump(py_obj_new_exception_2(q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
1336
1337
1338
        }
    }
    return elem->value;
Damien's avatar
Damien committed
1339
1340
}

1341
py_obj_t rt_load_build_class(void) {
Damien's avatar
Damien committed
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
    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) {
1352
    DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
1353
    py_qstr_map_lookup(map_locals, qstr, true)->value = obj;
1354
1355
1356
1357
}

void rt_store_global(qstr qstr, py_obj_t obj) {
    DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qstr), obj);
1358
    py_qstr_map_lookup(map_globals, qstr, true)->value = obj;
Damien's avatar
Damien committed
1359
1360
1361
}

py_obj_t rt_unary_op(int op, py_obj_t arg) {
Damien's avatar
Damien committed
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
    DEBUG_OP_printf("unary %d %p\n", op, arg);
    if (IS_SMALL_INT(arg)) {
        py_small_int_t val = FROM_SMALL_INT(arg);
        switch (op) {
            case RT_UNARY_OP_NOT: if (val != 0) { return py_const_true;} else { return py_const_false; }
            case RT_UNARY_OP_POSITIVE: break;
            case RT_UNARY_OP_NEGATIVE: val = -val; break;
            case RT_UNARY_OP_INVERT: val = ~val; break;
            default: assert(0); val = 0;
        }
        if (fit_small_int(val)) {
            return TO_SMALL_INT(val);
        }
#if MICROPY_ENABLE_FLOAT
    } else if (IS_O(arg, O_FLOAT)) {
        py_float_t val = py_obj_get_float(arg);
        switch (op) {
            case RT_UNARY_OP_NOT: if (val != 0) { return py_const_true;} else { return py_const_false; }
            case RT_UNARY_OP_POSITIVE: break;
            case RT_UNARY_OP_NEGATIVE: val = -val; break;
            case RT_UNARY_OP_INVERT: nlr_jump(py_obj_new_exception_2(q_TypeError, "bad operand type for unary ~: 'float'", NULL, NULL));
            default: assert(0); val = 0;
        }
        return py_obj_new_float(val);
#endif
    }
Damien's avatar
Damien committed
1388
1389
1390
1391
1392
1393
1394
    assert(0);
    return py_const_none;
}

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) {
1395
1396
1397
1398
1399
1400
        if (IS_O(lhs, O_STR)) {
            // string access
            // XXX a hack!
            const char *str = qstr_str(((py_obj_base_t*)lhs)->u_str);
            return py_obj_new_int(str[FROM_SMALL_INT(rhs)]);
        } else if ((IS_O(lhs, O_TUPLE) || IS_O(lhs, O_LIST))) {
Damien's avatar
Damien committed
1401
            // tuple/list load
1402
1403
            uint index = get_index(lhs, rhs);
            return ((py_obj_base_t*)lhs)->u_tuple_list.items[index];
Damien's avatar
Damien committed
1404
1405
1406
1407
1408
1409
1410
1411
        } 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
1412
1413
1414
1415
        } else {
            assert(0);
        }
    } else if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
1416
1417
        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
1418
        switch (op) {
1419
            case RT_BINARY_OP_OR:
Damien's avatar
Damien committed
1420
            case RT_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
1421
            case RT_BINARY_OP_XOR:
Damien's avatar
Damien committed
1422
            case RT_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
1423
            case RT_BINARY_OP_AND:
Damien's avatar
Damien committed
1424
            case RT_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
1425
            case RT_BINARY_OP_LSHIFT:
Damien's avatar
Damien committed
1426
            case RT_BINARY_OP_INPLACE_LSHIFT: lhs_val <<= rhs_val; break;
1427
            case RT_BINARY_OP_RSHIFT: