runtime.c 54.2 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
19
20
21
22
#include "map.h"
#include "obj.h"
#include "objprivate.h"
#include "builtin.h"

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

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// TODO make these predefined so they don't take up RAM
qstr rt_q_append;
qstr rt_q_pop;
qstr rt_q_sort;
qstr rt_q_join;
qstr rt_q_format;
qstr rt_q___build_class__;
qstr rt_q___next__;
qstr rt_q_AttributeError;
qstr rt_q_IndexError;
qstr rt_q_KeyError;
qstr rt_q_NameError;
qstr rt_q_TypeError;
qstr rt_q_SyntaxError;
qstr rt_q_ValueError;
48

Damien's avatar
Damien committed
49
50
51
py_obj_t py_const_none;
py_obj_t py_const_false;
py_obj_t py_const_true;
52
py_obj_t py_const_stop_iteration;
Damien's avatar
Damien committed
53

54
// locals and globals need to be pointers because they can be the same in outer module scope
55
56
57
static py_map_t *map_locals;
static py_map_t *map_globals;
static py_map_t map_builtins;
Damien's avatar
Damien committed
58

59
60
py_map_t *rt_get_map_locals(void) {
    return map_locals;
Damien's avatar
Damien committed
61
62
}

63
64
void rt_set_map_locals(py_map_t *m) {
    map_locals = m;
Damien's avatar
Damien committed
65
66
67
68
69
70
}

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

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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;
    }
}

91
92
93
94
95
96
97
void vstr_printf_wrapper(void *env, const char *fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vstr_vprintf(env, fmt, args);
    va_end(args);
}

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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:
128
    nlr_jump(py_obj_new_exception_2(rt_q_TypeError, "?str.join expecting a list of str's", NULL, NULL));
129
130
}

131
py_obj_t rt_str_format(int n_args, const py_obj_t *args) {
132
133
134
135
136
137
138
139
140
141
142
143
144
    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) {
145
                    nlr_jump(py_obj_new_exception_2(rt_q_IndexError, "tuple index out of range", NULL, NULL));
146
147
148
149
150
151
152
153
154
155
156
157
                }
                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));
}

158
159
160
161
162
163
164
165
166
167
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) {
168
            nlr_jump(py_obj_new_exception_2(rt_q_IndexError, "%s index out of range", py_obj_get_type_str(base), NULL));
169
170
171
        }
        return i;
    } else {
172
        nlr_jump(py_obj_new_exception_2(rt_q_TypeError, "%s indices must be integers, not %s", py_obj_get_type_str(base), py_obj_get_type_str(index)));
173
174
175
    }
}

176
py_obj_t rt_list_append(py_obj_t self_in, py_obj_t arg) {
Damien's avatar
Damien committed
177
178
    assert(IS_O(self_in, O_LIST));
    py_obj_base_t *self = self_in;
179
180
181
    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
182
    }
183
    self->u_tuple_list.items[self->u_tuple_list.len++] = arg;
Damien's avatar
Damien committed
184
    return py_const_none; // return None, as per CPython
Damien's avatar
Damien committed
185
186
}

187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
}

228
229
230
231
232
233
234
235
236
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
237
typedef enum {
238
    PY_CODE_NONE,
Damien's avatar
Damien committed
239
    PY_CODE_BYTE,
240
241
    PY_CODE_NATIVE,
    PY_CODE_INLINE_ASM,
Damien's avatar
Damien committed
242
243
244
245
246
} py_code_kind_t;

typedef struct _py_code_t {
    py_code_kind_t kind;
    int n_args;
247
    int n_locals;
Damien's avatar
Damien committed
248
    int n_cells;
249
250
    int n_stack;
    bool is_generator;
Damien's avatar
Damien committed
251
252
253
254
255
    union {
        struct {
            byte *code;
            uint len;
        } u_byte;
256
257
258
259
        struct {
            py_fun_t fun;
        } u_native;
        struct {
260
            void *fun;
261
        } u_inline_asm;
Damien's avatar
Damien committed
262
263
264
265
266
267
    };
} py_code_t;

static int next_unique_code_id;
static py_code_t *unique_codes;

268
py_obj_t fun_str_join;
269
py_obj_t fun_str_format;
Damien's avatar
Damien committed
270
py_obj_t fun_list_append;
271
272
py_obj_t fun_list_pop;
py_obj_t fun_list_sort;
273
py_obj_t fun_gen_instance_next;
Damien's avatar
Damien committed
274

