runtime.c 49.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

Damien's avatar
Damien committed
27
28
29
30
#include <stdio.h>
#include <string.h>
#include <assert.h>

31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "py/nlr.h"
#include "py/parsehelper.h"
#include "py/parsenum.h"
#include "py/compile.h"
#include "py/objtuple.h"
#include "py/objlist.h"
#include "py/objmodule.h"
#include "py/objgenerator.h"
#include "py/smallint.h"
#include "py/runtime0.h"
#include "py/runtime.h"
#include "py/builtin.h"
#include "py/stackctrl.h"
#include "py/gc.h"
45

46
#if 0 // print debugging info
47
#define DEBUG_PRINT (1)
48
#define DEBUG_printf DEBUG_printf
49
#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
50
#else // don't print debugging info
51
52
#define DEBUG_printf(...) (void)0
#define DEBUG_OP_printf(...) (void)0
53
#endif
Damien's avatar
Damien committed
54

55
56
57
// pending exception object (MP_OBJ_NULL if not pending)
mp_obj_t mp_pending_exception;

58
// locals and globals need to be pointers because they can be the same in outer module scope
59
60
STATIC mp_obj_dict_t *dict_locals;
STATIC mp_obj_dict_t *dict_globals;
61

62
// dictionary for the __main__ module
63
STATIC mp_obj_dict_t dict_main;
64
65
66
67

const mp_obj_module_t mp_module___main__ = {
    .base = { &mp_type_module },
    .name = MP_QSTR___main__,
68
    .globals = (mp_obj_dict_t*)&dict_main,
69
70
};

71
72
73
74
#if MICROPY_CAN_OVERRIDE_BUILTINS
mp_obj_dict_t *mp_module_builtins_override_dict;
#endif

