runtime.c 52 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
132
133
134
135
136
137
138
139
140
141
142
143
144
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) {
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);
Damien's avatar
Damien committed
305
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("__repl_print__"), true)->value = rt_make_function_1(py_builtin___repl_print__);
306
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("print"), true)->value = rt_make_function_var(0, py_builtin_print);
307
    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
308
    py_qstr_map_lookup(&map_builtins, qstr_from_str_static("abs"), true)->value = rt_make_function_1(py_builtin_abs);
309
    py_qstr_map_lookup(&map_builtins, rt_q___build_class__, true)->value = rt_make_function_2(py_builtin___build_class__);
310
    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
311

Damien's avatar
Damien committed
312
    next_unique_code_id = 2; // 1 is reserved for the __main__ module scope
Damien's avatar
Damien committed
313
314
    unique_codes = NULL;

315
    fun_str_join = rt_make_function_2(rt_str_join);
316
    fun_str_format = rt_make_function_var(1, rt_str_format);
317
    fun_list_append = rt_make_function_2(rt_list_append);
318
319
    fun_list_pop = rt_make_function_2(rt_list_pop);
    fun_list_sort = rt_make_function_2(rt_list_sort);
320
    fun_gen_instance_next = rt_make_function_1(rt_gen_instance_next);
Damien's avatar
Damien committed
321

322
323
#ifdef WRITE_CODE
    fp_write_code = fopen("out-code", "wb");
324
#endif
Damien's avatar
Damien committed
325
326
}

327
void rt_deinit(void) {
328
329
330
#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fclose(fp_write_code);
Damien's avatar
Damien committed
331
    }
332
#endif
Damien's avatar
Damien committed
333
334
}

Damien's avatar
Damien committed
335
336
337
338
339
340
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
341
342
}

343
static void alloc_unique_codes(void) {
Damien's avatar
Damien committed
344
    if (unique_codes == NULL) {
345
        unique_codes = m_new(py_code_t, next_unique_code_id + 10); // XXX hack until we fix the REPL allocation problem
346
347
348
        for (int i = 0; i < next_unique_code_id; i++) {
            unique_codes[i].kind = PY_CODE_NONE;
        }
Damien's avatar
Damien committed
349
    }
350
351
}

Damien's avatar
Damien committed
352
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) {
353
354
355
356
357
    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;
358
    unique_codes[unique_code_id].n_locals = n_locals;
Damien's avatar
Damien committed
359
    unique_codes[unique_code_id].n_cells = n_cells;
360
361
    unique_codes[unique_code_id].n_stack = n_stack;
    unique_codes[unique_code_id].is_generator = is_generator;
362
363
364
    unique_codes[unique_code_id].u_byte.code = code;
    unique_codes[unique_code_id].u_byte.len = len;

Damien's avatar
Damien committed
365
    //printf("byte code: %d bytes\n", len);
366
367

#ifdef DEBUG_PRINT
368
    DEBUG_printf("assign byte code: id=%d code=%p len=%u n_args=%d\n", unique_code_id, code, len, n_args);
369
370
371
372
373
374
375
    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");
376
377
    extern void py_show_byte_code(const byte *code, int len);
    py_show_byte_code(code, len);
378
379
380
381
382
383
384
385

#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fwrite(code, len, 1, fp_write_code);
        fflush(fp_write_code);
    }
#endif
#endif
386
387
388
389
390
}

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

391
    assert(1 <= unique_code_id && unique_code_id < next_unique_code_id);
Damien's avatar
Damien committed
392
393
    unique_codes[unique_code_id].kind = PY_CODE_NATIVE;
    unique_codes[unique_code_id].n_args = n_args;
394
    unique_codes[unique_code_id].n_locals = 0;
Damien's avatar
Damien committed
395
    unique_codes[unique_code_id].n_cells = 0;
396
397
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
Damien's avatar
Damien committed
398
399
    unique_codes[unique_code_id].u_native.fun = fun;

400
401
    printf("native code: %d bytes\n", len);

402
#ifdef DEBUG_PRINT
Damien's avatar
Damien committed
403
404
405
406
407
408
409
410
411
412
    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");

413
414
415
416
#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
417
    }
418
419
#endif
#endif
Damien's avatar
Damien committed
420
421
}

422
423
424
425
426
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
427
    unique_codes[unique_code_id].n_args = n_args;
428
    unique_codes[unique_code_id].n_locals = 0;
Damien's avatar
Damien committed
429
    unique_codes[unique_code_id].n_cells = 0;
430
431
    unique_codes[unique_code_id].n_stack = 0;
    unique_codes[unique_code_id].is_generator = false;
432
    unique_codes[unique_code_id].u_inline_asm.fun = fun;
Damien's avatar
Damien committed
433

434
#ifdef DEBUG_PRINT
435
436
437
438
439
440
441
442
443
444
    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");