275
276
#ifdef WRITE_CODE
FILE *fp_write_code = NULL;
277
#endif
Damien's avatar
Damien committed
278

279
void rt_init(void) {
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    rt_q_append = qstr_from_str_static("append");
    rt_q_pop = qstr_from_str_static("pop");
    rt_q_sort = qstr_from_str_static("sort");
    rt_q_join = qstr_from_str_static("join");
    rt_q_format = qstr_from_str_static("format");
    rt_q___build_class__ = qstr_from_str_static("__build_class__");
    rt_q___next__ = qstr_from_str_static("__next__");
    rt_q_AttributeError = qstr_from_str_static("AttributeError");
    rt_q_IndexError = qstr_from_str_static("IndexError");
    rt_q_KeyError = qstr_from_str_static("KeyError");
    rt_q_NameError = qstr_from_str_static("NameError");
    rt_q_TypeError = qstr_from_str_static("TypeError");
    rt_q_SyntaxError = qstr_from_str_static("SyntaxError");
    rt_q_ValueError = qstr_from_str_static("ValueError");
Damien's avatar
Damien committed
294
295
296
297

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

300
301
302
    // 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
303
304

    py_map_init(&map_builtins, MAP_QSTR, 3);
305
    py_qstr_map_lookup(&map_builtins, rt_q___build_class__, true)->value = rt_make_function_2(py_builtin___build_class__);
Damien's avatar
Damien committed
306
    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
307
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("abs"), true)->value = rt_make_function_1(py_builtin_abs);
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("all"), true)->value = rt_make_function_1(py_builtin_all);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("any"), true)->value = rt_make_function_1(py_builtin_any);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("bool"), true)->value = rt_make_function_var(0, py_builtin_bool);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("callable"), true)->value = rt_make_function_1(py_builtin_callable);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("complex"), true)->value = rt_make_function_var(0, py_builtin_complex);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("chr"), true)->value = rt_make_function_1(py_builtin_chr);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("dict"), true)->value = rt_make_function_0(py_builtin_dict);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("divmod"), true)->value = rt_make_function_2(py_builtin_divmod);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("hash"), true)->value = rt_make_function_1(py_builtin_hash);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("iter"), true)->value = rt_make_function_1(py_builtin_iter);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("len"), true)->value = rt_make_function_1(py_builtin_len);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("list"), true)->value = rt_make_function_var(0, py_builtin_list);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("max"), true)->value = rt_make_function_var(1, py_builtin_max);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("min"), true)->value = rt_make_function_var(1, py_builtin_min);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("next"), true)->value = rt_make_function_1(py_builtin_next);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("ord"), true)->value = rt_make_function_1(py_builtin_ord);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("pow"), true)->value = rt_make_function_var(2, py_builtin_pow);
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("print"), true)->value = rt_make_function_var(0, py_builtin_print);
326
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("range"), true)->value = rt_make_function_var(1, py_builtin_range);
327
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("sum"), true)->value = rt_make_function_var(1, py_builtin_sum);
Damien's avatar
Damien committed
328

Damien's avatar
Damien committed
329
    next_unique_code_id = 2; // 1 is reserved for the __main__ module scope
Damien's avatar
Damien committed
330
331
    unique_codes = NULL;

332
    fun_str_join = rt_make_function_2(rt_str_join);
333
    fun_str_format = rt_make_function_var(1, rt_str_format);
334
    fun_list_append = rt_make_function_2(rt_list_append);
335
336
    fun_list_pop = rt_make_function_2(rt_list_pop);
    fun_list_sort = rt_make_function_2(rt_list_sort);
337
    fun_gen_instance_next = rt_make_function_1(rt_gen_instance_next);
Damien's avatar
Damien committed
338

339
340
#ifdef WRITE_CODE
    fp_write_code = fopen("out-code", "wb");
341
#endif
Damien's avatar
Damien committed
342
343
}

344
void rt_deinit(void) {
345
346
347
#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fclose(fp_write_code);
Damien's avatar
Damien committed
348
    }
349
#endif
Damien's avatar
Damien committed
350
351
}

Damien's avatar
Damien committed
352
353
354
355
356
357
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
358
359
}

360
static void alloc_unique_codes(void) {
Damien's avatar
Damien committed
361
    if (unique_codes == NULL) {
362
        unique_codes = m_new(py_code_t, next_unique_code_id + 10); // XXX hack until we fix the REPL allocation problem
363
364
365
        for (int i = 0; i < next_unique_code_id; i++) {
            unique_codes[i].kind = PY_CODE_NONE;
        }
Damien's avatar
Damien committed
366
    }
367
368
}