Damien George's avatar
Damien George committed
75
void mp_init(void) {
76
    qstr_init();
Paul Sokolovsky's avatar
Paul Sokolovsky committed
77
    mp_stack_ctrl_init();
78

79
80
81
    // no pending exceptions to start with
    mp_pending_exception = MP_OBJ_NULL;

82
83
84
85
#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
    mp_init_emergency_exception_buf();
#endif

86
    // call port specific initialization if any
87
88
89
90
#ifdef MICROPY_PORT_INIT_FUNC
    MICROPY_PORT_INIT_FUNC;
#endif

91
92
    // optimization disabled by default
    mp_optimise_value = 0;
93

94
95
    // init global module stuff
    mp_module_init();
96

97
    // initialise the __main__ module
98
99
    mp_obj_dict_init(&dict_main, 1);
    mp_obj_dict_store(&dict_main, MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
100
101

    // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
102
    dict_locals = dict_globals = &dict_main;
103
104
105
106
107

    #if MICROPY_CAN_OVERRIDE_BUILTINS
    // start with no extensions to builtins
    mp_module_builtins_override_dict = NULL;
    #endif
Damien's avatar
Damien committed
108
109
}

Damien George's avatar
Damien George committed
110
void mp_deinit(void) {
111
    //mp_obj_dict_free(&dict_main);
112
    mp_module_deinit();
stijn's avatar
stijn committed
113
114
115
116
117

    // call port specific deinitialization if any 
#ifdef MICROPY_PORT_INIT_FUNC
    MICROPY_PORT_DEINIT_FUNC;
#endif
Damien's avatar
Damien committed
118
119
}

120
121
mp_obj_t mp_load_const_int(qstr qstr) {
    DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
122
    mp_uint_t len;
123
124
125
126
    const byte* data = qstr_data(qstr, &len);
    return mp_parse_num_integer((const char*)data, len, 0);
}

Damien George's avatar
Damien George committed
127
mp_obj_t mp_load_const_dec(qstr qstr) {
Damien's avatar
Damien committed
128
    DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
129
    mp_uint_t len;
130
    const byte* data = qstr_data(qstr, &len);
131
    return mp_parse_num_decimal((const char*)data, len, true, false);
Damien's avatar
Damien committed
132
133
}

Damien George's avatar
Damien George committed
134
mp_obj_t mp_load_const_str(qstr qstr) {
Damien's avatar
Damien committed
135
    DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
136
    return MP_OBJ_NEW_QSTR(qstr);
Damien's avatar
Damien committed
137
138
}

Damien George's avatar
Damien George committed
139
mp_obj_t mp_load_const_bytes(qstr qstr) {
140
    DEBUG_OP_printf("load b'%s'\n", qstr_str(qstr));
141
    mp_uint_t len;
142
143
144
145
    const byte *data = qstr_data(qstr, &len);
    return mp_obj_new_bytes(data, len);
}

Damien George's avatar
Damien George committed
146
mp_obj_t mp_load_name(qstr qstr) {
Damien's avatar
Damien committed
147
    // logic: search locals, globals, builtins
148
    DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
149
    // If we're at the outer scope (locals == globals), dispatch to load_global right away
150
151
    if (dict_locals != dict_globals) {
        mp_map_elem_t *elem = mp_map_lookup(&dict_locals->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
152
153
154
        if (elem != NULL) {
            return elem->value;
        }
Damien's avatar
Damien committed
155
    }
156
    return mp_load_global(qstr);
Damien's avatar
Damien committed
157
158
}

Damien George's avatar
Damien George committed
159
mp_obj_t mp_load_global(qstr qstr) {
160
161
    // logic: search globals, builtins
    DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
162
    mp_map_elem_t *elem = mp_map_lookup(&dict_globals->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
163
    if (elem == NULL) {
164
165
166
167
168
169
170
171
172
173
        #if MICROPY_CAN_OVERRIDE_BUILTINS
        if (mp_module_builtins_override_dict != NULL) {
            // lookup in additional dynamic table of builtins first
            elem = mp_map_lookup(&mp_module_builtins_override_dict->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
            if (elem != NULL) {
                return elem->value;
            }
        }
        #endif
        elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
174
        if (elem == NULL) {
175
176
177
178
179
180
181
            if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
                nlr_raise(mp_obj_new_exception_msg(&mp_type_NameError,
                    "name not defined"));
            } else {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
                    "name '%s' is not defined", qstr_str(qstr)));
            }
182
183
184
        }
    }
    return elem->value;
Damien's avatar
Damien committed
185
186
}

Damien George's avatar
Damien George committed
187
mp_obj_t mp_load_build_class(void) {
Damien's avatar
Damien committed
188
    DEBUG_OP_printf("load_build_class\n");
189
190
191
192
193
194
195
196
197
    #if MICROPY_CAN_OVERRIDE_BUILTINS
    if (mp_module_builtins_override_dict != NULL) {
        // lookup in additional dynamic table of builtins first
        mp_map_elem_t *elem = mp_map_lookup(&mp_module_builtins_override_dict->map, MP_OBJ_NEW_QSTR(MP_QSTR___build_class__), MP_MAP_LOOKUP);
        if (elem != NULL) {
            return elem->value;
        }
    }
    #endif
198
    return (mp_obj_t)&mp_builtin___build_class___obj;
Damien's avatar
Damien committed
199
200
}

Damien George's avatar
Damien George committed
201
void mp_store_name(qstr qstr, mp_obj_t obj) {
202
    DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
203
    mp_obj_dict_store(dict_locals, MP_OBJ_NEW_QSTR(qstr), obj);
204
205
}

Damien George's avatar
Damien George committed
206
void mp_delete_name(qstr qstr) {
207
    DEBUG_OP_printf("delete name %s\n", qstr_str(qstr));
208
209
    // TODO convert KeyError to NameError if qstr not found
    mp_obj_dict_delete(dict_locals, MP_OBJ_NEW_QSTR(qstr));
210
211
}

Damien George's avatar
Damien George committed
212
void mp_store_global(qstr qstr, mp_obj_t obj) {
213
    DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qstr), obj);
214
    mp_obj_dict_store(dict_globals, MP_OBJ_NEW_QSTR(qstr), obj);
Damien's avatar
Damien committed
215
216
}

217
218
219
220
221
222
void mp_delete_global(qstr qstr) {
    DEBUG_OP_printf("delete global %s\n", qstr_str(qstr));
    // TODO convert KeyError to NameError if qstr not found
    mp_obj_dict_delete(dict_globals, MP_OBJ_NEW_QSTR(qstr));
}

223
mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
224
    DEBUG_OP_printf("unary " UINT_FMT " %p\n", op, arg);
225

226
    if (MP_OBJ_IS_SMALL_INT(arg)) {
227
        mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
Damien's avatar
Damien committed
228
        switch (op) {
Damien George's avatar
Damien George committed
229
            case MP_UNARY_OP_BOOL:
230
                return MP_BOOL(val != 0);
Damien George's avatar
Damien George committed
231
            case MP_UNARY_OP_POSITIVE:
232
                return arg;
Damien George's avatar
Damien George committed
233
            case MP_UNARY_OP_NEGATIVE:
234
235
236
237
238
239
                // check for overflow
                if (val == MP_SMALL_INT_MIN) {
                    return mp_obj_new_int(-val);
                } else {
                    return MP_OBJ_NEW_SMALL_INT(-val);
                }
Damien George's avatar
Damien George committed
240
            case MP_UNARY_OP_INVERT:
241
242
243
244
                return MP_OBJ_NEW_SMALL_INT(~val);
            default:
                assert(0);
                return arg;
245
        }
246
247
248
249
    } else {
        mp_obj_type_t *type = mp_obj_get_type(arg);
        if (type->unary_op != NULL) {
            mp_obj_t result = type->unary_op(op, arg);
250
            if (result != MP_OBJ_NULL) {
251
252
                return result;
            }
Damien's avatar
Damien committed
253
        }
254
255
256
257
258
259
260
261
262
        if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
                "unsupported type for operator"));
        } else {
            // TODO specify in error message what the operator is
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
                "bad operand type for unary operator: '%s'",
                mp_obj_get_type_str(arg)));
        }