445
446
447
#ifdef WRITE_CODE
    if (fp_write_code != NULL) {
        fwrite(fun_data, len, 1, fp_write_code);
448
    }
449
450
#endif
#endif
Damien's avatar
Damien committed
451
452
}

Damien's avatar
Damien committed
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
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
#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) {
499
        nlr_jump(py_obj_new_exception_2(rt_q_SyntaxError, "invalid syntax for number", NULL, NULL));
Damien's avatar
Damien committed
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    }
    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
517
    nlr_jump(py_obj_new_exception_2(rt_q_SyntaxError, "decimal numbers not supported", NULL, NULL));
Damien's avatar
Damien committed
518
519
520
#endif
}

Damien's avatar
Damien committed
521
522
523
524
525
526
527
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
528
    DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
529
    py_map_elem_t *elem = py_qstr_map_lookup(map_locals, qstr, false);
Damien's avatar
Damien committed
530
    if (elem == NULL) {
531
        elem = py_qstr_map_lookup(map_globals, qstr, false);
Damien's avatar
Damien committed
532
        if (elem == NULL) {
533
534
            elem = py_qstr_map_lookup(&map_builtins, qstr, false);
            if (elem == NULL) {
535
                nlr_jump(py_obj_new_exception_2(rt_q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
536
            }
Damien's avatar
Damien committed
537
538
539
540
541
542
        }
    }
    return elem->value;
}

py_obj_t rt_load_global(qstr qstr) {
543
544
    // logic: search globals, builtins
    DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
545
    py_map_elem_t *elem = py_qstr_map_lookup(map_globals, qstr, false);
546
547
548
    if (elem == NULL) {
        elem = py_qstr_map_lookup(&map_builtins, qstr, false);
        if (elem == NULL) {
549
            nlr_jump(py_obj_new_exception_2(rt_q_NameError, "name '%s' is not defined", qstr_str(qstr), NULL));
550
551
552
        }
    }
    return elem->value;
Damien's avatar
Damien committed
553
554
}

555
py_obj_t rt_load_build_class(void) {
Damien's avatar
Damien committed
556
    DEBUG_OP_printf("load_build_class\n");
557
    py_map_elem_t *elem = py_qstr_map_lookup(&map_builtins, rt_q___build_class__, false);
Damien's avatar
Damien committed
558
559
560
561
562
563
564
    if (elem == NULL) {
        printf("name doesn't exist: __build_class__\n");
        assert(0);
    }
    return elem->value;
}

565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
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
589
void rt_store_name(qstr qstr, py_obj_t obj) {
590
    DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
591
    py_qstr_map_lookup(map_locals, qstr, true)->value = obj;
592
593
594
595
}

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

py_obj_t rt_unary_op(int op, py_obj_t arg) {
Damien's avatar
Damien committed
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    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;
620
            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
621
622
623
624
625
            default: assert(0); val = 0;
        }
        return py_obj_new_float(val);
#endif
    }
Damien's avatar
Damien committed
626
627
628
629
630
631
632
    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) {
633
634
635
636
637
638
        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
639
            // tuple/list load
640
641
            uint index = get_index(lhs, rhs);
            return ((py_obj_base_t*)lhs)->u_tuple_list.items[index];
Damien's avatar
Damien committed
642
643
644
645
        } else if (IS_O(lhs, O_MAP)) {
            // map load
            py_map_elem_t *elem = py_map_lookup(lhs, rhs, false);
            if (elem == NULL) {
646
                nlr_jump(py_obj_new_exception_2(rt_q_KeyError, "<value>", NULL, NULL));
Damien's avatar
Damien committed
647
648
649
            } else {
                return elem->value;
            }
Damien's avatar
Damien committed
650
651
652
653
        } else {
            assert(0);
        }
    } else if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
654
655
        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
656
        switch (op) {
657
            case RT_BINARY_OP_OR:
Damien's avatar
Damien committed
658
            case RT_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
659
            case RT_BINARY_OP_XOR:
Damien's avatar
Damien committed
660
            case RT_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
661
            case RT_BINARY_OP_AND:
Damien's avatar
Damien committed
662
            case RT_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
663
            case RT_BINARY_OP_LSHIFT:
Damien's avatar
Damien committed
664
            case RT_BINARY_OP_INPLACE_LSHIFT: lhs_val <<= rhs_val; break;
665
            case RT_BINARY_OP_RSHIFT:
Damien's avatar
Damien committed
666
            case RT_BINARY_OP_INPLACE_RSHIFT: lhs_val >>= rhs_val; break;
Damien's avatar
Damien committed
667
            case RT_BINARY_OP_ADD:
Damien's avatar
Damien committed
668
            case RT_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
669
            case RT_BINARY_OP_SUBTRACT:
Damien's avatar
Damien committed
670
            case RT_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
671
            case RT_BINARY_OP_MULTIPLY:
Damien's avatar
Damien committed
672
            case RT_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break;
673
            case RT_BINARY_OP_FLOOR_DIVIDE:
Damien's avatar
Damien committed
674
            case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: lhs_val /= rhs_val; break;
675
#if MICROPY_ENABLE_FLOAT
676
            case RT_BINARY_OP_TRUE_DIVIDE:
Damien's avatar
Damien committed
677
            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
678
#endif
679
680
681
682
            case RT_BINARY_OP_POWER:
            case RT_BINARY_OP_INPLACE_POWER:
                // TODO
                if (rhs_val == 2) {
Damien's avatar
Damien committed
683
                    lhs_val = lhs_val * lhs_val;
684
685
                    break;
                }
Damien's avatar
Damien committed
686
            default: printf("%d\n", op); assert(0);
Damien's avatar
Damien committed
687
        }