Damien's avatar
Damien committed
369
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) {
370
371
372
373
374
    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;
375
    unique_codes[unique_code_id].n_locals = n_locals;
Damien's avatar
Damien committed
376
    unique_codes[unique_code_id].n_cells = n_cells;
377
378
    unique_codes[unique_code_id].n_stack = n_stack;
    unique_codes[unique_code_id].is_generator = is_generator;
379
380
381
    unique_codes[unique_code_id].u_byte.code = code;
    unique_codes[unique_code_id].u_byte.len = len;

Damien's avatar
Damien committed
382
    //printf("byte code: %d bytes\n", len);
383
384

#ifdef DEBUG_PRINT
385
    DEBUG_printf("assign byte code: id=%d code=%p len=%u n_args=%d\n", unique_code_id, code, len, n_args);
386
387
388
389
390
391
392
    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");
393
394
    extern void py_show_byte_code(const byte *code, int len);
    py_show_byte_code(code, len);
395
396
397
398
399
400
401
402

#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fwrite(code, len, 1, fp_write_code);
        fflush(fp_write_code);
    }
#endif
#endif
403
404
405
406
407
}

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

408
    assert(1 <= unique_code_id && unique_code_id < next_unique_code_id);
Damien's avatar
Damien committed
409
410
    unique_codes[unique_code_id].kind = PY_CODE_NATIVE;
    unique_codes[unique_code_id].n_args = n_args;
411
    unique_codes[unique_code_id].n_locals = 0;
Damien's avatar
Damien committed
412
    unique_codes[unique_code_id].n_cells = 0;
413
414
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
Damien's avatar
Damien committed
415
416
    unique_codes[unique_code_id].u_native.fun = fun;

417
418
    printf("native code: %d bytes\n", len);

419
#ifdef DEBUG_PRINT
Damien's avatar
Damien committed
420
421
422
423
424
425
426
427
428
429
    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");

430
431
432
433
#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
434
    }
435
436
#endif
#endif
Damien's avatar
Damien committed
437
438
}

439
440
441
442
443
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
444
    unique_codes[unique_code_id].n_args = n_args;
445
    unique_codes[unique_code_id].n_locals = 0;
Damien's avatar
Damien committed
446
    unique_codes[unique_code_id].n_cells = 0;
447
448
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
449
    unique_codes[unique_code_id].u_inline_asm.fun = fun;
Damien's avatar
Damien committed
450

451
#ifdef DEBUG_PRINT
452
453
454
455
456
457
458
459
460
461
    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");

462
463
464
#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fwrite(fun_data, len, 1, fp_write_code);
465
    }
466
467
#endif
#endif
Damien's avatar
Damien committed
468
469
}

Damien's avatar
Damien committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
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
#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) {
516
        nlr_jump(py_obj_new_exception_2(rt_q_SyntaxError, "invalid syntax for number", NULL, NULL));
Damien's avatar
Damien committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
    }
    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
534
    nlr_jump(py_obj_new_exception_2(rt_q_SyntaxError, "decimal numbers not supported", NULL, NULL));
Damien's avatar
Damien committed
535
536
537
#endif
}

Damien's avatar
Damien committed
538
539
540
541
542
543
544
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
545
    DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
546
    py_map_elem_t *elem = py_qstr_map_lookup(map_locals, qstr, false);
Damien's avatar
Damien committed
547
    if (elem == NULL) {
548
        elem = py_qstr_map_lookup(map_globals, qstr, false);
Damien's avatar
Damien committed
549
        if (elem == NULL) {
550
551
            elem = py_qstr_map_lookup(&map_builtins, qstr, false);
            if (elem == NULL) {
552
                nlr_jump(py_obj_new_exception_2(rt_q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
553
            }
Damien's avatar
Damien committed
554
555
556
557
558
559
        }
    }
    return elem->value;
}

py_obj_t rt_load_global(qstr qstr) {
560
561
    // logic: search globals, builtins
    DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
562
    py_map_elem_t *elem = py_qstr_map_lookup(map_globals, qstr, false);
563
564
565
    if (elem == NULL) {
        elem = py_qstr_map_lookup(&map_builtins, qstr, false);
        if (elem == NULL) {
566
            nlr_jump(py_obj_new_exception_2(rt_q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
567
568
569
        }
    }
    return elem->value;
Damien's avatar
Damien committed
570
571
}

572
py_obj_t rt_load_build_class(void) {
Damien's avatar
Damien committed
573
    DEBUG_OP_printf("load_build_class\n");
574
    py_map_elem_t *elem = py_qstr_map_lookup(&map_builtins, rt_q___build_class__, false);
Damien's avatar
Damien committed
575
576
577
578
579
580
581
    if (elem == NULL) {
        printf("name doesn't exist: __build_class__\n");
        assert(0);
    }
    return elem->value;
}

582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
py_obj_t rt_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;
}

py_obj_t rt_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 rt_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);
    }
}