Damien's avatar
Damien committed
263
    }
Damien's avatar
Damien committed
264
265
}

266
mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs) {
267
    DEBUG_OP_printf("binary " UINT_FMT " %p %p\n", op, lhs, rhs);
268
269
270
271
272
273
274
275
276
277

    // TODO correctly distinguish inplace operators for mutable objects
    // lookup logic that CPython uses for +=:
    //   check for implemented +=
    //   then check for implemented +
    //   then check for implemented seq.inplace_concat
    //   then check for implemented seq.concat
    //   then fail
    // note that list does not implement + or +=, so that inplace_concat is reached first for +=

278
    // deal with is
Damien George's avatar
Damien George committed
279
    if (op == MP_BINARY_OP_IS) {
280
281
282
        return MP_BOOL(lhs == rhs);
    }

283
    // deal with == and != for all types
Damien George's avatar
Damien George committed
284
    if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
285
        if (mp_obj_equal(lhs, rhs)) {
Damien George's avatar
Damien George committed
286
            if (op == MP_BINARY_OP_EQUAL) {
287
288
289
290
291
                return mp_const_true;
            } else {
                return mp_const_false;
            }
        } else {
Damien George's avatar
Damien George committed
292
            if (op == MP_BINARY_OP_EQUAL) {
293
294
295
296
297
298
299
300
                return mp_const_false;
            } else {
                return mp_const_true;
            }
        }
    }

    // deal with exception_match for all types
Damien George's avatar
Damien George committed
301
    if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
302
303
        // rhs must be issubclass(rhs, BaseException)
        if (mp_obj_is_exception_type(rhs)) {
304
            if (mp_obj_exception_match(lhs, rhs)) {
305
306
307
308
                return mp_const_true;
            } else {
                return mp_const_false;
            }
309
310
311
312
313
314
315
316
317
318
319
320
        } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
            mp_obj_tuple_t *tuple = rhs;
            for (mp_uint_t i = 0; i < tuple->len; i++) {
                rhs = tuple->items[i];
                if (!mp_obj_is_exception_type(rhs)) {
                    goto unsupported_op;
                }
                if (mp_obj_exception_match(lhs, rhs)) {
                    return mp_const_true;
                }
            }
            return mp_const_false;
321
        }
322
        goto unsupported_op;
323
324
    }

