1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2013, 2014 Damien P. George
7  * Copyright (c) 2014-2018 Paul Sokolovsky
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
32 
33 #include "py/parsenum.h"
34 #include "py/compile.h"
35 #include "py/objstr.h"
36 #include "py/objtuple.h"
37 #include "py/objlist.h"
38 #include "py/objtype.h"
39 #include "py/objmodule.h"
40 #include "py/objgenerator.h"
41 #include "py/smallint.h"
42 #include "py/runtime.h"
43 #include "py/builtin.h"
44 #include "py/stackctrl.h"
45 #include "py/gc.h"
46 
47 #if MICROPY_DEBUG_VERBOSE // print debugging info
48 #define DEBUG_PRINT (1)
49 #define DEBUG_printf DEBUG_printf
50 #define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
51 #else // don't print debugging info
52 #define DEBUG_printf(...) (void)0
53 #define DEBUG_OP_printf(...) (void)0
54 #endif
55 
56 const mp_obj_module_t mp_module___main__ = {
57     .base = { &mp_type_module },
58     .globals = (mp_obj_dict_t *)&MP_STATE_VM(dict_main),
59 };
60 
mp_init(void)61 void mp_init(void) {
62     qstr_init();
63 
64     // no pending exceptions to start with
65     MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL;
66     #if MICROPY_ENABLE_SCHEDULER
67     MP_STATE_VM(sched_state) = MP_SCHED_IDLE;
68     MP_STATE_VM(sched_idx) = 0;
69     MP_STATE_VM(sched_len) = 0;
70     #endif
71 
72     #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
73     mp_init_emergency_exception_buf();
74     #endif
75 
76     #if MICROPY_KBD_EXCEPTION
77     // initialise the exception object for raising KeyboardInterrupt
78     MP_STATE_VM(mp_kbd_exception).base.type = &mp_type_KeyboardInterrupt;
79     MP_STATE_VM(mp_kbd_exception).traceback_alloc = 0;
80     MP_STATE_VM(mp_kbd_exception).traceback_len = 0;
81     MP_STATE_VM(mp_kbd_exception).traceback_data = NULL;
82     MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj;
83     #endif
84 
85     #if MICROPY_ENABLE_COMPILER
86     // optimization disabled by default
87     MP_STATE_VM(mp_optimise_value) = 0;
88     #if MICROPY_EMIT_NATIVE
89     MP_STATE_VM(default_emit_opt) = MP_EMIT_OPT_NONE;
90     #endif
91     #endif
92 
93     // init global module dict
94     mp_obj_dict_init(&MP_STATE_VM(mp_loaded_modules_dict), MICROPY_LOADED_MODULES_DICT_SIZE);
95 
96     // initialise the __main__ module
97     mp_obj_dict_init(&MP_STATE_VM(dict_main), 1);
98     mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(dict_main)), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
99 
100     // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
101     mp_locals_set(&MP_STATE_VM(dict_main));
102     mp_globals_set(&MP_STATE_VM(dict_main));
103 
104     #if MICROPY_CAN_OVERRIDE_BUILTINS
105     // start with no extensions to builtins
106     MP_STATE_VM(mp_module_builtins_override_dict) = NULL;
107     #endif
108 
109     #if MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE
110     MP_STATE_VM(track_reloc_code_list) = MP_OBJ_NULL;
111     #endif
112 
113     #if MICROPY_PY_OS_DUPTERM
114     for (size_t i = 0; i < MICROPY_PY_OS_DUPTERM; ++i) {
115         MP_STATE_VM(dupterm_objs[i]) = MP_OBJ_NULL;
116     }
117     #endif
118 
119     #if MICROPY_VFS
120     // initialise the VFS sub-system
121     MP_STATE_VM(vfs_cur) = NULL;
122     MP_STATE_VM(vfs_mount_table) = NULL;
123     #endif
124 
125     #if MICROPY_PY_SYS_ATEXIT
126     MP_STATE_VM(sys_exitfunc) = mp_const_none;
127     #endif
128 
129     #if MICROPY_PY_SYS_SETTRACE
130     MP_STATE_THREAD(prof_trace_callback) = MP_OBJ_NULL;
131     MP_STATE_THREAD(prof_callback_is_executing) = false;
132     MP_STATE_THREAD(current_code_state) = NULL;
133     #endif
134 
135     #if MICROPY_PY_BLUETOOTH
136     MP_STATE_VM(bluetooth) = MP_OBJ_NULL;
137     #endif
138 
139     #if MICROPY_PY_THREAD_GIL
140     mp_thread_mutex_init(&MP_STATE_VM(gil_mutex));
141     #endif
142 
143     // call port specific initialization if any
144     #ifdef MICROPY_PORT_INIT_FUNC
145     MICROPY_PORT_INIT_FUNC;
146     #endif
147 
148     MP_THREAD_GIL_ENTER();
149 }
150 
mp_deinit(void)151 void mp_deinit(void) {
152     MP_THREAD_GIL_EXIT();
153 
154     // call port specific deinitialization if any
155     #ifdef MICROPY_PORT_DEINIT_FUNC
156     MICROPY_PORT_DEINIT_FUNC;
157     #endif
158 }
159 
mp_load_name(qstr qst)160 mp_obj_t mp_load_name(qstr qst) {
161     // logic: search locals, globals, builtins
162     DEBUG_OP_printf("load name %s\n", qstr_str(qst));
163     // If we're at the outer scope (locals == globals), dispatch to load_global right away
164     if (mp_locals_get() != mp_globals_get()) {
165         mp_map_elem_t *elem = mp_map_lookup(&mp_locals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
166         if (elem != NULL) {
167             return elem->value;
168         }
169     }
170     return mp_load_global(qst);
171 }
172 
mp_load_global(qstr qst)173 mp_obj_t mp_load_global(qstr qst) {
174     // logic: search globals, builtins
175     DEBUG_OP_printf("load global %s\n", qstr_str(qst));
176     mp_map_elem_t *elem = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
177     if (elem == NULL) {
178         #if MICROPY_CAN_OVERRIDE_BUILTINS
179         if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
180             // lookup in additional dynamic table of builtins first
181             elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
182             if (elem != NULL) {
183                 return elem->value;
184             }
185         }
186         #endif
187         elem = mp_map_lookup((mp_map_t *)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
188         if (elem == NULL) {
189             #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
190             mp_raise_msg(&mp_type_NameError, MP_ERROR_TEXT("name not defined"));
191             #else
192             mp_raise_msg_varg(&mp_type_NameError, MP_ERROR_TEXT("name '%q' isn't defined"), qst);
193             #endif
194         }
195     }
196     return elem->value;
197 }
198 
mp_load_build_class(void)199 mp_obj_t mp_load_build_class(void) {
200     DEBUG_OP_printf("load_build_class\n");
201     #if MICROPY_CAN_OVERRIDE_BUILTINS
202     if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
203         // lookup in additional dynamic table of builtins first
204         mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(MP_QSTR___build_class__), MP_MAP_LOOKUP);
205         if (elem != NULL) {
206             return elem->value;
207         }
208     }
209     #endif
210     return MP_OBJ_FROM_PTR(&mp_builtin___build_class___obj);
211 }
212 
mp_store_name(qstr qst,mp_obj_t obj)213 void mp_store_name(qstr qst, mp_obj_t obj) {
214     DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qst), obj);
215     mp_obj_dict_store(MP_OBJ_FROM_PTR(mp_locals_get()), MP_OBJ_NEW_QSTR(qst), obj);
216 }
217 
mp_delete_name(qstr qst)218 void mp_delete_name(qstr qst) {
219     DEBUG_OP_printf("delete name %s\n", qstr_str(qst));
220     // TODO convert KeyError to NameError if qst not found
221     mp_obj_dict_delete(MP_OBJ_FROM_PTR(mp_locals_get()), MP_OBJ_NEW_QSTR(qst));
222 }
223 
mp_store_global(qstr qst,mp_obj_t obj)224 void mp_store_global(qstr qst, mp_obj_t obj) {
225     DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qst), obj);
226     mp_obj_dict_store(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(qst), obj);
227 }
228 
mp_delete_global(qstr qst)229 void mp_delete_global(qstr qst) {
230     DEBUG_OP_printf("delete global %s\n", qstr_str(qst));
231     // TODO convert KeyError to NameError if qst not found
232     mp_obj_dict_delete(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(qst));
233 }
234 
mp_unary_op(mp_unary_op_t op,mp_obj_t arg)235 mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) {
236     DEBUG_OP_printf("unary " UINT_FMT " %q %p\n", op, mp_unary_op_method_name[op], arg);
237 
238     if (op == MP_UNARY_OP_NOT) {
239         // "not x" is the negative of whether "x" is true per Python semantics
240         return mp_obj_new_bool(mp_obj_is_true(arg) == 0);
241     } else if (mp_obj_is_small_int(arg)) {
242         mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
243         switch (op) {
244             case MP_UNARY_OP_BOOL:
245                 return mp_obj_new_bool(val != 0);
246             case MP_UNARY_OP_HASH:
247                 return arg;
248             case MP_UNARY_OP_POSITIVE:
249             case MP_UNARY_OP_INT:
250                 return arg;
251             case MP_UNARY_OP_NEGATIVE:
252                 // check for overflow
253                 if (val == MP_SMALL_INT_MIN) {
254                     return mp_obj_new_int(-val);
255                 } else {
256                     return MP_OBJ_NEW_SMALL_INT(-val);
257                 }
258             case MP_UNARY_OP_ABS:
259                 if (val >= 0) {
260                     return arg;
261                 } else if (val == MP_SMALL_INT_MIN) {
262                     // check for overflow
263                     return mp_obj_new_int(-val);
264                 } else {
265                     return MP_OBJ_NEW_SMALL_INT(-val);
266                 }
267             default:
268                 assert(op == MP_UNARY_OP_INVERT);
269                 return MP_OBJ_NEW_SMALL_INT(~val);
270         }
271     } else if (op == MP_UNARY_OP_HASH && mp_obj_is_str_or_bytes(arg)) {
272         // fast path for hashing str/bytes
273         GET_STR_HASH(arg, h);
274         if (h == 0) {
275             GET_STR_DATA_LEN(arg, data, len);
276             h = qstr_compute_hash(data, len);
277         }
278         return MP_OBJ_NEW_SMALL_INT(h);
279     } else {
280         const mp_obj_type_t *type = mp_obj_get_type(arg);
281         if (type->unary_op != NULL) {
282             mp_obj_t result = type->unary_op(op, arg);
283             if (result != MP_OBJ_NULL) {
284                 return result;
285             }
286         }
287         if (op == MP_UNARY_OP_BOOL) {
288             // Type doesn't have unary_op (or didn't handle MP_UNARY_OP_BOOL),
289             // so is implicitly True as this code path is impossible to reach
290             // if arg==mp_const_none.
291             return mp_const_true;
292         }
293         // With MP_UNARY_OP_INT, mp_unary_op() becomes a fallback for mp_obj_get_int().
294         // In this case provide a more focused error message to not confuse, e.g. chr(1.0)
295         #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
296         if (op == MP_UNARY_OP_INT) {
297             mp_raise_TypeError(MP_ERROR_TEXT("can't convert to int"));
298         } else {
299             mp_raise_TypeError(MP_ERROR_TEXT("unsupported type for operator"));
300         }
301         #else
302         if (op == MP_UNARY_OP_INT) {
303             mp_raise_msg_varg(&mp_type_TypeError,
304                 MP_ERROR_TEXT("can't convert %s to int"), mp_obj_get_type_str(arg));
305         } else {
306             mp_raise_msg_varg(&mp_type_TypeError,
307                 MP_ERROR_TEXT("unsupported type for %q: '%s'"),
308                 mp_unary_op_method_name[op], mp_obj_get_type_str(arg));
309         }
310         #endif
311     }
312 }
313 
mp_binary_op(mp_binary_op_t op,mp_obj_t lhs,mp_obj_t rhs)314 mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
315     DEBUG_OP_printf("binary " UINT_FMT " %q %p %p\n", op, mp_binary_op_method_name[op], lhs, rhs);
316 
317     // TODO correctly distinguish inplace operators for mutable objects
318     // lookup logic that CPython uses for +=:
319     //   check for implemented +=
320     //   then check for implemented +
321     //   then check for implemented seq.inplace_concat
322     //   then check for implemented seq.concat
323     //   then fail
324     // note that list does not implement + or +=, so that inplace_concat is reached first for +=
325 
326     // deal with is
327     if (op == MP_BINARY_OP_IS) {
328         return mp_obj_new_bool(lhs == rhs);
329     }
330 
331     // deal with == and != for all types
332     if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
333         // mp_obj_equal_not_equal supports a bunch of shortcuts
334         return mp_obj_equal_not_equal(op, lhs, rhs);
335     }
336 
337     // deal with exception_match for all types
338     if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
339         // rhs must be issubclass(rhs, BaseException)
340         if (mp_obj_is_exception_type(rhs)) {
341             if (mp_obj_exception_match(lhs, rhs)) {
342                 return mp_const_true;
343             } else {
344                 return mp_const_false;
345             }
346         } else if (mp_obj_is_type(rhs, &mp_type_tuple)) {
347             mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(rhs);
348             for (size_t i = 0; i < tuple->len; i++) {
349                 rhs = tuple->items[i];
350                 if (!mp_obj_is_exception_type(rhs)) {
351                     goto unsupported_op;
352                 }
353                 if (mp_obj_exception_match(lhs, rhs)) {
354                     return mp_const_true;
355                 }
356             }
357             return mp_const_false;
358         }
359         goto unsupported_op;
360     }
361 
362     if (mp_obj_is_small_int(lhs)) {
363         mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
364         if (mp_obj_is_small_int(rhs)) {
365             mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
366             // This is a binary operation: lhs_val op rhs_val
367             // We need to be careful to handle overflow; see CERT INT32-C
368             // Operations that can overflow:
369             //      +       result always fits in mp_int_t, then handled by SMALL_INT check
370             //      -       result always fits in mp_int_t, then handled by SMALL_INT check
371             //      *       checked explicitly
372             //      /       if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
373             //      %       if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
374             //      <<      checked explicitly
375             switch (op) {
376                 case MP_BINARY_OP_OR:
377                 case MP_BINARY_OP_INPLACE_OR:
378                     lhs_val |= rhs_val;
379                     break;
380                 case MP_BINARY_OP_XOR:
381                 case MP_BINARY_OP_INPLACE_XOR:
382                     lhs_val ^= rhs_val;
383                     break;
384                 case MP_BINARY_OP_AND:
385                 case MP_BINARY_OP_INPLACE_AND:
386                     lhs_val &= rhs_val;
387                     break;
388                 case MP_BINARY_OP_LSHIFT:
389                 case MP_BINARY_OP_INPLACE_LSHIFT: {
390                     if (rhs_val < 0) {
391                         // negative shift not allowed
392                         mp_raise_ValueError(MP_ERROR_TEXT("negative shift count"));
393                     } else if (rhs_val >= (mp_int_t)(sizeof(lhs_val) * MP_BITS_PER_BYTE)
394                                || lhs_val > (MP_SMALL_INT_MAX >> rhs_val)
395                                || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
396                         // left-shift will overflow, so use higher precision integer
397                         lhs = mp_obj_new_int_from_ll(lhs_val);
398                         goto generic_binary_op;
399                     } else {
400                         // use standard precision
401                         lhs_val = (mp_uint_t)lhs_val << rhs_val;
402                     }
403                     break;
404                 }
405                 case MP_BINARY_OP_RSHIFT:
406                 case MP_BINARY_OP_INPLACE_RSHIFT:
407                     if (rhs_val < 0) {
408                         // negative shift not allowed
409                         mp_raise_ValueError(MP_ERROR_TEXT("negative shift count"));
410                     } else {
411                         // standard precision is enough for right-shift
412                         if (rhs_val >= (mp_int_t)(sizeof(lhs_val) * MP_BITS_PER_BYTE)) {
413                             // Shifting to big amounts is underfined behavior
414                             // in C and is CPU-dependent; propagate sign bit.
415                             rhs_val = sizeof(lhs_val) * MP_BITS_PER_BYTE - 1;
416                         }
417                         lhs_val >>= rhs_val;
418                     }
419                     break;
420                 case MP_BINARY_OP_ADD:
421                 case MP_BINARY_OP_INPLACE_ADD:
422                     lhs_val += rhs_val;
423                     break;
424                 case MP_BINARY_OP_SUBTRACT:
425                 case MP_BINARY_OP_INPLACE_SUBTRACT:
426                     lhs_val -= rhs_val;
427                     break;
428                 case MP_BINARY_OP_MULTIPLY:
429                 case MP_BINARY_OP_INPLACE_MULTIPLY: {
430 
431                     // If long long type exists and is larger than mp_int_t, then
432                     // we can use the following code to perform overflow-checked multiplication.
433                     // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
434                     #if 0
435                     // compute result using long long precision
436                     long long res = (long long)lhs_val * (long long)rhs_val;
437                     if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
438                         // result overflowed SMALL_INT, so return higher precision integer
439                         return mp_obj_new_int_from_ll(res);
440                     } else {
441                         // use standard precision
442                         lhs_val = (mp_int_t)res;
443                     }
444                     #endif
445 
446                     if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
447                         // use higher precision
448                         lhs = mp_obj_new_int_from_ll(lhs_val);
449                         goto generic_binary_op;
450                     } else {
451                         // use standard precision
452                         return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
453                     }
454                 }
455                 case MP_BINARY_OP_FLOOR_DIVIDE:
456                 case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
457                     if (rhs_val == 0) {
458                         goto zero_division;
459                     }
460                     lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
461                     break;
462 
463                 #if MICROPY_PY_BUILTINS_FLOAT
464                 case MP_BINARY_OP_TRUE_DIVIDE:
465                 case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
466                     if (rhs_val == 0) {
467                         goto zero_division;
468                     }
469                     return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
470                 #endif
471 
472                 case MP_BINARY_OP_MODULO:
473                 case MP_BINARY_OP_INPLACE_MODULO: {
474                     if (rhs_val == 0) {
475                         goto zero_division;
476                     }
477                     lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
478                     break;
479                 }
480 
481                 case MP_BINARY_OP_POWER:
482                 case MP_BINARY_OP_INPLACE_POWER:
483                     if (rhs_val < 0) {
484                         #if MICROPY_PY_BUILTINS_FLOAT
485                         return mp_obj_float_binary_op(op, (mp_float_t)lhs_val, rhs);
486                         #else
487                         mp_raise_ValueError(MP_ERROR_TEXT("negative power with no float support"));
488                         #endif
489                     } else {
490                         mp_int_t ans = 1;
491                         while (rhs_val > 0) {
492                             if (rhs_val & 1) {
493                                 if (mp_small_int_mul_overflow(ans, lhs_val)) {
494                                     goto power_overflow;
495                                 }
496                                 ans *= lhs_val;
497                             }
498                             if (rhs_val == 1) {
499                                 break;
500                             }
501                             rhs_val /= 2;
502                             if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
503                                 goto power_overflow;
504                             }
505                             lhs_val *= lhs_val;
506                         }
507                         lhs_val = ans;
508                     }
509                     break;
510 
511                 power_overflow:
512                     // use higher precision
513                     lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
514                     goto generic_binary_op;
515 
516                 case MP_BINARY_OP_DIVMOD: {
517                     if (rhs_val == 0) {
518                         goto zero_division;
519                     }
520                     // to reduce stack usage we don't pass a temp array of the 2 items
521                     mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
522                     tuple->items[0] = MP_OBJ_NEW_SMALL_INT(mp_small_int_floor_divide(lhs_val, rhs_val));
523                     tuple->items[1] = MP_OBJ_NEW_SMALL_INT(mp_small_int_modulo(lhs_val, rhs_val));
524                     return MP_OBJ_FROM_PTR(tuple);
525                 }
526 
527                 case MP_BINARY_OP_LESS:
528                     return mp_obj_new_bool(lhs_val < rhs_val);
529                 case MP_BINARY_OP_MORE:
530                     return mp_obj_new_bool(lhs_val > rhs_val);
531                 case MP_BINARY_OP_LESS_EQUAL:
532                     return mp_obj_new_bool(lhs_val <= rhs_val);
533                 case MP_BINARY_OP_MORE_EQUAL:
534                     return mp_obj_new_bool(lhs_val >= rhs_val);
535 
536                 default:
537                     goto unsupported_op;
538             }
539             // This is an inlined version of mp_obj_new_int, for speed
540             if (MP_SMALL_INT_FITS(lhs_val)) {
541                 return MP_OBJ_NEW_SMALL_INT(lhs_val);
542             } else {
543                 return mp_obj_new_int_from_ll(lhs_val);
544             }
545         #if MICROPY_PY_BUILTINS_FLOAT
546         } else if (mp_obj_is_float(rhs)) {
547             mp_obj_t res = mp_obj_float_binary_op(op, (mp_float_t)lhs_val, rhs);
548             if (res == MP_OBJ_NULL) {
549                 goto unsupported_op;
550             } else {
551                 return res;
552             }
553         #endif
554         #if MICROPY_PY_BUILTINS_COMPLEX
555         } else if (mp_obj_is_type(rhs, &mp_type_complex)) {
556             mp_obj_t res = mp_obj_complex_binary_op(op, (mp_float_t)lhs_val, 0, rhs);
557             if (res == MP_OBJ_NULL) {
558                 goto unsupported_op;
559             } else {
560                 return res;
561             }
562         #endif
563         }
564     }
565 
566     // Convert MP_BINARY_OP_IN to MP_BINARY_OP_CONTAINS with swapped args.
567     if (op == MP_BINARY_OP_IN) {
568         op = MP_BINARY_OP_CONTAINS;
569         mp_obj_t temp = lhs;
570         lhs = rhs;
571         rhs = temp;
572     }
573 
574     // generic binary_op supplied by type
575     const mp_obj_type_t *type;
576 generic_binary_op:
577     type = mp_obj_get_type(lhs);
578     if (type->binary_op != NULL) {
579         mp_obj_t result = type->binary_op(op, lhs, rhs);
580         if (result != MP_OBJ_NULL) {
581             return result;
582         }
583     }
584 
585     #if MICROPY_PY_REVERSE_SPECIAL_METHODS
586     if (op >= MP_BINARY_OP_OR && op <= MP_BINARY_OP_POWER) {
587         mp_obj_t t = rhs;
588         rhs = lhs;
589         lhs = t;
590         op += MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
591         goto generic_binary_op;
592     } else if (op >= MP_BINARY_OP_REVERSE_OR) {
593         // Convert __rop__ back to __op__ for error message
594         mp_obj_t t = rhs;
595         rhs = lhs;
596         lhs = t;
597         op -= MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
598     }
599     #endif
600 
601     if (op == MP_BINARY_OP_CONTAINS) {
602         // If type didn't support containment then explicitly walk the iterator.
603         // mp_getiter will raise the appropriate exception if lhs is not iterable.
604         mp_obj_iter_buf_t iter_buf;
605         mp_obj_t iter = mp_getiter(lhs, &iter_buf);
606         mp_obj_t next;
607         while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
608             if (mp_obj_equal(next, rhs)) {
609                 return mp_const_true;
610             }
611         }
612         return mp_const_false;
613     }
614 
615 unsupported_op:
616     #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
617     mp_raise_TypeError(MP_ERROR_TEXT("unsupported type for operator"));
618     #else
619     mp_raise_msg_varg(&mp_type_TypeError,
620         MP_ERROR_TEXT("unsupported types for %q: '%s', '%s'"),
621         mp_binary_op_method_name[op], mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs));
622     #endif
623 
624 zero_division:
625     mp_raise_msg(&mp_type_ZeroDivisionError, MP_ERROR_TEXT("divide by zero"));
626 }
627 
mp_call_function_0(mp_obj_t fun)628 mp_obj_t mp_call_function_0(mp_obj_t fun) {
629     return mp_call_function_n_kw(fun, 0, 0, NULL);
630 }
631 
mp_call_function_1(mp_obj_t fun,mp_obj_t arg)632 mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
633     return mp_call_function_n_kw(fun, 1, 0, &arg);
634 }
635 
mp_call_function_2(mp_obj_t fun,mp_obj_t arg1,mp_obj_t arg2)636 mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
637     mp_obj_t args[2];
638     args[0] = arg1;
639     args[1] = arg2;
640     return mp_call_function_n_kw(fun, 2, 0, args);
641 }
642 
643 // args contains, eg: arg0  arg1  key0  value0  key1  value1
mp_call_function_n_kw(mp_obj_t fun_in,size_t n_args,size_t n_kw,const mp_obj_t * args)644 mp_obj_t mp_call_function_n_kw(mp_obj_t fun_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
645     // TODO improve this: fun object can specify its type and we parse here the arguments,
646     // passing to the function arrays of fixed and keyword arguments
647 
648     DEBUG_OP_printf("calling function %p(n_args=" UINT_FMT ", n_kw=" UINT_FMT ", args=%p)\n", fun_in, n_args, n_kw, args);
649 
650     // get the type
651     const mp_obj_type_t *type = mp_obj_get_type(fun_in);
652 
653     // do the call
654     if (type->call != NULL) {
655         return type->call(fun_in, n_args, n_kw, args);
656     }
657 
658     #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
659     mp_raise_TypeError(MP_ERROR_TEXT("object not callable"));
660     #else
661     mp_raise_msg_varg(&mp_type_TypeError,
662         MP_ERROR_TEXT("'%s' object isn't callable"), mp_obj_get_type_str(fun_in));
663     #endif
664 }
665 
666 // 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)
667 // if n_args==0 and n_kw==0 then there are only fun and self/NULL
mp_call_method_n_kw(size_t n_args,size_t n_kw,const mp_obj_t * args)668 mp_obj_t mp_call_method_n_kw(size_t n_args, size_t n_kw, const mp_obj_t *args) {
669     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);
670     int adjust = (args[1] == MP_OBJ_NULL) ? 0 : 1;
671     return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
672 }
673 
674 // This function only needs to be exposed externally when in stackless mode.
675 #if !MICROPY_STACKLESS
676 STATIC
677 #endif
mp_call_prepare_args_n_kw_var(bool have_self,size_t n_args_n_kw,const mp_obj_t * args,mp_call_args_t * out_args)678 void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args, mp_call_args_t *out_args) {
679     mp_obj_t fun = *args++;
680     mp_obj_t self = MP_OBJ_NULL;
681     if (have_self) {
682         self = *args++; // may be MP_OBJ_NULL
683     }
684     uint n_args = n_args_n_kw & 0xff;
685     uint n_kw = (n_args_n_kw >> 8) & 0xff;
686     mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // may be MP_OBJ_NULL
687     mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // may be MP_OBJ_NULL
688 
689     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);
690 
691     // We need to create the following array of objects:
692     //     args[0 .. n_args]  unpacked(pos_seq)  args[n_args .. n_args + 2 * n_kw]  unpacked(kw_dict)
693     // TODO: optimize one day to avoid constructing new arg array? Will be hard.
694 
695     // The new args array
696     mp_obj_t *args2;
697     uint args2_alloc;
698     uint args2_len = 0;
699 
700     // Try to get a hint for the size of the kw_dict
701     uint kw_dict_len = 0;
702     if (kw_dict != MP_OBJ_NULL && mp_obj_is_type(kw_dict, &mp_type_dict)) {
703         kw_dict_len = mp_obj_dict_len(kw_dict);
704     }
705 
706     // Extract the pos_seq sequence to the new args array.
707     // Note that it can be arbitrary iterator.
708     if (pos_seq == MP_OBJ_NULL) {
709         // no sequence
710 
711         // allocate memory for the new array of args
712         args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
713         args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
714 
715         // copy the self
716         if (self != MP_OBJ_NULL) {
717             args2[args2_len++] = self;
718         }
719 
720         // copy the fixed pos args
721         mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
722         args2_len += n_args;
723 
724     } else if (mp_obj_is_type(pos_seq, &mp_type_tuple) || mp_obj_is_type(pos_seq, &mp_type_list)) {
725         // optimise the case of a tuple and list
726 
727         // get the items
728         size_t len;
729         mp_obj_t *items;
730         mp_obj_get_array(pos_seq, &len, &items);
731 
732         // allocate memory for the new array of args
733         args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
734         args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
735 
736         // copy the self
737         if (self != MP_OBJ_NULL) {
738             args2[args2_len++] = self;
739         }
740 
741         // copy the fixed and variable position args
742         mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
743         args2_len += n_args + len;
744 
745     } else {
746         // generic iterator
747 
748         // allocate memory for the new array of args
749         args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
750         args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
751 
752         // copy the self
753         if (self != MP_OBJ_NULL) {
754             args2[args2_len++] = self;
755         }
756 
757         // copy the fixed position args
758         mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
759         args2_len += n_args;
760 
761         // extract the variable position args from the iterator
762         mp_obj_iter_buf_t iter_buf;
763         mp_obj_t iterable = mp_getiter(pos_seq, &iter_buf);
764         mp_obj_t item;
765         while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
766             if (args2_len >= args2_alloc) {
767                 args2 = mp_nonlocal_realloc(args2, args2_alloc * sizeof(mp_obj_t), args2_alloc * 2 * sizeof(mp_obj_t));
768                 args2_alloc *= 2;
769             }
770             args2[args2_len++] = item;
771         }
772     }
773 
774     // The size of the args2 array now is the number of positional args.
775     uint pos_args_len = args2_len;
776 
777     // Copy the fixed kw args.
778     mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
779     args2_len += 2 * n_kw;
780 
781     // Extract (key,value) pairs from kw_dict dictionary and append to args2.
782     // Note that it can be arbitrary iterator.
783     if (kw_dict == MP_OBJ_NULL) {
784         // pass
785     } else if (mp_obj_is_type(kw_dict, &mp_type_dict)) {
786         // dictionary
787         mp_map_t *map = mp_obj_dict_get_map(kw_dict);
788         assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above
789         for (size_t i = 0; i < map->alloc; i++) {
790             if (mp_map_slot_is_filled(map, i)) {
791                 // the key must be a qstr, so intern it if it's a string
792                 mp_obj_t key = map->table[i].key;
793                 if (!mp_obj_is_qstr(key)) {
794                     key = mp_obj_str_intern_checked(key);
795                 }
796                 args2[args2_len++] = key;
797                 args2[args2_len++] = map->table[i].value;
798             }
799         }
800     } else {
801         // generic mapping:
802         // - call keys() to get an iterable of all keys in the mapping
803         // - call __getitem__ for each key to get the corresponding value
804 
805         // get the keys iterable
806         mp_obj_t dest[3];
807         mp_load_method(kw_dict, MP_QSTR_keys, dest);
808         mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest), NULL);
809 
810         mp_obj_t key;
811         while ((key = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
812             // expand size of args array if needed
813             if (args2_len + 1 >= args2_alloc) {
814                 uint new_alloc = args2_alloc * 2;
815                 if (new_alloc < 4) {
816                     new_alloc = 4;
817                 }
818                 args2 = mp_nonlocal_realloc(args2, args2_alloc * sizeof(mp_obj_t), new_alloc * sizeof(mp_obj_t));
819                 args2_alloc = new_alloc;
820             }
821 
822             // the key must be a qstr, so intern it if it's a string
823             if (!mp_obj_is_qstr(key)) {
824                 key = mp_obj_str_intern_checked(key);
825             }
826 
827             // get the value corresponding to the key
828             mp_load_method(kw_dict, MP_QSTR___getitem__, dest);
829             dest[2] = key;
830             mp_obj_t value = mp_call_method_n_kw(1, 0, dest);
831 
832             // store the key/value pair in the argument array
833             args2[args2_len++] = key;
834             args2[args2_len++] = value;
835         }
836     }
837 
838     out_args->fun = fun;
839     out_args->args = args2;
840     out_args->n_args = pos_args_len;
841     out_args->n_kw = (args2_len - pos_args_len) / 2;
842     out_args->n_alloc = args2_alloc;
843 }
844 
mp_call_method_n_kw_var(bool have_self,size_t n_args_n_kw,const mp_obj_t * args)845 mp_obj_t mp_call_method_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args) {
846     mp_call_args_t out_args;
847     mp_call_prepare_args_n_kw_var(have_self, n_args_n_kw, args, &out_args);
848 
849     mp_obj_t res = mp_call_function_n_kw(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args);
850     mp_nonlocal_free(out_args.args, out_args.n_alloc * sizeof(mp_obj_t));
851 
852     return res;
853 }
854 
855 // unpacked items are stored in reverse order into the array pointed to by items
mp_unpack_sequence(mp_obj_t seq_in,size_t num,mp_obj_t * items)856 void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) {
857     size_t seq_len;
858     if (mp_obj_is_type(seq_in, &mp_type_tuple) || mp_obj_is_type(seq_in, &mp_type_list)) {
859         mp_obj_t *seq_items;
860         mp_obj_get_array(seq_in, &seq_len, &seq_items);
861         if (seq_len < num) {
862             goto too_short;
863         } else if (seq_len > num) {
864             goto too_long;
865         }
866         for (size_t i = 0; i < num; i++) {
867             items[i] = seq_items[num - 1 - i];
868         }
869     } else {
870         mp_obj_iter_buf_t iter_buf;
871         mp_obj_t iterable = mp_getiter(seq_in, &iter_buf);
872 
873         for (seq_len = 0; seq_len < num; seq_len++) {
874             mp_obj_t el = mp_iternext(iterable);
875             if (el == MP_OBJ_STOP_ITERATION) {
876                 goto too_short;
877             }
878             items[num - 1 - seq_len] = el;
879         }
880         if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
881             goto too_long;
882         }
883     }
884     return;
885 
886 too_short:
887     #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
888     mp_raise_ValueError(MP_ERROR_TEXT("wrong number of values to unpack"));
889     #else
890     mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("need more than %d values to unpack"), (int)seq_len);
891     #endif
892 too_long:
893     #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
894     mp_raise_ValueError(MP_ERROR_TEXT("wrong number of values to unpack"));
895     #else
896     mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("too many values to unpack (expected %d)"), (int)num);
897     #endif
898 }
899 
900 // unpacked items are stored in reverse order into the array pointed to by items
mp_unpack_ex(mp_obj_t seq_in,size_t num_in,mp_obj_t * items)901 void mp_unpack_ex(mp_obj_t seq_in, size_t num_in, mp_obj_t *items) {
902     size_t num_left = num_in & 0xff;
903     size_t num_right = (num_in >> 8) & 0xff;
904     DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
905     size_t seq_len;
906     if (mp_obj_is_type(seq_in, &mp_type_tuple) || mp_obj_is_type(seq_in, &mp_type_list)) {
907         // Make the seq variable volatile so the compiler keeps a reference to it,
908         // since if it's a tuple then seq_items points to the interior of the GC cell
909         // and mp_obj_new_list may trigger a GC which doesn't trace this and reclaims seq.
910         volatile mp_obj_t seq = seq_in;
911         mp_obj_t *seq_items;
912         mp_obj_get_array(seq, &seq_len, &seq_items);
913         if (seq_len < num_left + num_right) {
914             goto too_short;
915         }
916         for (size_t i = 0; i < num_right; i++) {
917             items[i] = seq_items[seq_len - 1 - i];
918         }
919         items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
920         for (size_t i = 0; i < num_left; i++) {
921             items[num_right + 1 + i] = seq_items[num_left - 1 - i];
922         }
923         seq = MP_OBJ_NULL;
924     } else {
925         // Generic iterable; this gets a bit messy: we unpack known left length to the
926         // items destination array, then the rest to a dynamically created list.  Once the
927         // iterable is exhausted, we take from this list for the right part of the items.
928         // TODO Improve to waste less memory in the dynamically created list.
929         mp_obj_t iterable = mp_getiter(seq_in, NULL);
930         mp_obj_t item;
931         for (seq_len = 0; seq_len < num_left; seq_len++) {
932             item = mp_iternext(iterable);
933             if (item == MP_OBJ_STOP_ITERATION) {
934                 goto too_short;
935             }
936             items[num_left + num_right + 1 - 1 - seq_len] = item;
937         }
938         mp_obj_list_t *rest = MP_OBJ_TO_PTR(mp_obj_new_list(0, NULL));
939         while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
940             mp_obj_list_append(MP_OBJ_FROM_PTR(rest), item);
941         }
942         if (rest->len < num_right) {
943             goto too_short;
944         }
945         items[num_right] = MP_OBJ_FROM_PTR(rest);
946         for (size_t i = 0; i < num_right; i++) {
947             items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
948         }
949         mp_obj_list_set_len(MP_OBJ_FROM_PTR(rest), rest->len - num_right);
950     }
951     return;
952 
953 too_short:
954     #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
955     mp_raise_ValueError(MP_ERROR_TEXT("wrong number of values to unpack"));
956     #else
957     mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("need more than %d values to unpack"), (int)seq_len);
958     #endif
959 }
960 
mp_load_attr(mp_obj_t base,qstr attr)961 mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
962     DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
963     // use load_method
964     mp_obj_t dest[2];
965     mp_load_method(base, attr, dest);
966     if (dest[1] == MP_OBJ_NULL) {
967         // load_method returned just a normal attribute
968         return dest[0];
969     } else {
970         // load_method returned a method, so build a bound method object
971         return mp_obj_new_bound_meth(dest[0], dest[1]);
972     }
973 }
974 
975 #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
976 
977 // The following "checked fun" type is local to the mp_convert_member_lookup
978 // function, and serves to check that the first argument to a builtin function
979 // has the correct type.
980 
981 typedef struct _mp_obj_checked_fun_t {
982     mp_obj_base_t base;
983     const mp_obj_type_t *type;
984     mp_obj_t fun;
985 } mp_obj_checked_fun_t;
986 
checked_fun_call(mp_obj_t self_in,size_t n_args,size_t n_kw,const mp_obj_t * args)987 STATIC mp_obj_t checked_fun_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
988     mp_obj_checked_fun_t *self = MP_OBJ_TO_PTR(self_in);
989     if (n_args > 0) {
990         const mp_obj_type_t *arg0_type = mp_obj_get_type(args[0]);
991         if (arg0_type != self->type) {
992             #if MICROPY_ERROR_REPORTING != MICROPY_ERROR_REPORTING_DETAILED
993             mp_raise_TypeError(MP_ERROR_TEXT("argument has wrong type"));
994             #else
995             mp_raise_msg_varg(&mp_type_TypeError,
996                 MP_ERROR_TEXT("argument should be a '%q' not a '%q'"), self->type->name, arg0_type->name);
997             #endif
998         }
999     }
1000     return mp_call_function_n_kw(self->fun, n_args, n_kw, args);
1001 }
1002 
1003 STATIC const mp_obj_type_t mp_type_checked_fun = {
1004     { &mp_type_type },
1005     .flags = MP_TYPE_FLAG_BINDS_SELF,
1006     .name = MP_QSTR_function,
1007     .call = checked_fun_call,
1008 };
1009 
mp_obj_new_checked_fun(const mp_obj_type_t * type,mp_obj_t fun)1010 STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) {
1011     mp_obj_checked_fun_t *o = m_new_obj(mp_obj_checked_fun_t);
1012     o->base.type = &mp_type_checked_fun;
1013     o->type = type;
1014     o->fun = fun;
1015     return MP_OBJ_FROM_PTR(o);
1016 }
1017 
1018 #endif // MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
1019 
1020 // Given a member that was extracted from an instance, convert it correctly
1021 // and put the result in the dest[] array for a possible method call.
1022 // Conversion means dealing with static/class methods, callables, and values.
1023 // see http://docs.python.org/3/howto/descriptor.html
1024 // and also https://mail.python.org/pipermail/python-dev/2015-March/138950.html
mp_convert_member_lookup(mp_obj_t self,const mp_obj_type_t * type,mp_obj_t member,mp_obj_t * dest)1025 void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) {
1026     if (mp_obj_is_obj(member)) {
1027         const mp_obj_type_t *m_type = ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type;
1028         if (m_type->flags & MP_TYPE_FLAG_BINDS_SELF) {
1029             // `member` is a function that binds self as its first argument.
1030             if (m_type->flags & MP_TYPE_FLAG_BUILTIN_FUN) {
1031                 // `member` is a built-in function, which has special behaviour.
1032                 if (mp_obj_is_instance_type(type)) {
1033                     // Built-in functions on user types always behave like a staticmethod.
1034                     dest[0] = member;
1035                 }
1036                 #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
1037                 else if (self == MP_OBJ_NULL && type != &mp_type_object) {
1038                     // `member` is a built-in method without a first argument, so wrap
1039                     // it in a type checker that will check self when it's supplied.
1040                     // Note that object will do its own checking so shouldn't be wrapped.
1041                     dest[0] = mp_obj_new_checked_fun(type, member);
1042                 }
1043                 #endif
1044                 else {
1045                     // Return a (built-in) bound method, with self being this object.
1046                     dest[0] = member;
1047                     dest[1] = self;
1048                 }
1049             } else {
1050                 // Return a bound method, with self being this object.
1051                 dest[0] = member;
1052                 dest[1] = self;
1053             }
1054         } else if (m_type == &mp_type_staticmethod) {
1055             // `member` is a staticmethod, return the function that it wraps.
1056             dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun;
1057         } else if (m_type == &mp_type_classmethod) {
1058             // `member` is a classmethod, return a bound method with self being the type of
1059             // this object.  This type should be the type of the original instance, not the
1060             // base type (which is what is passed in the `type` argument to this function).
1061             if (self != MP_OBJ_NULL) {
1062                 type = mp_obj_get_type(self);
1063             }
1064             dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun;
1065             dest[1] = MP_OBJ_FROM_PTR(type);
1066         } else {
1067             // `member` is a value, so just return that value.
1068             dest[0] = member;
1069         }
1070     } else {
1071         // `member` is a value, so just return that value.
1072         dest[0] = member;
1073     }
1074 }
1075 
1076 // no attribute found, returns:     dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
1077 // normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
1078 // method attribute found, returns: dest[0] == <method>,    dest[1] == <self>
mp_load_method_maybe(mp_obj_t obj,qstr attr,mp_obj_t * dest)1079 void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) {
1080     // clear output to indicate no attribute/method found yet
1081     dest[0] = MP_OBJ_NULL;
1082     dest[1] = MP_OBJ_NULL;
1083 
1084     // get the type
1085     const mp_obj_type_t *type = mp_obj_get_type(obj);
1086 
1087     // look for built-in names
1088     #if MICROPY_CPYTHON_COMPAT
1089     if (attr == MP_QSTR___class__) {
1090         // a.__class__ is equivalent to type(a)
1091         dest[0] = MP_OBJ_FROM_PTR(type);
1092         return;
1093     }
1094     #endif
1095 
1096     if (attr == MP_QSTR___next__ && type->iternext != NULL) {
1097         dest[0] = MP_OBJ_FROM_PTR(&mp_builtin_next_obj);
1098         dest[1] = obj;
1099 
1100     } else if (type->attr != NULL) {
1101         // this type can do its own load, so call it
1102         type->attr(obj, attr, dest);
1103 
1104     } else if (type->locals_dict != NULL) {
1105         // generic method lookup
1106         // this is a lookup in the object (ie not class or type)
1107         assert(type->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now
1108         mp_map_t *locals_map = &type->locals_dict->map;
1109         mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
1110         if (elem != NULL) {
1111             mp_convert_member_lookup(obj, type, elem->value, dest);
1112         }
1113     }
1114 }
1115 
mp_load_method(mp_obj_t base,qstr attr,mp_obj_t * dest)1116 void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
1117     DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
1118 
1119     mp_load_method_maybe(base, attr, dest);
1120 
1121     if (dest[0] == MP_OBJ_NULL) {
1122         // no attribute/method called attr
1123         #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
1124         mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("no such attribute"));
1125         #else
1126         // following CPython, we give a more detailed error message for type objects
1127         if (mp_obj_is_type(base, &mp_type_type)) {
1128             mp_raise_msg_varg(&mp_type_AttributeError,
1129                 MP_ERROR_TEXT("type object '%q' has no attribute '%q'"),
1130                 ((mp_obj_type_t *)MP_OBJ_TO_PTR(base))->name, attr);
1131         } else {
1132             mp_raise_msg_varg(&mp_type_AttributeError,
1133                 MP_ERROR_TEXT("'%s' object has no attribute '%q'"),
1134                 mp_obj_get_type_str(base), attr);
1135         }
1136         #endif
1137     }
1138 }
1139 
1140 // Acts like mp_load_method_maybe but catches AttributeError, and all other exceptions if requested
mp_load_method_protected(mp_obj_t obj,qstr attr,mp_obj_t * dest,bool catch_all_exc)1141 void mp_load_method_protected(mp_obj_t obj, qstr attr, mp_obj_t *dest, bool catch_all_exc) {
1142     nlr_buf_t nlr;
1143     if (nlr_push(&nlr) == 0) {
1144         mp_load_method_maybe(obj, attr, dest);
1145         nlr_pop();
1146     } else {
1147         if (!catch_all_exc
1148             && !mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type),
1149                 MP_OBJ_FROM_PTR(&mp_type_AttributeError))) {
1150             // Re-raise the exception
1151             nlr_raise(MP_OBJ_FROM_PTR(nlr.ret_val));
1152         }
1153     }
1154 }
1155 
mp_store_attr(mp_obj_t base,qstr attr,mp_obj_t value)1156 void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
1157     DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
1158     const mp_obj_type_t *type = mp_obj_get_type(base);
1159     if (type->attr != NULL) {
1160         mp_obj_t dest[2] = {MP_OBJ_SENTINEL, value};
1161         type->attr(base, attr, dest);
1162         if (dest[0] == MP_OBJ_NULL) {
1163             // success
1164             return;
1165         }
1166     }
1167     #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
1168     mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("no such attribute"));
1169     #else
1170     mp_raise_msg_varg(&mp_type_AttributeError,
1171         MP_ERROR_TEXT("'%s' object has no attribute '%q'"),
1172         mp_obj_get_type_str(base), attr);
1173     #endif
1174 }
1175 
mp_getiter(mp_obj_t o_in,mp_obj_iter_buf_t * iter_buf)1176 mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
1177     assert(o_in);
1178     const mp_obj_type_t *type = mp_obj_get_type(o_in);
1179 
1180     // Check for native getiter which is the identity.  We handle this case explicitly
1181     // so we don't unnecessarily allocate any RAM for the iter_buf, which won't be used.
1182     if (type->getiter == mp_identity_getiter) {
1183         return o_in;
1184     }
1185 
1186     // check for native getiter (corresponds to __iter__)
1187     if (type->getiter != NULL) {
1188         if (iter_buf == NULL && type->getiter != mp_obj_instance_getiter) {
1189             // if caller did not provide a buffer then allocate one on the heap
1190             // mp_obj_instance_getiter is special, it will allocate only if needed
1191             iter_buf = m_new_obj(mp_obj_iter_buf_t);
1192         }
1193         mp_obj_t iter = type->getiter(o_in, iter_buf);
1194         if (iter != MP_OBJ_NULL) {
1195             return iter;
1196         }
1197     }
1198 
1199     // check for __getitem__
1200     mp_obj_t dest[2];
1201     mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
1202     if (dest[0] != MP_OBJ_NULL) {
1203         // __getitem__ exists, create and return an iterator
1204         if (iter_buf == NULL) {
1205             // if caller did not provide a buffer then allocate one on the heap
1206             iter_buf = m_new_obj(mp_obj_iter_buf_t);
1207         }
1208         return mp_obj_new_getitem_iter(dest, iter_buf);
1209     }
1210 
1211     // object not iterable
1212     #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
1213     mp_raise_TypeError(MP_ERROR_TEXT("object not iterable"));
1214     #else
1215     mp_raise_msg_varg(&mp_type_TypeError,
1216         MP_ERROR_TEXT("'%s' object isn't iterable"), mp_obj_get_type_str(o_in));
1217     #endif
1218 
1219 }
1220 
1221 // may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
1222 // may also raise StopIteration()
mp_iternext_allow_raise(mp_obj_t o_in)1223 mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
1224     const mp_obj_type_t *type = mp_obj_get_type(o_in);
1225     if (type->iternext != NULL) {
1226         MP_STATE_THREAD(stop_iteration_arg) = MP_OBJ_NULL;
1227         return type->iternext(o_in);
1228     } else {
1229         // check for __next__ method
1230         mp_obj_t dest[2];
1231         mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
1232         if (dest[0] != MP_OBJ_NULL) {
1233             // __next__ exists, call it and return its result
1234             return mp_call_method_n_kw(0, 0, dest);
1235         } else {
1236             #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
1237             mp_raise_TypeError(MP_ERROR_TEXT("object not an iterator"));
1238             #else
1239             mp_raise_msg_varg(&mp_type_TypeError,
1240                 MP_ERROR_TEXT("'%s' object isn't an iterator"), mp_obj_get_type_str(o_in));
1241             #endif
1242         }
1243     }
1244 }
1245 
1246 // will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
1247 // may raise other exceptions
mp_iternext(mp_obj_t o_in)1248 mp_obj_t mp_iternext(mp_obj_t o_in) {
1249     MP_STACK_CHECK(); // enumerate, filter, map and zip can recursively call mp_iternext
1250     const mp_obj_type_t *type = mp_obj_get_type(o_in);
1251     if (type->iternext != NULL) {
1252         MP_STATE_THREAD(stop_iteration_arg) = MP_OBJ_NULL;
1253         return type->iternext(o_in);
1254     } else {
1255         // check for __next__ method
1256         mp_obj_t dest[2];
1257         mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
1258         if (dest[0] != MP_OBJ_NULL) {
1259             // __next__ exists, call it and return its result
1260             nlr_buf_t nlr;
1261             if (nlr_push(&nlr) == 0) {
1262                 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
1263                 nlr_pop();
1264                 return ret;
1265             } else {
1266                 if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
1267                     return mp_make_stop_iteration(mp_obj_exception_get_value(MP_OBJ_FROM_PTR(nlr.ret_val)));
1268                 } else {
1269                     nlr_jump(nlr.ret_val);
1270                 }
1271             }
1272         } else {
1273             #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
1274             mp_raise_TypeError(MP_ERROR_TEXT("object not an iterator"));
1275             #else
1276             mp_raise_msg_varg(&mp_type_TypeError,
1277                 MP_ERROR_TEXT("'%s' object isn't an iterator"), mp_obj_get_type_str(o_in));
1278             #endif
1279         }
1280     }
1281 }
1282 
mp_resume(mp_obj_t self_in,mp_obj_t send_value,mp_obj_t throw_value,mp_obj_t * ret_val)1283 mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, mp_obj_t *ret_val) {
1284     assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
1285     const mp_obj_type_t *type = mp_obj_get_type(self_in);
1286 
1287     if (type == &mp_type_gen_instance) {
1288         return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
1289     }
1290 
1291     if (type->iternext != NULL && send_value == mp_const_none) {
1292         MP_STATE_THREAD(stop_iteration_arg) = MP_OBJ_NULL;
1293         mp_obj_t ret = type->iternext(self_in);
1294         *ret_val = ret;
1295         if (ret != MP_OBJ_STOP_ITERATION) {
1296             return MP_VM_RETURN_YIELD;
1297         } else {
1298             // The generator is finished.
1299             // This is an optimised "raise StopIteration(*ret_val)".
1300             *ret_val = MP_STATE_THREAD(stop_iteration_arg);
1301             if (*ret_val == MP_OBJ_NULL) {
1302                 *ret_val = mp_const_none;
1303             }
1304             return MP_VM_RETURN_NORMAL;
1305         }
1306     }
1307 
1308     mp_obj_t dest[3]; // Reserve slot for send() arg
1309 
1310     // Python instance iterator protocol
1311     if (send_value == mp_const_none) {
1312         mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1313         if (dest[0] != MP_OBJ_NULL) {
1314             *ret_val = mp_call_method_n_kw(0, 0, dest);
1315             return MP_VM_RETURN_YIELD;
1316         }
1317     }
1318 
1319     // Either python instance generator protocol, or native object
1320     // generator protocol.
1321     if (send_value != MP_OBJ_NULL) {
1322         mp_load_method(self_in, MP_QSTR_send, dest);
1323         dest[2] = send_value;
1324         *ret_val = mp_call_method_n_kw(1, 0, dest);
1325         return MP_VM_RETURN_YIELD;
1326     }
1327 
1328     assert(throw_value != MP_OBJ_NULL);
1329     {
1330         if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(throw_value)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
1331             mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1332             if (dest[0] != MP_OBJ_NULL) {
1333                 // TODO: Exceptions raised in close() are not propagated,
1334                 // printed to sys.stderr
1335                 *ret_val = mp_call_method_n_kw(0, 0, dest);
1336                 // We assume one can't "yield" from close()
1337                 return MP_VM_RETURN_NORMAL;
1338             }
1339         } else {
1340             mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1341             if (dest[0] != MP_OBJ_NULL) {
1342                 dest[2] = throw_value;
1343                 *ret_val = mp_call_method_n_kw(1, 0, dest);
1344                 // If .throw() method returned, we assume it's value to yield
1345                 // - any exception would be thrown with nlr_raise().
1346                 return MP_VM_RETURN_YIELD;
1347             }
1348         }
1349         // If there's nowhere to throw exception into, then we assume that object
1350         // is just incapable to handle it, so any exception thrown into it
1351         // will be propagated up. This behavior is approved by test_pep380.py
1352         // test_delegation_of_close_to_non_generator(),
1353         //  test_delegating_throw_to_non_generator()
1354         if (mp_obj_exception_match(throw_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
1355             // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError
1356             *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("generator raised StopIteration"));
1357         } else {
1358             *ret_val = mp_make_raise_obj(throw_value);
1359         }
1360         return MP_VM_RETURN_EXCEPTION;
1361     }
1362 }
1363 
mp_make_raise_obj(mp_obj_t o)1364 mp_obj_t mp_make_raise_obj(mp_obj_t o) {
1365     DEBUG_printf("raise %p\n", o);
1366     if (mp_obj_is_exception_type(o)) {
1367         // o is an exception type (it is derived from BaseException (or is BaseException))
1368         // create and return a new exception instance by calling o
1369         // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1370         // could have const instances in ROM which we return here instead
1371         return mp_call_function_n_kw(o, 0, 0, NULL);
1372     } else if (mp_obj_is_exception_instance(o)) {
1373         // o is an instance of an exception, so use it as the exception
1374         return o;
1375     } else {
1376         // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1377         return mp_obj_new_exception_msg(&mp_type_TypeError, MP_ERROR_TEXT("exceptions must derive from BaseException"));
1378     }
1379 }
1380 
mp_import_name(qstr name,mp_obj_t fromlist,mp_obj_t level)1381 mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
1382     DEBUG_printf("import name '%s' level=%d\n", qstr_str(name), MP_OBJ_SMALL_INT_VALUE(level));
1383 
1384     // build args array
1385     mp_obj_t args[5];
1386     args[0] = MP_OBJ_NEW_QSTR(name);
1387     args[1] = mp_const_none; // TODO should be globals
1388     args[2] = mp_const_none; // TODO should be locals
1389     args[3] = fromlist;
1390     args[4] = level;
1391 
1392     #if MICROPY_CAN_OVERRIDE_BUILTINS
1393     // Lookup __import__ and call that if it exists
1394     mp_obj_dict_t *bo_dict = MP_STATE_VM(mp_module_builtins_override_dict);
1395     if (bo_dict != NULL) {
1396         mp_map_elem_t *import = mp_map_lookup(&bo_dict->map, MP_OBJ_NEW_QSTR(MP_QSTR___import__), MP_MAP_LOOKUP);
1397         if (import != NULL) {
1398             return mp_call_function_n_kw(import->value, 5, 0, args);
1399         }
1400     }
1401     #endif
1402 
1403     return mp_builtin___import__(5, args);
1404 }
1405 
mp_import_from(mp_obj_t module,qstr name)1406 mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
1407     DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1408 
1409     mp_obj_t dest[2];
1410 
1411     mp_load_method_maybe(module, name, dest);
1412 
1413     if (dest[1] != MP_OBJ_NULL) {
1414         // Hopefully we can't import bound method from an object
1415     import_error:
1416         mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("can't import name %q"), name);
1417     }
1418 
1419     if (dest[0] != MP_OBJ_NULL) {
1420         return dest[0];
1421     }
1422 
1423     #if MICROPY_ENABLE_EXTERNAL_IMPORT
1424 
1425     // See if it's a package, then can try FS import
1426     if (!mp_obj_is_package(module)) {
1427         goto import_error;
1428     }
1429 
1430     mp_load_method_maybe(module, MP_QSTR___name__, dest);
1431     size_t pkg_name_len;
1432     const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1433 
1434     const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1435     char *dot_name = mp_local_alloc(dot_name_len);
1436     memcpy(dot_name, pkg_name, pkg_name_len);
1437     dot_name[pkg_name_len] = '.';
1438     memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
1439     qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
1440     mp_local_free(dot_name);
1441 
1442     // For fromlist, pass sentinel "non empty" value to force returning of leaf module
1443     return mp_import_name(dot_name_q, mp_const_true, MP_OBJ_NEW_SMALL_INT(0));
1444 
1445     #else
1446 
1447     // Package import not supported with external imports disabled
1448     goto import_error;
1449 
1450     #endif
1451 }
1452 
mp_import_all(mp_obj_t module)1453 void mp_import_all(mp_obj_t module) {
1454     DEBUG_printf("import all %p\n", module);
1455 
1456     // TODO: Support __all__
1457     mp_map_t *map = &mp_obj_module_get_globals(module)->map;
1458     for (size_t i = 0; i < map->alloc; i++) {
1459         if (mp_map_slot_is_filled(map, i)) {
1460             // Entry in module global scope may be generated programmatically
1461             // (and thus be not a qstr for longer names). Avoid turning it in
1462             // qstr if it has '_' and was used exactly to save memory.
1463             const char *name = mp_obj_str_get_str(map->table[i].key);
1464             if (*name != '_') {
1465                 qstr qname = mp_obj_str_get_qstr(map->table[i].key);
1466                 mp_store_name(qname, map->table[i].value);
1467             }
1468         }
1469     }
1470 }
1471 
1472 #if MICROPY_ENABLE_COMPILER
1473 
mp_parse_compile_execute(mp_lexer_t * lex,mp_parse_input_kind_t parse_input_kind,mp_obj_dict_t * globals,mp_obj_dict_t * locals)1474 mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_input_kind, mp_obj_dict_t *globals, mp_obj_dict_t *locals) {
1475     // save context
1476     mp_obj_dict_t *volatile old_globals = mp_globals_get();
1477     mp_obj_dict_t *volatile old_locals = mp_locals_get();
1478 
1479     // set new context
1480     mp_globals_set(globals);
1481     mp_locals_set(locals);
1482 
1483     nlr_buf_t nlr;
1484     if (nlr_push(&nlr) == 0) {
1485         qstr source_name = lex->source_name;
1486         mp_parse_tree_t parse_tree = mp_parse(lex, parse_input_kind);
1487         mp_obj_t module_fun = mp_compile(&parse_tree, source_name, parse_input_kind == MP_PARSE_SINGLE_INPUT);
1488 
1489         mp_obj_t ret;
1490         if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
1491             // for compile only, return value is the module function
1492             ret = module_fun;
1493         } else {
1494             // execute module function and get return value
1495             ret = mp_call_function_0(module_fun);
1496         }
1497 
1498         // finish nlr block, restore context and return value
1499         nlr_pop();
1500         mp_globals_set(old_globals);
1501         mp_locals_set(old_locals);
1502         return ret;
1503     } else {
1504         // exception; restore context and re-raise same exception
1505         mp_globals_set(old_globals);
1506         mp_locals_set(old_locals);
1507         nlr_jump(nlr.ret_val);
1508     }
1509 }
1510 
1511 #endif // MICROPY_ENABLE_COMPILER
1512 
m_malloc_fail(size_t num_bytes)1513 NORETURN void m_malloc_fail(size_t num_bytes) {
1514     DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes);
1515     #if MICROPY_ENABLE_GC
1516     if (gc_is_locked()) {
1517         mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("memory allocation failed, heap is locked"));
1518     }
1519     #endif
1520     mp_raise_msg_varg(&mp_type_MemoryError,
1521         MP_ERROR_TEXT("memory allocation failed, allocating %u bytes"), (uint)num_bytes);
1522 }
1523 
1524 #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NONE
1525 
mp_raise_type(const mp_obj_type_t * exc_type)1526 NORETURN void mp_raise_type(const mp_obj_type_t *exc_type) {
1527     nlr_raise(mp_obj_new_exception(exc_type));
1528 }
1529 
mp_raise_ValueError_no_msg(void)1530 NORETURN void mp_raise_ValueError_no_msg(void) {
1531     mp_raise_type(&mp_type_ValueError);
1532 }
1533 
mp_raise_TypeError_no_msg(void)1534 NORETURN void mp_raise_TypeError_no_msg(void) {
1535     mp_raise_type(&mp_type_TypeError);
1536 }
1537 
mp_raise_NotImplementedError_no_msg(void)1538 NORETURN void mp_raise_NotImplementedError_no_msg(void) {
1539     mp_raise_type(&mp_type_NotImplementedError);
1540 }
1541 
1542 #else
1543 
mp_raise_msg(const mp_obj_type_t * exc_type,mp_rom_error_text_t msg)1544 NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg) {
1545     if (msg == NULL) {
1546         nlr_raise(mp_obj_new_exception(exc_type));
1547     } else {
1548         nlr_raise(mp_obj_new_exception_msg(exc_type, msg));
1549     }
1550 }
1551 
mp_raise_msg_varg(const mp_obj_type_t * exc_type,mp_rom_error_text_t fmt,...)1552 NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...) {
1553     va_list args;
1554     va_start(args, fmt);
1555     mp_obj_t exc = mp_obj_new_exception_msg_vlist(exc_type, fmt, args);
1556     va_end(args);
1557     nlr_raise(exc);
1558 }
1559 
mp_raise_ValueError(mp_rom_error_text_t msg)1560 NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg) {
1561     mp_raise_msg(&mp_type_ValueError, msg);
1562 }
1563 
mp_raise_TypeError(mp_rom_error_text_t msg)1564 NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg) {
1565     mp_raise_msg(&mp_type_TypeError, msg);
1566 }
1567 
mp_raise_NotImplementedError(mp_rom_error_text_t msg)1568 NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg) {
1569     mp_raise_msg(&mp_type_NotImplementedError, msg);
1570 }
1571 
1572 #endif
1573 
mp_raise_type_arg(const mp_obj_type_t * exc_type,mp_obj_t arg)1574 NORETURN void mp_raise_type_arg(const mp_obj_type_t *exc_type, mp_obj_t arg) {
1575     nlr_raise(mp_obj_new_exception_arg1(exc_type, arg));
1576 }
1577 
mp_raise_StopIteration(mp_obj_t arg)1578 NORETURN void mp_raise_StopIteration(mp_obj_t arg) {
1579     if (arg == MP_OBJ_NULL) {
1580         mp_raise_type(&mp_type_StopIteration);
1581     } else {
1582         mp_raise_type_arg(&mp_type_StopIteration, arg);
1583     }
1584 }
1585 
mp_raise_OSError(int errno_)1586 NORETURN void mp_raise_OSError(int errno_) {
1587     mp_raise_type_arg(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno_));
1588 }
1589 
1590 #if MICROPY_STACK_CHECK || MICROPY_ENABLE_PYSTACK
mp_raise_recursion_depth(void)1591 NORETURN void mp_raise_recursion_depth(void) {
1592     mp_raise_type_arg(&mp_type_RuntimeError, MP_OBJ_NEW_QSTR(MP_QSTR_maximum_space_recursion_space_depth_space_exceeded));
1593 }
1594 #endif
1595