Damien's avatar
Damien committed
606
void rt_store_name(qstr qstr, py_obj_t obj) {
607
    DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
608
    py_qstr_map_lookup(map_locals, qstr, true)->value = obj;
609
610
611
612
}

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

py_obj_t rt_unary_op(int op, py_obj_t arg) {
Damien's avatar
Damien committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
    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;
637
            case RT_UNARY_OP_INVERT: nlr_jump(py_obj_new_exception_2(rt_q_TypeError, "bad operand type for unary ~: 'float'", NULL, NULL));
Damien's avatar
Damien committed
638
639
640
641
642
            default: assert(0); val = 0;
        }
        return py_obj_new_float(val);
#endif
    }
Damien's avatar
Damien committed
643
644
645
646
647
648
649
    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) {
650
651
652
653
654
655
        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
656
            // tuple/list load
657
658
            uint index = get_index(lhs, rhs);
            return ((py_obj_base_t*)lhs)->u_tuple_list.items[index];
Damien's avatar
Damien committed
659
660
661
662
        } else if (IS_O(lhs, O_MAP)) {
            // map load
            py_map_elem_t *elem = py_map_lookup(lhs, rhs, false);
            if (elem == NULL) {
663
                nlr_jump(py_obj_new_exception_2(rt_q_KeyError, "<value>", NULL, NULL));
Damien's avatar
Damien committed
664
665
666
            } else {
                return elem->value;
            }
Damien's avatar
Damien committed
667
668
669
670
        } else {
            assert(0);
        }
    } else if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
671
672
        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
673
        switch (op) {
674
            case RT_BINARY_OP_OR:
Damien's avatar
Damien committed
675
            case RT_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
676
            case RT_BINARY_OP_XOR:
Damien's avatar
Damien committed
677
            case RT_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
678
            case RT_BINARY_OP_AND:
Damien's avatar
Damien committed
679
            case RT_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
680
            case RT_BINARY_OP_LSHIFT:
Damien's avatar
Damien committed
681
            case RT_BINARY_OP_INPLACE_LSHIFT: lhs_val <<= rhs_val; break;
682
            case RT_BINARY_OP_RSHIFT:
Damien's avatar
Damien committed
683
            case RT_BINARY_OP_INPLACE_RSHIFT: lhs_val >>= rhs_val; break;
Damien's avatar
Damien committed
684
            case RT_BINARY_OP_ADD:
Damien's avatar
Damien committed
685
            case RT_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
686
            case RT_BINARY_OP_SUBTRACT:
Damien's avatar
Damien committed
687
            case RT_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
688
            case RT_BINARY_OP_MULTIPLY:
Damien's avatar
Damien committed
689
            case RT_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break;
690
            case RT_BINARY_OP_FLOOR_DIVIDE:
Damien's avatar
Damien committed
691
            case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: lhs_val /= rhs_val; break;
692
#if MICROPY_ENABLE_FLOAT
693
            case RT_BINARY_OP_TRUE_DIVIDE:
Damien's avatar
Damien committed
694
            case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: return py_obj_new_float((py_float_t)lhs_val / (py_float_t)rhs_val);
Damien's avatar
Damien committed
695
#endif
696
697
698
699
700
701

            // TODO implement modulo as specified by Python
            case RT_BINARY_OP_MODULO:
            case RT_BINARY_OP_INPLACE_MODULO: lhs_val %= rhs_val; break;

            // TODO check for negative power, and overflow
702
703
            case RT_BINARY_OP_POWER:
            case RT_BINARY_OP_INPLACE_POWER:
704
705
706
707
708
709
710
711
            {
                int ans = 1;
                while (rhs_val > 0) {
                    if (rhs_val & 1) {
                        ans *= lhs_val;
                    }
                    lhs_val *= lhs_val;
                    rhs_val /= 2;
712
                }
713
714
715
716
                lhs_val = ans;
                break;
            }

Damien's avatar
Damien committed
717
            default: printf("%d\n", op); assert(0);
Damien's avatar
Damien committed
718
        }