325
    if (MP_OBJ_IS_SMALL_INT(lhs)) {
326
        mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
327
        if (MP_OBJ_IS_SMALL_INT(rhs)) {
328
            mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
329
330
331
            // This is a binary operation: lhs_val op rhs_val
            // We need to be careful to handle overflow; see CERT INT32-C
            // Operations that can overflow:
332
333
            //      +       result always fits in mp_int_t, then handled by SMALL_INT check
            //      -       result always fits in mp_int_t, then handled by SMALL_INT check
334
            //      *       checked explicitly
335
336
            //      /       if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
            //      %       if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
337
            //      <<      checked explicitly
338
            switch (op) {
Damien George's avatar
Damien George committed
339
340
341
342
343
344
345
346
                case MP_BINARY_OP_OR:
                case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
                case MP_BINARY_OP_XOR:
                case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
                case MP_BINARY_OP_AND:
                case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
                case MP_BINARY_OP_LSHIFT:
                case MP_BINARY_OP_INPLACE_LSHIFT: {
347
348
                    if (rhs_val < 0) {
                        // negative shift not allowed
349
                        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
350
351
352
353
354
355
356
357
358
359
                    } else if (rhs_val >= BITS_PER_WORD || lhs_val > (MP_SMALL_INT_MAX >> rhs_val) || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
                        // left-shift will overflow, so use higher precision integer
                        lhs = mp_obj_new_int_from_ll(lhs_val);
                        goto generic_binary_op;
                    } else {
                        // use standard precision
                        lhs_val <<= rhs_val;
                    }
                    break;
                }
Damien George's avatar
Damien George committed
360
361
                case MP_BINARY_OP_RSHIFT:
                case MP_BINARY_OP_INPLACE_RSHIFT:
362
363
                    if (rhs_val < 0) {
                        // negative shift not allowed
364
                        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
365
366
                    } else {
                        // standard precision is enough for right-shift
367
368
369
370
371
                        if (rhs_val >= BITS_PER_WORD) {
                            // Shifting to big amounts is underfined behavior
                            // in C and is CPU-dependent; propagate sign bit.
                            rhs_val = BITS_PER_WORD - 1;
                        }
372
373
374
                        lhs_val >>= rhs_val;
                    }
                    break;
Damien George's avatar
Damien George committed
375
376
377
378
379
380
                case MP_BINARY_OP_ADD:
                case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
                case MP_BINARY_OP_SUBTRACT:
                case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
                case MP_BINARY_OP_MULTIPLY:
                case MP_BINARY_OP_INPLACE_MULTIPLY: {
381

382
                    // If long long type exists and is larger than mp_int_t, then
383
                    // we can use the following code to perform overflow-checked multiplication.
384
                    // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
385
386
387
388
389
390
391
392
                    #if 0
                    // compute result using long long precision
                    long long res = (long long)lhs_val * (long long)rhs_val;
                    if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
                        // result overflowed SMALL_INT, so return higher precision integer
                        return mp_obj_new_int_from_ll(res);
                    } else {
                        // use standard precision
393
                        lhs_val = (mp_int_t)res;
394
395
396
                    }
                    #endif

397
398
399
400
401
402
403
404
                    if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
                        // use higher precision
                        lhs = mp_obj_new_int_from_ll(lhs_val);
                        goto generic_binary_op;
                    } else {
                        // use standard precision
                        return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
                    }
405
406
                    break;
                }
Damien George's avatar
Damien George committed
407
408
                case MP_BINARY_OP_FLOOR_DIVIDE:
                case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
409
410
411
                    if (rhs_val == 0) {
                        goto zero_division;
                    }
412
                    lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
413
                    break;
414

415
                #if MICROPY_PY_BUILTINS_FLOAT
Damien George's avatar
Damien George committed
416
                case MP_BINARY_OP_TRUE_DIVIDE:
417
418
                case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
                    if (rhs_val == 0) {
419
                        goto zero_division;
420
421
                    }
                    return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
422
                #endif
423

Damien George's avatar
Damien George committed
424
                case MP_BINARY_OP_MODULO:
425
426
                case MP_BINARY_OP_INPLACE_MODULO: {
                    lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
427
428
                    break;
                }
429

Damien George's avatar
Damien George committed
430
431
                case MP_BINARY_OP_POWER:
                case MP_BINARY_OP_INPLACE_POWER:
432
                    if (rhs_val < 0) {
433
                        #if MICROPY_PY_BUILTINS_FLOAT
434
435
436
                        lhs = mp_obj_new_float(lhs_val);
                        goto generic_binary_op;
                        #else
437
                        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative power with no float support"));
438
439
                        #endif
                    } else {
440
                        mp_int_t ans = 1;
441
442
                        while (rhs_val > 0) {
                            if (rhs_val & 1) {
443
                                if (mp_small_int_mul_overflow(ans, lhs_val)) {
444
445
                                    goto power_overflow;
                                }
446
                                ans *= lhs_val;
447
448
449
                            }
                            if (rhs_val == 1) {
                                break;
450
451
                            }
                            rhs_val /= 2;
452
                            if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
453
454
                                goto power_overflow;
                            }
455
                            lhs_val *= lhs_val;
456
                        }
457
                        lhs_val = ans;
458
                    }
459
                    break;
460
461
462
463
464
465

                power_overflow:
                    // use higher precision
                    lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
                    goto generic_binary_op;

Damien George's avatar
Damien George committed
466
467
468
469
                case MP_BINARY_OP_LESS: return MP_BOOL(lhs_val < rhs_val); break;
                case MP_BINARY_OP_MORE: return MP_BOOL(lhs_val > rhs_val); break;
                case MP_BINARY_OP_LESS_EQUAL: return MP_BOOL(lhs_val <= rhs_val); break;
                case MP_BINARY_OP_MORE_EQUAL: return MP_BOOL(lhs_val >= rhs_val); break;
470

471
472
                default:
                    goto unsupported_op;
473
            }
474
            // TODO: We just should make mp_obj_new_int() inline and use that
475
            if (MP_SMALL_INT_FITS(lhs_val)) {
476
                return MP_OBJ_NEW_SMALL_INT(lhs_val);
477
478
            } else {
                return mp_obj_new_int(lhs_val);
479
            }
480
#if MICROPY_PY_BUILTINS_FLOAT
481
        } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_float)) {
482
483
484
485
486
487
            mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
            if (res == MP_OBJ_NULL) {
                goto unsupported_op;
            } else {
                return res;
            }
488
#if MICROPY_PY_BUILTINS_COMPLEX
489
        } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