Damien's avatar
Damien committed
688
689
        if (fit_small_int(lhs_val)) {
            return TO_SMALL_INT(lhs_val);
Damien's avatar
Damien committed
690
        }
691
#if MICROPY_ENABLE_FLOAT
Damien's avatar
Damien committed
692
693
694
695
    } 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);
696
697
        switch (op) {
            case RT_BINARY_OP_ADD:
Damien's avatar
Damien committed
698
699
700
701
            case RT_BINARY_OP_INPLACE_ADD:
                lhs_real += rhs_real;
                lhs_imag += rhs_imag;
                break;
702
            case RT_BINARY_OP_SUBTRACT:
Damien's avatar
Damien committed
703
704
705
706
            case RT_BINARY_OP_INPLACE_SUBTRACT:
                lhs_real -= rhs_real;
                lhs_imag -= rhs_imag;
                break;
707
            case RT_BINARY_OP_MULTIPLY:
Damien's avatar
Damien committed
708
709
710
711
712
713
714
            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;
            }
715
716
717
718
            /* 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
719
            /* TODO
720
721
            case RT_BINARY_OP_TRUE_DIVIDE:
            case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: val = lhs_val / rhs_val; break;
Damien's avatar
Damien committed
722
723
            */
            default: printf("%d\n", op); assert(0);
724
        }
Damien's avatar
Damien committed
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
        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);
745
#endif
Damien's avatar
Damien committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
    } 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);
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781

    // 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
782
    if (IS_SMALL_INT(lhs) && IS_SMALL_INT(rhs)) {
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
        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
803
804
        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
805
806
        int cmp;
        switch (op) {
807
808
809
810
            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
811
812
813
814
815
816
817
818
            default: assert(0); cmp = 0;
        }
        if (cmp) {
            return py_const_true;
        } else {
            return py_const_false;
        }
    }
819
#endif
820
821

    // not implemented
Damien's avatar
Damien committed
822
823
824
825
826
    assert(0);
    return py_const_none;
}

py_obj_t rt_make_function_from_id(int unique_code_id) {
827
828
    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
829
830
831
832
833
834
        // 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) {
835
836
837
        case PY_CODE_BYTE:
            o->kind = O_FUN_BC;
            o->u_fun_bc.n_args = c->n_args;
Damien's avatar
Damien committed
838
            o->u_fun_bc.n_state = c->n_locals + c->n_cells + c->n_stack;
839
840
            o->u_fun_bc.code = c->u_byte.code;
            break;
Damien's avatar
Damien committed
841
842
843
844
845
846
847
848
849
        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;
850
851
852
853
        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
854
855
856
857
            break;
        default:
            assert(0);
    }
858
859
860
861
862
863

    // 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
864
        o2->u_gen_wrap.n_state = ((c->n_locals + c->n_cells) < 3 ? 3 : (c->n_locals + c->n_cells)) + c->n_stack;
865
866
867
868
        o2->u_gen_wrap.fun = o;
        o = o2;
    }

Damien's avatar
Damien committed
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
    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;
898
    o->u_fun.fun = code;
Damien's avatar
Damien committed
899
900
901
    return o;
}

902
903
904
905
906
907
908
909
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
910
911
912
913
914
915
916
917
918
919
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;
}

920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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);

940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
// 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);

958
#if MICROPY_ENABLE_FLOAT
959
960
            case O_FLOAT:
                // convert float to int (could also pass in float registers)
Damien's avatar
Damien committed
961
                return (machine_int_t)o->u_float;
962
#endif
963

964
            case O_TUPLE:
965
            case O_LIST:
966
967
                // 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;
968
969
970
971
972
973
974
975
976
977
978
979
980

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

981
982
983
// 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
984
985
    if (IS_O(fun, O_FUN_0)) {
        py_obj_base_t *o = fun;
986
987
988
989
990
        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
991
        return ((py_fun_0_t)o->u_fun.fun)();
992
993
994
995
996
997
998
999
1000

    } 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]);
For faster browsing, not all history is shown. View entire blame