Damien's avatar
Damien committed
719
720
        if (fit_small_int(lhs_val)) {
            return TO_SMALL_INT(lhs_val);
Damien's avatar
Damien committed
721
        }
722
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
723
724
725
726
    } else if (IS_O(lhs, O_COMPLEX) || IS_O(rhs, O_COMPLEX)) {
        py_float_t lhs_real, lhs_imag, rhs_real, rhs_imag;
        py_obj_get_complex(lhs, &lhs_real, &lhs_imag);
        py_obj_get_complex(rhs, &rhs_real, &rhs_imag);
727
728
        switch (op) {
            case RT_BINARY_OP_ADD:
Damien's avatar
Damien committed
729
730
731
732
            case RT_BINARY_OP_INPLACE_ADD:
                lhs_real += rhs_real;
                lhs_imag += rhs_imag;
                break;
733
            case RT_BINARY_OP_SUBTRACT:
Damien's avatar
Damien committed
734
735
736
737
            case RT_BINARY_OP_INPLACE_SUBTRACT:
                lhs_real -= rhs_real;
                lhs_imag -= rhs_imag;
                break;
738
            case RT_BINARY_OP_MULTIPLY:
Damien's avatar
Damien committed
739
740
741
742
743
744
745
            case RT_BINARY_OP_INPLACE_MULTIPLY:
            {
                py_float_t real = lhs_real * rhs_real - lhs_imag * rhs_imag;
                lhs_imag = lhs_real * rhs_imag + lhs_imag * rhs_real;
                lhs_real = real;
                break;
            }
746
747
748
749
            /* TODO floor(?) the value
            case RT_BINARY_OP_FLOOR_DIVIDE:
            case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: val = lhs_val / rhs_val; break;
            */
Damien's avatar
Damien committed
750
            /* TODO
751
752
            case RT_BINARY_OP_TRUE_DIVIDE:
            case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: val = lhs_val / rhs_val; break;
Damien's avatar
Damien committed
753
754
            */
            default: printf("%d\n", op); assert(0);
755
        }
Damien's avatar
Damien committed
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
        return py_obj_new_complex(lhs_real, lhs_imag);
    } else if (IS_O(lhs, O_FLOAT) || IS_O(rhs, O_FLOAT)) {
        py_float_t lhs_val = py_obj_get_float(lhs);
        py_float_t rhs_val = py_obj_get_float(rhs);
        switch (op) {
            case RT_BINARY_OP_ADD:
            case RT_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
            case RT_BINARY_OP_SUBTRACT:
            case RT_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
            case RT_BINARY_OP_MULTIPLY:
            case RT_BINARY_OP_INPLACE_MULTIPLY: 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: lhs_val /= rhs_val; break;
            default: printf("%d\n", op); assert(0);
        }
        return py_obj_new_float(lhs_val);
776
#endif
Damien's avatar
Damien committed
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
    } 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);
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812

    // 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
813
    if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
        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)) {
Damien's avatar
Damien committed
834
835
        py_float_t lhs_val = py_obj_get_float(lhs);
        py_float_t rhs_val = py_obj_get_float(rhs);
Damien's avatar
Damien committed
836
837
        int cmp;
        switch (op) {
838
839
840
841
            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
842
843
844
845
846
847
848
849
            default: assert(0); cmp = 0;
        }
        if (cmp) {
            return py_const_true;
        } else {
            return py_const_false;
        }
    }
850
#endif
851
852

    // not implemented
Damien's avatar
Damien committed
853
854
855
856
857
    assert(0);
    return py_const_none;
}

py_obj_t rt_make_function_from_id(int unique_code_id) {
858
859
    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
860
861
862
863
864
865
        // 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) {
866
867
868
        case PY_CODE_BYTE:
            o->kind = O_FUN_BC;
            o->u_fun_bc.n_args = c->n_args;
Damien's avatar
Damien committed
869
            o->u_fun_bc.n_state = c->n_locals + c->n_cells + c->n_stack;
870
871
            o->u_fun_bc.code = c->u_byte.code;
            break;
Damien's avatar
Damien committed
872
873
874
875
876
877
878
879
880
        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;
881
882
883
884
        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
885
886
887
888
            break;
        default:
            assert(0);
    }
889
890
891
892
893
894

    // 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
Damien's avatar
Damien committed
895
        o2->u_gen_wrap.n_state = ((c->n_locals + c->n_cells) < 3 ? 3 : (c->n_locals + c->n_cells)) + c->n_stack;