490
491
492
493
494
495
            mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
            if (res == MP_OBJ_NULL) {
                goto unsupported_op;
            } else {
                return res;
            }
496
#endif
497
#endif
498
        }
499
    }
500

501
    /* deal with `in`
502
503
     *
     * NOTE `a in b` is `b.__contains__(a)`, hence why the generic dispatch
Damien George's avatar
Damien George committed
504
     * needs to go below with swapped arguments
505
     */
Damien George's avatar
Damien George committed
506
    if (op == MP_BINARY_OP_IN) {
507
508
509
        mp_obj_type_t *type = mp_obj_get_type(rhs);
        if (type->binary_op != NULL) {
            mp_obj_t res = type->binary_op(op, rhs, lhs);
510
            if (res != MP_OBJ_NULL) {
511
                return res;
John R. Lenton's avatar
John R. Lenton committed
512
            }
513
514
515
        }
        if (type->getiter != NULL) {
            /* second attempt, walk the iterator */
Damien George's avatar
Damien George committed
516
            mp_obj_t iter = mp_getiter(rhs);
517
            mp_obj_t next;
518
            while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
519
                if (mp_obj_equal(next, lhs)) {
520
                    return mp_const_true;
John R. Lenton's avatar
John R. Lenton committed
521
                }
522
            }
523
            return mp_const_false;
524
525
        }

526
527
528
529
530
531
532
        if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
                "object not iterable"));
        } else {
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
                "'%s' object is not iterable", mp_obj_get_type_str(rhs)));
        }
533
534
    }

535
    // generic binary_op supplied by type
536
537
538
    mp_obj_type_t *type;
generic_binary_op:
    type = mp_obj_get_type(lhs);
539
540
    if (type->binary_op != NULL) {
        mp_obj_t result = type->binary_op(op, lhs, rhs);
541
        if (result != MP_OBJ_NULL) {
542
            return result;
Damien's avatar
Damien committed
543
544
        }
    }
545

546
547
    // TODO implement dispatch for reverse binary ops

548
unsupported_op:
549
550
551
552
553
554
555
556
557
    if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
            "unsupported type for operator"));
    } else {
        // TODO specify in error message what the operator is
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
            "unsupported operand types for binary operator: '%s', '%s'",
            mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs)));
    }
558
559

zero_division:
560
    nlr_raise(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero"));
Damien's avatar
Damien committed
561
562
}

Damien George's avatar
Damien George committed
563
564
mp_obj_t mp_call_function_0(mp_obj_t fun) {
    return mp_call_function_n_kw(fun, 0, 0, NULL);
565
566
}

Damien George's avatar
Damien George committed
567
568
mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
    return mp_call_function_n_kw(fun, 1, 0, &arg);
569
570
}

Damien George's avatar
Damien George committed
571
mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
572
    mp_obj_t args[2];
573
574
    args[0] = arg1;
    args[1] = arg2;
Damien George's avatar
Damien George committed
575
    return mp_call_function_n_kw(fun, 2, 0, args);
576
577
}

578
// args contains, eg: arg0  arg1  key0  value0  key1  value1
579
mp_obj_t mp_call_function_n_kw(mp_obj_t fun_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
580
581
    // TODO improve this: fun object can specify its type and we parse here the arguments,
    // passing to the function arrays of fixed and keyword arguments
582

583
    DEBUG_OP_printf("calling function %p(n_args=" UINT_FMT ", n_kw=" UINT_FMT ", args=%p)\n", fun_in, n_args, n_kw, args);
584

585
586
587
588
589
    // get the type
    mp_obj_type_t *type = mp_obj_get_type(fun_in);

    // do the call
    if (type->call != NULL) {
590
        return type->call(fun_in, n_args, n_kw, args);
591
    }
592

593
594
595
596
597
598
599
    if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
            "object not callable"));
    } else {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
            "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
    }
600
601
}

602
603
// args contains: fun  self/NULL  arg(0)  ...  arg(n_args-2)  arg(n_args-1)  kw_key(0)  kw_val(0)  ... kw_key(n_kw-1)  kw_val(n_kw-1)
// if n_args==0 and n_kw==0 then there are only fun and self/NULL
604
mp_obj_t mp_call_method_n_kw(mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
605
    DEBUG_OP_printf("call method (fun=%p, self=%p, n_args=" UINT_FMT ", n_kw=" UINT_FMT ", args=%p)\n", args[0], args[1], n_args, n_kw, args);
606
    int adjust = (args[1] == NULL) ? 0 : 1;
Damien George's avatar
Damien George committed
607
    return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
608
609
}