896
897
898
899
        o2->u_gen_wrap.fun = o;
        o = o2;
    }

Damien's avatar
Damien committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
    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;
929
    o->u_fun.fun = code;
Damien's avatar
Damien committed
930
931
932
    return o;
}

933
934
935
936
937
938
939
940
py_obj_t rt_make_function_var(int n_fixed_args, py_fun_var_t f) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_FUN_VAR;
    o->u_fun.n_args = n_fixed_args;
    o->u_fun.fun = f;
    return o;
}

Damien's avatar
Damien committed
941
942
943
944
945
946
947
948
949
950
py_obj_t rt_make_closure_from_id(int unique_code_id, py_obj_t closure_tuple) {
    py_obj_t f = rt_make_function_from_id(unique_code_id);
    // wrap function in closure object
    py_obj_base_t *f2 = m_new(py_obj_base_t, 1);
    f2->kind = O_CLOSURE;
    f2->u_closure.fun = f;
    f2->u_closure.vars = closure_tuple;
    return f2;
}

951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
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);

971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
// 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);

989
#if MICROPY_ENABLE_FLOAT
990
991
            case O_FLOAT:
                // convert float to int (could also pass in float registers)
Damien's avatar
Damien committed
992
                return (machine_int_t)o->u_float;
993
#endif
994

995
            case O_TUPLE:
996
            case O_LIST:
997
998
                // 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;
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011

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

1012
1013
1014
// 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
1015
1016
    if (IS_O(fun, O_FUN_0)) {
        py_obj_base_t *o = fun;
1017
1018
1019
1020
1021
        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
1022
        return ((py_fun_0_t)o->u_fun.fun)();
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043

    } 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

1044
1045
1046
    } else if (IS_O(fun, O_FUN_VAR)) {
        py_obj_base_t *o = fun;
        if (n_args < o->u_fun.n_args) {
1047
            nlr_jump(py_obj_new_exception_2(rt_q_TypeError, "<fun name>() missing %d required positional arguments: <list of names of params>", (const char*)(machine_int_t)(o->u_fun.n_args - n_args), NULL));
1048
        }
1049
1050
        // TODO really the args need to be passed in as a Python tuple, as the form f(*[1,2]) can be used to pass var args
        py_obj_t *args_ordered = m_new(py_obj_t, n_args);
1051
1052
1053
1054
1055
1056
1057
        for (int i = 0; i < n_args; i++) {
            args_ordered[i] = args[n_args - i - 1];
        }
        py_obj_t res = ((py_fun_var_t)o->u_fun.fun)(n_args, args_ordered);
        m_free(args_ordered);
        return res;

Damien's avatar
Damien committed
1058
1059
    } else if (IS_O(fun, O_FUN_BC)) {
        py_obj_base_t *o = fun;
1060
1061
1062
1063
1064
        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);
1065
        return py_execute_byte_code(o->u_fun_bc.code, args, n_args, o->u_fun_bc.n_state);
1066

1067
1068
    } else if (IS_O(fun, O_FUN_ASM)) {
        py_obj_base_t *o = fun;
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
        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);

1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
    } else if (IS_O(fun, O_GEN_WRAP)) {
        py_obj_base_t *o = fun;
        py_obj_base_t *o_fun = o->u_gen_wrap.fun;
        assert(o_fun->kind == O_FUN_BC); // TODO
        if (n_args != o_fun->u_fun_bc.n_args) {
            n_args_fun = o_fun->u_fun_bc.n_args;
            goto bad_n_args;
        }
        py_obj_t *state = m_new(py_obj_t, 1 + o->u_gen_wrap.n_state);
        // put function object at first slot in state (to keep u_gen_instance small)
        state[0] = o_fun;
        // init args
        for (int i = 0; i < n_args; i++) {
            state[1 + i] = args[n_args - 1 - i];
        }
        py_obj_base_t *o2 = m_new(py_obj_base_t, 1);
        o2->kind = O_GEN_INSTANCE;
        o2->u_gen_instance.state = state;
        o2->u_gen_instance.ip = o_fun->u_fun_bc.code;
        o2->u_gen_instance.sp = state + o->u_gen_wrap.n_state;
        return o2;

1111
1112
    } else if (IS_O(fun, O_BOUND_METH)) {
        py_obj_base_t *o = fun;
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
        DEBUG_OP_printf("calling bound method %p(self=%p, n_args=%d)\n", o->u_bound_meth.meth, o->u_bound_meth.self, n_args);
        if (n_args == 0) {
            return rt_call_function_n(o->u_bound_meth.meth, 1, &o->u_bound_meth.self);
        } else if (n_args == 1) {
            py_obj_t args2[2];
            args2[1] = o->u_bound_meth.self;
            args2[0] = args[0];
            return rt_call_function_n(o->u_bound_meth.meth, 2, args2);
        } else {
            // TODO not implemented
            assert(0);
            return py_const_none;
            //return rt_call_function_2(o->u_bound_meth.meth, n_args + 1, o->u_bound_meth.self + args);
        }

1128
1129
    } else if (IS_O(fun, O_CLASS)) {
        // instantiate an instance of a class
1130
1131

        DEBUG_OP_printf("instantiate object of class %p with %d args\n", fun, n_args);
1132
1133
1134
1135
        py_obj_base_t *o = m_new(py_obj_base_t, 1);
        o->kind = O_OBJ;
        o->u_obj.class = fun;
        o->u_obj.members = py_map_new(MAP_QSTR, 0);
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153

        // look for __init__ function
        py_obj_base_t *o_class = fun;
        py_map_elem_t *init_fn = py_qstr_map_lookup(o_class->u_class.locals, qstr_from_str_static("__init__"), false);

        if (init_fn != NULL) {
            // call __init__ function
            py_obj_t init_ret;
            if (n_args == 0) {
                init_ret = rt_call_function_n(init_fn->value, 1, (py_obj_t*)&o);
            } else {
                py_obj_t *args2 = m_new(py_obj_t, n_args + 1);
                memcpy(args2, args, n_args * sizeof(py_obj_t));
                args2[n_args] = o;
                init_ret = rt_call_function_n(init_fn->value, n_args + 1, args2);
                m_free(args2);
            }
            if (init_ret != py_const_none) {
1154
                nlr_jump(py_obj_new_exception_2(rt_q_TypeError, "__init__() should return None, not '%s'", py_obj_get_type_str(init_ret), NULL));
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
            }

        } else {
            // TODO
            if (n_args != 0) {
                n_args_fun = 0;
                goto bad_n_args;
            }
        }

1165
        return o;
Damien's avatar
Damien committed
1166
1167

    } else {
1168
        printf("fun %p %d\n", fun, ((py_obj_base_t*)fun)->kind);
Damien's avatar
Damien committed
1169
1170
1171
1172
        assert(0);
        return py_const_none;
    }

1173
bad_n_args:
1174
    nlr_jump(py_obj_new_exception_2(rt_q_TypeError, "function takes %d positional arguments but %d were given", (const char*)(machine_int_t)n_args_fun, (const char*)(machine_int_t)n_args));
Damien's avatar
Damien committed
1175
1176
}

1177
1178
1179
1180
1181
1182
1183
1184
// args are in reverse order in the array; keyword arguments come first, value then key
// eg: (value1, key1, value0, key0, arg1, arg0)
py_obj_t rt_call_function_n_kw(py_obj_t fun, uint n_args, uint n_kw, const py_obj_t *args) {
    // TODO
    assert(0);
    return py_const_none;
}

1185
1186
// args contains: arg(n_args-1)  arg(n_args-2)  ...  arg(0)  self/NULL  fun
// if n_args==0 then there are only self/NULL and fun
1187
1188
py_obj_t rt_call_method_n(uint n_args, const py_obj_t *args) {
    DEBUG_OP_printf("call method %p(self=%p, n_args=%u)\n", args[n_args + 1], args[n_args], n_args);
1189
1190
1191
    return rt_call_function_n(args[n_args + 1], n_args + ((args[n_args] == NULL) ? 0 : 1), args);
}

1192
1193
1194
1195
1196
1197
1198
// args contains: kw_val(n_kw-1)  kw_key(n_kw-1) ... kw_val(0)  kw_key(0)  arg(n_args-1)  arg(n_args-2)  ...  arg(0)  self/NULL  fun
py_obj_t rt_call_method_n_kw(uint n_args, uint n_kw, const py_obj_t *args) {
    uint n = n_args + 2 * n_kw;
    DEBUG_OP_printf("call method %p(self=%p, n_args=%u, n_kw=%u)\n", args[n + 1], args[n], n_args, n_kw);
    return rt_call_function_n_kw(args[n + 1], n_args + ((args[n] == NULL) ? 0 : 1), n_kw, args);
}