610
mp_obj_t mp_call_method_n_kw_var(bool have_self, mp_uint_t n_args_n_kw, const mp_obj_t *args) {
611
612
613
614
615
616
617
    mp_obj_t fun = *args++;
    mp_obj_t self = MP_OBJ_NULL;
    if (have_self) {
        self = *args++; // may be MP_OBJ_NULL
    }
    uint n_args = n_args_n_kw & 0xff;
    uint n_kw = (n_args_n_kw >> 8) & 0xff;
618
619
    mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // map be MP_OBJ_NULL
    mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // map be MP_OBJ_NULL
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652

    DEBUG_OP_printf("call method var (fun=%p, self=%p, n_args=%u, n_kw=%u, args=%p, seq=%p, dict=%p)\n", fun, self, n_args, n_kw, args, pos_seq, kw_dict);

    // We need to create the following array of objects:
    //     args[0 .. n_args]  unpacked(pos_seq)  args[n_args .. n_args + 2 * n_kw]  unpacked(kw_dict)
    // TODO: optimize one day to avoid constructing new arg array? Will be hard.

    // The new args array
    mp_obj_t *args2;
    uint args2_alloc;
    uint args2_len = 0;

    // Try to get a hint for the size of the kw_dict
    uint kw_dict_len = 0;
    if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
        kw_dict_len = mp_obj_dict_len(kw_dict);
    }

    // Extract the pos_seq sequence to the new args array.
    // Note that it can be arbitrary iterator.
    if (pos_seq == MP_OBJ_NULL) {
        // no sequence

        // allocate memory for the new array of args
        args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
        args2 = m_new(mp_obj_t, args2_alloc);

        // copy the self
        if (self != MP_OBJ_NULL) {
            args2[args2_len++] = self;
        }

        // copy the fixed pos args
653
        mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
654
655
656
657
658
659
        args2_len += n_args;

    } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
        // optimise the case of a tuple and list

        // get the items
660
        mp_uint_t len;
661
662
663
664
665
666
667
668
669
670
671
672
673
        mp_obj_t *items;
        mp_obj_get_array(pos_seq, &len, &items);

        // allocate memory for the new array of args
        args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
        args2 = m_new(mp_obj_t, args2_alloc);

        // copy the self
        if (self != MP_OBJ_NULL) {
            args2[args2_len++] = self;
        }

        // copy the fixed and variable position args
674
        mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
        args2_len += n_args + len;

    } else {
        // generic iterator

        // allocate memory for the new array of args
        args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
        args2 = m_new(mp_obj_t, args2_alloc);

        // copy the self
        if (self != MP_OBJ_NULL) {
            args2[args2_len++] = self;
        }

        // copy the fixed position args
690
        mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
691
692
693
694

        // extract the variable position args from the iterator
        mp_obj_t iterable = mp_getiter(pos_seq);
        mp_obj_t item;
695
        while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
696
697
698
699
700
701
702
703
704
705
706
707
            if (args2_len >= args2_alloc) {
                args2 = m_renew(mp_obj_t, args2, args2_alloc, args2_alloc * 2);
                args2_alloc *= 2;
            }
            args2[args2_len++] = item;
        }
    }

    // The size of the args2 array now is the number of positional args.
    uint pos_args_len = args2_len;

    // Copy the fixed kw args.
708
    mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
709
710
711
712
713
714
715
716
717
718
    args2_len += 2 * n_kw;

    // Extract (key,value) pairs from kw_dict dictionary and append to args2.
    // Note that it can be arbitrary iterator.
    if (kw_dict == MP_OBJ_NULL) {
        // pass
    } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
        // dictionary
        mp_map_t *map = mp_obj_dict_get_map(kw_dict);
        assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above
719
720
        for (mp_uint_t i = 0; i < map->alloc; i++) {
            if (MP_MAP_SLOT_IS_FILLED(map, i)) {
721
722
723
724
725
726
727
728
729
730
731
                args2[args2_len++] = map->table[i].key;
                args2[args2_len++] = map->table[i].value;
            }
        }
    } else {
        // generic mapping
        // TODO is calling 'items' on the mapping the correct thing to do here?
        mp_obj_t dest[2];
        mp_load_method(kw_dict, MP_QSTR_items, dest);
        mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest));
        mp_obj_t item;
732
        while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
            if (args2_len + 1 >= args2_alloc) {
                uint new_alloc = args2_alloc * 2;
                if (new_alloc < 4) {
                    new_alloc = 4;
                }
                args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
                args2_alloc = new_alloc;
            }
            mp_obj_t *items;
            mp_obj_get_array_fixed_n(item, 2, &items);
            args2[args2_len++] = items[0];
            args2[args2_len++] = items[1];
        }
    }

    mp_obj_t res = mp_call_function_n_kw(fun, pos_args_len, (args2_len - pos_args_len) / 2, args2);
    m_del(mp_obj_t, args2, args2_alloc);

    return res;
}

754
// unpacked items are stored in reverse order into the array pointed to by items
755
void mp_unpack_sequence(mp_obj_t seq_in, mp_uint_t num, mp_obj_t *items) {
756
    mp_uint_t seq_len;
757
    if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
758
        mp_obj_t *seq_items;
759
        if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
760
761
762
            mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
        } else {
            mp_obj_list_get(seq_in, &seq_len, &seq_items);
763
        }
764
        if (seq_len < num) {
765
            goto too_short;
766
        } else if (seq_len > num) {
767
            goto too_long;
768
        }
769
        for (mp_uint_t i = 0; i < num; i++) {
770
771
            items[i] = seq_items[num - 1 - i];
        }
772
    } else {
Damien George's avatar
Damien George committed
773
        mp_obj_t iterable = mp_getiter(seq_in);
774
775

        for (seq_len = 0; seq_len < num; seq_len++) {
Damien George's avatar
Damien George committed
776
            mp_obj_t el = mp_iternext(iterable);
777
            if (el == MP_OBJ_STOP_ITERATION) {
778
779
780
781
                goto too_short;
            }
            items[num - 1 - seq_len] = el;
        }
782
        if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
783
784
            goto too_long;
        }
785
    }
786
787
788
    return;

too_short:
789
790
791
792
793
794
795
    if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
            "wrong number of values to unpack"));
    } else {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
            "need more than %d values to unpack", seq_len));
    }
796
too_long:
797
798
799
800
801
802
803
    if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
            "wrong number of values to unpack"));
    } else {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
            "too many values to unpack (expected %d)", num));
    }
804
805
}

806
// unpacked items are stored in reverse order into the array pointed to by items
807
808
809
void mp_unpack_ex(mp_obj_t seq_in, mp_uint_t num_in, mp_obj_t *items) {
    mp_uint_t num_left = num_in & 0xff;
    mp_uint_t num_right = (num_in >> 8) & 0xff;
810
    DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
811
    mp_uint_t seq_len;
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
    if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
        mp_obj_t *seq_items;
        if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
            mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
        } else {
            if (num_left == 0 && num_right == 0) {
                // *a, = b # sets a to b if b is a list
                items[0] = seq_in;
                return;
            }
            mp_obj_list_get(seq_in, &seq_len, &seq_items);
        }
        if (seq_len < num_left + num_right) {
            goto too_short;
        }
827
        for (mp_uint_t i = 0; i < num_right; i++) {
828
829
830
            items[i] = seq_items[seq_len - 1 - i];
        }
        items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
831
        for (mp_uint_t i = 0; i < num_left; i++) {
832
833
834
835
836
837
838
839
840
841
842
            items[num_right + 1 + i] = seq_items[num_left - 1 - i];
        }
    } else {
        // Generic iterable; this gets a bit messy: we unpack known left length to the
        // items destination array, then the rest to a dynamically created list.  Once the
        // iterable is exhausted, we take from this list for the right part of the items.
        // TODO Improve to waste less memory in the dynamically created list.
        mp_obj_t iterable = mp_getiter(seq_in);
        mp_obj_t item;
        for (seq_len = 0; seq_len < num_left; seq_len++) {
            item = mp_iternext(iterable);
843
            if (item == MP_OBJ_STOP_ITERATION) {
844
845
846
847
                goto too_short;
            }
            items[num_left + num_right + 1 - 1 - seq_len] = item;
        }
848
        mp_obj_list_t *rest = mp_obj_new_list(0, NULL);
849
        while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
850
851
            mp_obj_list_append(rest, item);
        }
852
        if (rest->len < num_right) {
853
854
855
            goto too_short;
        }
        items[num_right] = rest;
856
        for (mp_uint_t i = 0; i < num_right; i++) {
857
            items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
858
        }
859
        mp_obj_list_set_len(rest, rest->len - num_right);
860
861
862
863
    }
    return;

too_short:
864
865
866
867
868
869
870
    if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
            "wrong number of values to unpack"));
    } else {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
            "need more than %d values to unpack", seq_len));
    }
871
872
}

873
mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
874
    DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
875
    // use load_method
876
    mp_obj_t dest[2];
877
878
    mp_load_method(base, attr, dest);
    if (dest[1] == MP_OBJ_NULL) {
879
        // load_method returned just a normal attribute
880
        return dest[0];
881
882
883
    } else {
        // load_method returned a method, so build a bound method object
        return mp_obj_new_bound_meth(dest[0], dest[1]);
Damien's avatar
Damien committed
884
885
886
    }
}