1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
// items are in reverse order
py_obj_t rt_build_tuple(int n_args, py_obj_t *items) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_TUPLE;
    o->u_tuple_list.alloc = n_args < 4 ? 4 : n_args;
    o->u_tuple_list.len = n_args;
    o->u_tuple_list.items = m_new(py_obj_t, o->u_tuple_list.alloc);
    for (int i = 0; i < n_args; i++) {
        o->u_tuple_list.items[i] = items[n_args - i - 1];
    }
    return o;
}

Damien's avatar
Damien committed
1212
1213
1214
1215
// items are in reverse order
py_obj_t rt_build_list(int n_args, py_obj_t *items) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_LIST;
1216
1217
1218
    o->u_tuple_list.alloc = n_args < 4 ? 4 : n_args;
    o->u_tuple_list.len = n_args;
    o->u_tuple_list.items = m_new(py_obj_t, o->u_tuple_list.alloc);
Damien's avatar
Damien committed
1219
    for (int i = 0; i < n_args; i++) {
1220
        o->u_tuple_list.items[i] = items[n_args - i - 1];
Damien's avatar
Damien committed
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
    }
    return o;
}

py_obj_t rt_build_set(int n_args, py_obj_t *items) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_SET;
    o->u_set.alloc = get_doubling_prime_greater_or_equal_to(n_args + 1);
    o->u_set.used = 0;
    o->u_set.table = m_new(py_obj_t, o->u_set.alloc);
    for (int i = 0; i < o->u_set.alloc; i++) {
        o->u_set.table[i] = NULL;
    }
    for (int i = 0; i < n_args; i++) {
        py_set_lookup(o, items[i], true);
    }
    return o;
}

Damien's avatar
Damien committed
1240
1241
1242
1243
1244
py_obj_t rt_store_set(py_obj_t set, py_obj_t item) {
    py_set_lookup(set, item, true);
    return set;
}

1245
1246
1247
1248
1249
// unpacked items are stored in order into the array pointed to by items
void rt_unpack_sequence(py_obj_t seq_in, uint num, py_obj_t *items) {
    if (IS_O(seq_in, O_TUPLE) || IS_O(seq_in, O_LIST)) {
        py_obj_base_t *seq = seq_in;
        if (seq->u_tuple_list.len < num) {
1250
            nlr_jump(py_obj_new_exception_2(rt_q_ValueError, "need more than %d values to unpack", (void*)seq->u_tuple_list.len, NULL));
1251
        } else if (seq->u_tuple_list.len > num) {
1252
            nlr_jump(py_obj_new_exception_2(rt_q_ValueError, "too many values to unpack (expected %d)", (void*)(machine_uint_t)num, NULL));
1253
1254
1255
1256
        }
        memcpy(items, seq->u_tuple_list.items, num * sizeof(py_obj_t));
    } else {
        // TODO call rt_getiter and extract via rt_iternext
1257
        nlr_jump(py_obj_new_exception_2(rt_q_TypeError, "'%s' object is not iterable", py_obj_get_type_str(seq_in), NULL));
1258
1259
1260
    }
}

Damien's avatar
Damien committed
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
py_obj_t rt_build_map(int n_args) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_MAP;
    py_map_init(&o->u_map, MAP_PY_OBJ, n_args);
    return o;
}

py_obj_t rt_store_map(py_obj_t map, py_obj_t key, py_obj_t value) {
    assert(IS_O(map, O_MAP)); // should always be
    py_map_lookup(map, key, true)->value = value;
    return map;
}

py_obj_t build_bound_method(py_obj_t self, py_obj_t meth) {
    py_obj_base_t *o = m_new(py_obj_base_t, 1);
    o->kind = O_BOUND_METH;
    o->u_bound_meth.meth = meth;
    o->u_bound_meth.self = self;
    return o;
}

py_obj_t rt_load_attr(py_obj_t base, qstr attr) {
1283
    DEBUG_OP_printf("load attr %s\n", qstr_str(attr));
1284
    if (IS_O(base, O_LIST) && attr == rt_q_append) {
Damien's avatar
Damien committed
1285
        return build_bound_method(base, fun_list_append);
1286
    } else if (IS_O(base, O_LIST) && attr == rt_q_pop) {
1287
        return build_bound_method(base, fun_list_pop);
1288
    } else if (IS_O(base, O_LIST) && attr == rt_q_sort) {
1289
        return build_bound_method(base, fun_list_sort);
Damien's avatar
Damien committed
1290
1291
    } else if (IS_O(base, O_CLASS)) {
        py_obj_base_t *o = base;
1292
        py_map_elem_t *elem = py_qstr_map_lookup(o