887
888
889
// no attribute found, returns:     dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
// method attribute found, returns: dest[0] == <method>,    dest[1] == <self>
Damien George's avatar
Damien George committed
890
void mp_load_method_maybe(mp_obj_t base, qstr attr, mp_obj_t *dest) {
891
892
893
894
895
896
897
    // clear output to indicate no attribute/method found yet
    dest[0] = MP_OBJ_NULL;
    dest[1] = MP_OBJ_NULL;

    // get the type
    mp_obj_type_t *type = mp_obj_get_type(base);

Damien George's avatar
Damien George committed
898
899
    // look for built-in names
    if (0) {
900
#if MICROPY_CPYTHON_COMPAT
Damien George's avatar
Damien George committed
901
902
903
    } else if (attr == MP_QSTR___class__) {
        // a.__class__ is equivalent to type(a)
        dest[0] = type;
904
#endif
Damien George's avatar
Damien George committed
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921

    } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
        dest[0] = (mp_obj_t)&mp_builtin_next_obj;
        dest[1] = base;

    } else if (type->load_attr != NULL) {
        // this type can do its own load, so call it
        type->load_attr(base, attr, dest);

    } else if (type->locals_dict != NULL) {
        // generic method lookup
        // this is a lookup in the object (ie not class or type)
        assert(MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)); // Micro Python restriction, for now
        mp_map_t *locals_map = mp_obj_dict_get_map(type->locals_dict);
        mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
        if (elem != NULL) {
            // check if the methods are functions, static or class methods
922
            // see http://docs.python.org/3/howto/descriptor.html
Damien George's avatar
Damien George committed
923
924
925
926
927
928
929
            if (MP_OBJ_IS_TYPE(elem->value, &mp_type_staticmethod)) {
                // return just the function
                dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
            } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_classmethod)) {
                // return a bound method, with self being the type of this object
                dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
                dest[1] = mp_obj_get_type(base);
930
931
932
            } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_type)) {
                // Don't try to bind types
                dest[0] = elem->value;
Damien George's avatar
Damien George committed
933
934
935
936
937
938
939
            } else if (mp_obj_is_callable(elem->value)) {
                // return a bound method, with self being this object
                dest[0] = elem->value;
                dest[1] = base;
            } else {
                // class member is a value, so just return that value
                dest[0] = elem->value;
Damien's avatar
Damien committed
940
941
            }
        }
942
    }
943
944
}

Damien George's avatar
Damien George committed
945
void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
946
947
    DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));

Damien George's avatar
Damien George committed
948
    mp_load_method_maybe(base, attr, dest);
949

950
    if (dest[0] == MP_OBJ_NULL) {
951
        // no attribute/method called attr
952
953
954
        if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
                "no such attribute"));
955
        } else {
956
957
958
959
960
961
962
963
964
965
            // following CPython, we give a more detailed error message for type objects
            if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
                    "type object '%s' has no attribute '%s'",
                    qstr_str(((mp_obj_type_t*)base)->name), qstr_str(attr)));
            } else {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
                    "'%s' object has no attribute '%s'",
                    mp_obj_get_type_str(base), qstr_str(attr)));
            }
966
967
        }
    }
968
969
}

Damien George's avatar
Damien George committed
970
void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien's avatar
Damien committed
971
    DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
972
973
974
975
976
    mp_obj_type_t *type = mp_obj_get_type(base);
    if (type->store_attr != NULL) {
        if (type->store_attr(base, attr, value)) {
            return;
        }
977
    }
978
979
980
981
982
983
984
985
    if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
            "no such attribute"));
    } else {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
            "'%s' object has no attribute '%s'",
            mp_obj_get_type_str(base), qstr_str(attr)));
    }
986
987
}

Damien George's avatar
Damien George committed
988
mp_obj_t mp_getiter(mp_obj_t o_in) {
989
    assert(o_in);
990
991
    mp_obj_type_t *type = mp_obj_get_type(o_in);
    if (type->getiter != NULL) {
992
993
994
995
996
        mp_obj_t iter = type->getiter(o_in);
        if (iter == MP_OBJ_NULL) {
            goto not_iterable;
        }
        return iter;
997
    } else {
998
        // check for __iter__ method
999
        mp_obj_t dest[2];
Damien George's avatar
Damien George committed
1000
        mp_load_method_maybe(o_in, MP_QSTR___iter__, dest);
1001
        if (dest[0] != MP_OBJ_NULL) {
1002
            // __iter__ exists, call it and return its result
Damien George's avatar
Damien George committed
1003
            return mp_call_method_n_kw(0, 0, dest);
1004
        } else {
Damien George's avatar
Damien George committed
1005
            mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
1006
1007
1008
1009
1010
            if (dest[0] != MP_OBJ_NULL) {
                // __getitem__ exists, create an iterator
                return mp_obj_new_getitem_iter(dest);
            } else {
                // object not iterable
1011
not_iterable:
1012
1013
1014