blob: b9d7b72dcf6f23fcfbe38fced48c032fa51fb19b [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
Damien429d7192013-10-04 19:53:11 +010027#include <stdio.h>
28#include <string.h>
29#include <assert.h>
30
Damien Georgeb4b10fd2015-01-01 23:30:53 +000031#include "py/mpstate.h"
Damien George51dfcb42015-01-01 20:27:54 +000032#include "py/nlr.h"
Damien George51dfcb42015-01-01 20:27:54 +000033#include "py/parsenum.h"
34#include "py/compile.h"
Damien Georgec2a4e4e2015-05-11 12:25:19 +000035#include "py/objstr.h"
Damien George51dfcb42015-01-01 20:27:54 +000036#include "py/objtuple.h"
37#include "py/objlist.h"
38#include "py/objmodule.h"
39#include "py/objgenerator.h"
40#include "py/smallint.h"
41#include "py/runtime0.h"
42#include "py/runtime.h"
43#include "py/builtin.h"
44#include "py/stackctrl.h"
45#include "py/gc.h"
Damien660365e2013-12-17 18:27:24 +000046
Damien7f5dacf2013-10-10 11:24:39 +010047#if 0 // print debugging info
Damiena1ddfcc2013-10-10 23:25:50 +010048#define DEBUG_PRINT (1)
Paul Sokolovsky44739e22014-02-16 18:11:42 +020049#define DEBUG_printf DEBUG_printf
Damien George41eb6082014-02-26 22:40:35 +000050#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
Damien7f5dacf2013-10-10 11:24:39 +010051#else // don't print debugging info
Damien George41eb6082014-02-26 22:40:35 +000052#define DEBUG_printf(...) (void)0
53#define DEBUG_OP_printf(...) (void)0
Damien7f5dacf2013-10-10 11:24:39 +010054#endif
Damien429d7192013-10-04 19:53:11 +010055
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030056const mp_obj_module_t mp_module___main__ = {
57 .base = { &mp_type_module },
Damien Georgeb4b10fd2015-01-01 23:30:53 +000058 .globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main),
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030059};
60
Damien Georged17926d2014-03-30 13:35:08 +010061void mp_init(void) {
Damien George8dbbbbc2014-08-04 10:05:16 +010062 qstr_init();
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030063
Damien George124df6f2014-10-25 18:19:55 +010064 // no pending exceptions to start with
Damien Georgeb4b10fd2015-01-01 23:30:53 +000065 MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
Damien George124df6f2014-10-25 18:19:55 +010066
Damien George8dbbbbc2014-08-04 10:05:16 +010067#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
68 mp_init_emergency_exception_buf();
69#endif
70
Damien George7f1da0a2016-12-15 13:00:19 +110071 #if MICROPY_KBD_EXCEPTION
72 // initialise the exception object for raising KeyboardInterrupt
73 MP_STATE_VM(mp_kbd_exception).base.type = &mp_type_KeyboardInterrupt;
74 MP_STATE_VM(mp_kbd_exception).traceback_alloc = 0;
75 MP_STATE_VM(mp_kbd_exception).traceback_len = 0;
76 MP_STATE_VM(mp_kbd_exception).traceback_data = NULL;
77 MP_STATE_VM(mp_kbd_exception).args = mp_const_empty_tuple;
78 #endif
79
Damien George97f9a282014-05-12 23:07:34 +010080 // call port specific initialization if any
stijn72521a12014-05-03 11:28:29 +020081#ifdef MICROPY_PORT_INIT_FUNC
82 MICROPY_PORT_INIT_FUNC;
83#endif
84
Paul Sokolovskyd3439d02014-06-02 19:37:55 +030085 // optimization disabled by default
Damien Georgeb4b10fd2015-01-01 23:30:53 +000086 MP_STATE_VM(mp_optimise_value) = 0;
Damien George97f9a282014-05-12 23:07:34 +010087
Damien Georgee9cb1f82017-01-26 23:30:38 +110088 // init global module dict
89 mp_obj_dict_init(&MP_STATE_VM(mp_loaded_modules_dict), 3);
Damien George0d028742014-01-22 23:59:20 +000090
Damien George7efc5b32014-04-05 22:36:42 +010091 // initialise the __main__ module
Damien Georgeb4b10fd2015-01-01 23:30:53 +000092 mp_obj_dict_init(&MP_STATE_VM(dict_main), 1);
Damien George999cedb2015-11-27 17:01:44 +000093 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__));
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030094
95 // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
Damien Georgeb4b10fd2015-01-01 23:30:53 +000096 MP_STATE_CTX(dict_locals) = MP_STATE_CTX(dict_globals) = &MP_STATE_VM(dict_main);
Damien George78d702c2014-12-09 16:19:48 +000097
98 #if MICROPY_CAN_OVERRIDE_BUILTINS
99 // start with no extensions to builtins
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000100 MP_STATE_VM(mp_module_builtins_override_dict) = NULL;
Damien George78d702c2014-12-09 16:19:48 +0000101 #endif
Damien George4cec63a2016-05-26 10:42:53 +0000102
Damien Georgee8f2db72016-12-14 11:40:11 +1100103 #if MICROPY_FSUSERMOUNT
104 // zero out the pointers to the user-mounted devices
105 memset(MP_STATE_VM(fs_user_mount), 0, sizeof(MP_STATE_VM(fs_user_mount)));
106 #endif
107
Damien Georgedcb9ea72017-01-27 15:10:09 +1100108 #if MICROPY_VFS
109 // initialise the VFS sub-system
110 MP_STATE_VM(vfs_cur) = NULL;
111 MP_STATE_VM(vfs_mount_table) = NULL;
112 #endif
113
Damien George4cec63a2016-05-26 10:42:53 +0000114 #if MICROPY_PY_THREAD_GIL
115 mp_thread_mutex_init(&MP_STATE_VM(gil_mutex));
116 #endif
117
118 MP_THREAD_GIL_ENTER();
Damien429d7192013-10-04 19:53:11 +0100119}
120
Damien Georged17926d2014-03-30 13:35:08 +0100121void mp_deinit(void) {
Damien George7efc5b32014-04-05 22:36:42 +0100122 //mp_obj_dict_free(&dict_main);
Damien Georgee9cb1f82017-01-26 23:30:38 +1100123 //mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map));
stijn5ed284a2014-05-08 10:56:33 +0200124
125 // call port specific deinitialization if any
126#ifdef MICROPY_PORT_INIT_FUNC
127 MICROPY_PORT_DEINIT_FUNC;
128#endif
Damien429d7192013-10-04 19:53:11 +0100129}
130
Damien George50912e72015-01-20 11:55:10 +0000131mp_obj_t mp_load_name(qstr qst) {
Damien429d7192013-10-04 19:53:11 +0100132 // logic: search locals, globals, builtins
Damien George50912e72015-01-20 11:55:10 +0000133 DEBUG_OP_printf("load name %s\n", qstr_str(qst));
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300134 // If we're at the outer scope (locals == globals), dispatch to load_global right away
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000135 if (MP_STATE_CTX(dict_locals) != MP_STATE_CTX(dict_globals)) {
Damien George50912e72015-01-20 11:55:10 +0000136 mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_locals)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300137 if (elem != NULL) {
138 return elem->value;
139 }
Damiena3977762013-10-09 23:10:10 +0100140 }
Damien George50912e72015-01-20 11:55:10 +0000141 return mp_load_global(qst);
Damiena3977762013-10-09 23:10:10 +0100142}
143
Damien George50912e72015-01-20 11:55:10 +0000144mp_obj_t mp_load_global(qstr qst) {
Damiena3977762013-10-09 23:10:10 +0100145 // logic: search globals, builtins
Damien George50912e72015-01-20 11:55:10 +0000146 DEBUG_OP_printf("load global %s\n", qstr_str(qst));
147 mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_globals)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100148 if (elem == NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000149 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000150 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000151 // lookup in additional dynamic table of builtins first
Damien George50912e72015-01-20 11:55:10 +0000152 elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Damien George78d702c2014-12-09 16:19:48 +0000153 if (elem != NULL) {
154 return elem->value;
155 }
156 }
157 #endif
Damien George50912e72015-01-20 11:55:10 +0000158 elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100159 if (elem == NULL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000160 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100161 mp_raise_msg(&mp_type_NameError, "name not defined");
Damien George1e9a92f2014-11-06 17:36:16 +0000162 } else {
163 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
Damien George044c4732015-04-11 13:03:37 +0100164 "name '%q' is not defined", qst));
Damien George1e9a92f2014-11-06 17:36:16 +0000165 }
Damien429d7192013-10-04 19:53:11 +0100166 }
167 }
168 return elem->value;
169}
170
Damien Georged17926d2014-03-30 13:35:08 +0100171mp_obj_t mp_load_build_class(void) {
Damien429d7192013-10-04 19:53:11 +0100172 DEBUG_OP_printf("load_build_class\n");
Damien George78d702c2014-12-09 16:19:48 +0000173 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000174 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000175 // lookup in additional dynamic table of builtins first
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000176 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);
Damien George78d702c2014-12-09 16:19:48 +0000177 if (elem != NULL) {
178 return elem->value;
179 }
180 }
181 #endif
Damien George999cedb2015-11-27 17:01:44 +0000182 return MP_OBJ_FROM_PTR(&mp_builtin___build_class___obj);
Damien429d7192013-10-04 19:53:11 +0100183}
184
Damien George50912e72015-01-20 11:55:10 +0000185void mp_store_name(qstr qst, mp_obj_t obj) {
186 DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qst), obj);
Damien George999cedb2015-11-27 17:01:44 +0000187 mp_obj_dict_store(MP_OBJ_FROM_PTR(MP_STATE_CTX(dict_locals)), MP_OBJ_NEW_QSTR(qst), obj);
Damiena3977762013-10-09 23:10:10 +0100188}
189
Damien George50912e72015-01-20 11:55:10 +0000190void mp_delete_name(qstr qst) {
191 DEBUG_OP_printf("delete name %s\n", qstr_str(qst));
192 // TODO convert KeyError to NameError if qst not found
Damien George999cedb2015-11-27 17:01:44 +0000193 mp_obj_dict_delete(MP_OBJ_FROM_PTR(MP_STATE_CTX(dict_locals)), MP_OBJ_NEW_QSTR(qst));
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200194}
195
Damien George50912e72015-01-20 11:55:10 +0000196void mp_store_global(qstr qst, mp_obj_t obj) {
197 DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qst), obj);
Damien George999cedb2015-11-27 17:01:44 +0000198 mp_obj_dict_store(MP_OBJ_FROM_PTR(MP_STATE_CTX(dict_globals)), MP_OBJ_NEW_QSTR(qst), obj);
Damien429d7192013-10-04 19:53:11 +0100199}
200
Damien George50912e72015-01-20 11:55:10 +0000201void mp_delete_global(qstr qst) {
202 DEBUG_OP_printf("delete global %s\n", qstr_str(qst));
203 // TODO convert KeyError to NameError if qst not found
Damien George999cedb2015-11-27 17:01:44 +0000204 mp_obj_dict_delete(MP_OBJ_FROM_PTR(MP_STATE_CTX(dict_globals)), MP_OBJ_NEW_QSTR(qst));
Damien George1d24ea52014-04-08 21:11:49 +0100205}
206
Damien George4abff752014-08-30 14:59:21 +0100207mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100208 DEBUG_OP_printf("unary " UINT_FMT " %p\n", op, arg);
Damien George9aa2a522014-02-01 23:04:09 +0000209
Damien Georgebdbe8c92015-12-08 12:28:11 +0000210 if (op == MP_UNARY_OP_NOT) {
211 // "not x" is the negative of whether "x" is true per Python semantics
212 return mp_obj_new_bool(mp_obj_is_true(arg) == 0);
213 } else if (MP_OBJ_IS_SMALL_INT(arg)) {
Damien George40f3c022014-07-03 13:25:24 +0100214 mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
Damien7410e442013-11-02 19:47:57 +0000215 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100216 case MP_UNARY_OP_BOOL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300217 return mp_obj_new_bool(val != 0);
Damien Georgec2a4e4e2015-05-11 12:25:19 +0000218 case MP_UNARY_OP_HASH:
219 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100220 case MP_UNARY_OP_POSITIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000221 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100222 case MP_UNARY_OP_NEGATIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000223 // check for overflow
224 if (val == MP_SMALL_INT_MIN) {
225 return mp_obj_new_int(-val);
226 } else {
227 return MP_OBJ_NEW_SMALL_INT(-val);
228 }
Damien George9d68e9c2014-03-12 15:38:15 +0000229 default:
Damien Georged7150b02017-01-17 17:03:56 +1100230 assert(op == MP_UNARY_OP_INVERT);
231 return MP_OBJ_NEW_SMALL_INT(~val);
Damien7410e442013-11-02 19:47:57 +0000232 }
Damien Georgec2a4e4e2015-05-11 12:25:19 +0000233 } else if (op == MP_UNARY_OP_HASH && MP_OBJ_IS_STR_OR_BYTES(arg)) {
234 // fast path for hashing str/bytes
235 GET_STR_HASH(arg, h);
Damien George5f3bda42016-09-02 14:42:53 +1000236 if (h == 0) {
237 GET_STR_DATA_LEN(arg, data, len);
238 h = qstr_compute_hash(data, len);
239 }
Damien Georgec2a4e4e2015-05-11 12:25:19 +0000240 return MP_OBJ_NEW_SMALL_INT(h);
Damien George1e708fe2014-01-23 18:27:51 +0000241 } else {
242 mp_obj_type_t *type = mp_obj_get_type(arg);
243 if (type->unary_op != NULL) {
244 mp_obj_t result = type->unary_op(op, arg);
Damien George6ac5dce2014-05-21 19:42:43 +0100245 if (result != MP_OBJ_NULL) {
Damiend99b0522013-12-21 18:17:45 +0000246 return result;
247 }
Damien7410e442013-11-02 19:47:57 +0000248 }
Damien George1e9a92f2014-11-06 17:36:16 +0000249 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100250 mp_raise_msg(&mp_type_TypeError, "unsupported type for operator");
Damien George1e9a92f2014-11-06 17:36:16 +0000251 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000252 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
Damien George044c4732015-04-11 13:03:37 +0100253 "unsupported type for %q: '%s'",
254 mp_unary_op_method_name[op], mp_obj_get_type_str(arg)));
Damien George1e9a92f2014-11-06 17:36:16 +0000255 }
Damien7410e442013-11-02 19:47:57 +0000256 }
Damien429d7192013-10-04 19:53:11 +0100257}
258
Damien George4abff752014-08-30 14:59:21 +0100259mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100260 DEBUG_OP_printf("binary " UINT_FMT " %p %p\n", op, lhs, rhs);
Damien George14f945c2014-01-03 14:09:31 +0000261
262 // TODO correctly distinguish inplace operators for mutable objects
263 // lookup logic that CPython uses for +=:
264 // check for implemented +=
265 // then check for implemented +
266 // then check for implemented seq.inplace_concat
267 // then check for implemented seq.concat
268 // then fail
269 // note that list does not implement + or +=, so that inplace_concat is reached first for +=
270
Damien George9aa2a522014-02-01 23:04:09 +0000271 // deal with is
Damien Georged17926d2014-03-30 13:35:08 +0100272 if (op == MP_BINARY_OP_IS) {
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300273 return mp_obj_new_bool(lhs == rhs);
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200274 }
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200275
Damien Georgebcbeea02014-01-11 10:47:22 +0000276 // deal with == and != for all types
Damien Georged17926d2014-03-30 13:35:08 +0100277 if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000278 if (mp_obj_equal(lhs, rhs)) {
Damien Georged17926d2014-03-30 13:35:08 +0100279 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000280 return mp_const_true;
281 } else {
282 return mp_const_false;
283 }
284 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100285 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000286 return mp_const_false;
287 } else {
288 return mp_const_true;
289 }
290 }
291 }
292
293 // deal with exception_match for all types
Damien Georged17926d2014-03-30 13:35:08 +0100294 if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
Damien Georgec5966122014-02-15 16:10:44 +0000295 // rhs must be issubclass(rhs, BaseException)
296 if (mp_obj_is_exception_type(rhs)) {
Damien George4bcd04b2014-09-24 14:05:40 +0100297 if (mp_obj_exception_match(lhs, rhs)) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000298 return mp_const_true;
299 } else {
300 return mp_const_false;
301 }
Damien George4bcd04b2014-09-24 14:05:40 +0100302 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
Damien George999cedb2015-11-27 17:01:44 +0000303 mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(rhs);
Damien George4e3bac22017-02-16 15:32:34 +1100304 for (size_t i = 0; i < tuple->len; i++) {
Damien George4bcd04b2014-09-24 14:05:40 +0100305 rhs = tuple->items[i];
306 if (!mp_obj_is_exception_type(rhs)) {
307 goto unsupported_op;
308 }
309 if (mp_obj_exception_match(lhs, rhs)) {
310 return mp_const_true;
311 }
312 }
313 return mp_const_false;
Damien Georgebcbeea02014-01-11 10:47:22 +0000314 }
Damien George4bcd04b2014-09-24 14:05:40 +0100315 goto unsupported_op;
Damien Georgebcbeea02014-01-11 10:47:22 +0000316 }
317
Damien George1a9951d2014-01-06 22:13:00 +0000318 if (MP_OBJ_IS_SMALL_INT(lhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100319 mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
Damien George1a9951d2014-01-06 22:13:00 +0000320 if (MP_OBJ_IS_SMALL_INT(rhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100321 mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
Damien George9d68e9c2014-03-12 15:38:15 +0000322 // This is a binary operation: lhs_val op rhs_val
323 // We need to be careful to handle overflow; see CERT INT32-C
324 // Operations that can overflow:
Damien George40f3c022014-07-03 13:25:24 +0100325 // + result always fits in mp_int_t, then handled by SMALL_INT check
326 // - result always fits in mp_int_t, then handled by SMALL_INT check
Damien George9d68e9c2014-03-12 15:38:15 +0000327 // * checked explicitly
Damien George40f3c022014-07-03 13:25:24 +0100328 // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
329 // % if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
Damien George9d68e9c2014-03-12 15:38:15 +0000330 // << checked explicitly
Damien George1a9951d2014-01-06 22:13:00 +0000331 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100332 case MP_BINARY_OP_OR:
333 case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
334 case MP_BINARY_OP_XOR:
335 case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
336 case MP_BINARY_OP_AND:
337 case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
338 case MP_BINARY_OP_LSHIFT:
339 case MP_BINARY_OP_INPLACE_LSHIFT: {
Damien George9d68e9c2014-03-12 15:38:15 +0000340 if (rhs_val < 0) {
341 // negative shift not allowed
Damien George7d0d7212016-10-17 12:17:37 +1100342 mp_raise_msg(&mp_type_ValueError, "negative shift count");
Damien George963a5a32015-01-16 17:47:07 +0000343 } else if (rhs_val >= (mp_int_t)BITS_PER_WORD || lhs_val > (MP_SMALL_INT_MAX >> rhs_val) || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
Damien George9d68e9c2014-03-12 15:38:15 +0000344 // left-shift will overflow, so use higher precision integer
345 lhs = mp_obj_new_int_from_ll(lhs_val);
346 goto generic_binary_op;
347 } else {
348 // use standard precision
349 lhs_val <<= rhs_val;
350 }
351 break;
352 }
Damien Georged17926d2014-03-30 13:35:08 +0100353 case MP_BINARY_OP_RSHIFT:
354 case MP_BINARY_OP_INPLACE_RSHIFT:
Damien George9d68e9c2014-03-12 15:38:15 +0000355 if (rhs_val < 0) {
356 // negative shift not allowed
Damien George7d0d7212016-10-17 12:17:37 +1100357 mp_raise_msg(&mp_type_ValueError, "negative shift count");
Damien George9d68e9c2014-03-12 15:38:15 +0000358 } else {
359 // standard precision is enough for right-shift
Damien George963a5a32015-01-16 17:47:07 +0000360 if (rhs_val >= (mp_int_t)BITS_PER_WORD) {
Paul Sokolovsky039887a2014-11-02 02:39:41 +0200361 // Shifting to big amounts is underfined behavior
362 // in C and is CPU-dependent; propagate sign bit.
363 rhs_val = BITS_PER_WORD - 1;
364 }
Damien George9d68e9c2014-03-12 15:38:15 +0000365 lhs_val >>= rhs_val;
366 }
367 break;
Damien Georged17926d2014-03-30 13:35:08 +0100368 case MP_BINARY_OP_ADD:
369 case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
370 case MP_BINARY_OP_SUBTRACT:
371 case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
372 case MP_BINARY_OP_MULTIPLY:
373 case MP_BINARY_OP_INPLACE_MULTIPLY: {
Damien George9d68e9c2014-03-12 15:38:15 +0000374
Damien George40f3c022014-07-03 13:25:24 +0100375 // If long long type exists and is larger than mp_int_t, then
Damien George9d68e9c2014-03-12 15:38:15 +0000376 // we can use the following code to perform overflow-checked multiplication.
Damien Georgeecf5b772014-04-04 11:13:51 +0000377 // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
Damien George9d68e9c2014-03-12 15:38:15 +0000378 #if 0
379 // compute result using long long precision
380 long long res = (long long)lhs_val * (long long)rhs_val;
381 if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
382 // result overflowed SMALL_INT, so return higher precision integer
383 return mp_obj_new_int_from_ll(res);
384 } else {
385 // use standard precision
Damien George40f3c022014-07-03 13:25:24 +0100386 lhs_val = (mp_int_t)res;
Damien George9d68e9c2014-03-12 15:38:15 +0000387 }
388 #endif
389
Damien Georgeecf5b772014-04-04 11:13:51 +0000390 if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
391 // use higher precision
392 lhs = mp_obj_new_int_from_ll(lhs_val);
393 goto generic_binary_op;
394 } else {
395 // use standard precision
396 return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
397 }
Damien George9d68e9c2014-03-12 15:38:15 +0000398 break;
399 }
Damien Georged17926d2014-03-30 13:35:08 +0100400 case MP_BINARY_OP_FLOOR_DIVIDE:
401 case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300402 if (rhs_val == 0) {
403 goto zero_division;
404 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000405 lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
Rachel Dowdall56402792014-03-22 20:19:24 +0000406 break;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300407
Damien Georgefb510b32014-06-01 13:32:54 +0100408 #if MICROPY_PY_BUILTINS_FLOAT
Damien Georged17926d2014-03-30 13:35:08 +0100409 case MP_BINARY_OP_TRUE_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300410 case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
411 if (rhs_val == 0) {
Damien George70f33cd2014-04-02 17:06:05 +0100412 goto zero_division;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300413 }
414 return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000415 #endif
Damiena3dcd9e2013-12-17 21:35:38 +0000416
Damien Georged17926d2014-03-30 13:35:08 +0100417 case MP_BINARY_OP_MODULO:
Damien Georgeecf5b772014-04-04 11:13:51 +0000418 case MP_BINARY_OP_INPLACE_MODULO: {
Damien Georgee5635f42015-10-01 22:48:48 +0100419 if (rhs_val == 0) {
420 goto zero_division;
421 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000422 lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
Rachel Dowdallcde86312014-03-22 17:29:27 +0000423 break;
424 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000425
Damien Georged17926d2014-03-30 13:35:08 +0100426 case MP_BINARY_OP_POWER:
427 case MP_BINARY_OP_INPLACE_POWER:
Damien George9d68e9c2014-03-12 15:38:15 +0000428 if (rhs_val < 0) {
Damien Georgefb510b32014-06-01 13:32:54 +0100429 #if MICROPY_PY_BUILTINS_FLOAT
Damien George9d68e9c2014-03-12 15:38:15 +0000430 lhs = mp_obj_new_float(lhs_val);
431 goto generic_binary_op;
432 #else
Damien George7d0d7212016-10-17 12:17:37 +1100433 mp_raise_msg(&mp_type_ValueError, "negative power with no float support");
Damien George9d68e9c2014-03-12 15:38:15 +0000434 #endif
435 } else {
Damien George40f3c022014-07-03 13:25:24 +0100436 mp_int_t ans = 1;
Damien George9d68e9c2014-03-12 15:38:15 +0000437 while (rhs_val > 0) {
438 if (rhs_val & 1) {
Damien Georgeecf5b772014-04-04 11:13:51 +0000439 if (mp_small_int_mul_overflow(ans, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100440 goto power_overflow;
441 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000442 ans *= lhs_val;
Damien George9d68e9c2014-03-12 15:38:15 +0000443 }
Damien George5bf565e2014-04-04 00:16:32 +0100444 if (rhs_val == 1) {
445 break;
446 }
Damien George9d68e9c2014-03-12 15:38:15 +0000447 rhs_val /= 2;
Damien Georgeecf5b772014-04-04 11:13:51 +0000448 if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100449 goto power_overflow;
450 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000451 lhs_val *= lhs_val;
Damien George1a9951d2014-01-06 22:13:00 +0000452 }
Damien George9d68e9c2014-03-12 15:38:15 +0000453 lhs_val = ans;
Damiena3dcd9e2013-12-17 21:35:38 +0000454 }
Damien George1a9951d2014-01-06 22:13:00 +0000455 break;
Damien George5bf565e2014-04-04 00:16:32 +0100456
457 power_overflow:
458 // use higher precision
459 lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
460 goto generic_binary_op;
461
Damien Georgec5029bc2015-06-13 22:00:10 +0100462 case MP_BINARY_OP_DIVMOD: {
463 if (rhs_val == 0) {
464 goto zero_division;
465 }
466 // to reduce stack usage we don't pass a temp array of the 2 items
Damien George999cedb2015-11-27 17:01:44 +0000467 mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
Damien Georgec5029bc2015-06-13 22:00:10 +0100468 tuple->items[0] = MP_OBJ_NEW_SMALL_INT(mp_small_int_floor_divide(lhs_val, rhs_val));
469 tuple->items[1] = MP_OBJ_NEW_SMALL_INT(mp_small_int_modulo(lhs_val, rhs_val));
Damien George999cedb2015-11-27 17:01:44 +0000470 return MP_OBJ_FROM_PTR(tuple);
Damien Georgec5029bc2015-06-13 22:00:10 +0100471 }
472
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300473 case MP_BINARY_OP_LESS: return mp_obj_new_bool(lhs_val < rhs_val); break;
474 case MP_BINARY_OP_MORE: return mp_obj_new_bool(lhs_val > rhs_val); break;
475 case MP_BINARY_OP_LESS_EQUAL: return mp_obj_new_bool(lhs_val <= rhs_val); break;
476 case MP_BINARY_OP_MORE_EQUAL: return mp_obj_new_bool(lhs_val >= rhs_val); break;
Damiena3dcd9e2013-12-17 21:35:38 +0000477
Damien George8bcb9862014-04-17 16:26:50 +0100478 default:
479 goto unsupported_op;
Damien George1a9951d2014-01-06 22:13:00 +0000480 }
Paul Sokolovsky757ac812014-01-12 17:06:25 +0200481 // TODO: We just should make mp_obj_new_int() inline and use that
Damien Georged1e355e2014-05-28 14:51:12 +0100482 if (MP_SMALL_INT_FITS(lhs_val)) {
Damien George1a9951d2014-01-06 22:13:00 +0000483 return MP_OBJ_NEW_SMALL_INT(lhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000484 } else {
485 return mp_obj_new_int(lhs_val);
Damien George1a9951d2014-01-06 22:13:00 +0000486 }
Damien Georgefb510b32014-06-01 13:32:54 +0100487#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100488 } else if (mp_obj_is_float(rhs)) {
Damien Georgeae491052014-04-10 20:08:11 +0100489 mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
490 if (res == MP_OBJ_NULL) {
491 goto unsupported_op;
492 } else {
493 return res;
494 }
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300495#if MICROPY_PY_BUILTINS_COMPLEX
Damien George0c36da02014-03-08 15:24:39 +0000496 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
Damien Georgeae491052014-04-10 20:08:11 +0100497 mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
498 if (res == MP_OBJ_NULL) {
499 goto unsupported_op;
500 } else {
501 return res;
502 }
Damien George3f759b72014-01-31 00:42:12 +0000503#endif
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300504#endif
Damien429d7192013-10-04 19:53:11 +0100505 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000506 }
John R. Lentonb8698fc2014-01-11 00:58:59 +0000507
Damien George9aa2a522014-02-01 23:04:09 +0000508 /* deal with `in`
John R. Lentonc1bef212014-01-11 12:39:33 +0000509 *
510 * NOTE `a in b` is `b.__contains__(a)`, hence why the generic dispatch
Damien George48697f12014-02-01 23:32:29 +0000511 * needs to go below with swapped arguments
John R. Lentonc1bef212014-01-11 12:39:33 +0000512 */
Damien Georged17926d2014-03-30 13:35:08 +0100513 if (op == MP_BINARY_OP_IN) {
Damien George5fa93b62014-01-22 14:35:10 +0000514 mp_obj_type_t *type = mp_obj_get_type(rhs);
515 if (type->binary_op != NULL) {
516 mp_obj_t res = type->binary_op(op, rhs, lhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100517 if (res != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000518 return res;
519 }
520 }
521 if (type->getiter != NULL) {
522 /* second attempt, walk the iterator */
Damien Georgeae8d8672016-01-09 23:14:54 +0000523 mp_obj_iter_buf_t iter_buf;
524 mp_obj_t iter = mp_getiter(rhs, &iter_buf);
Damien George3aa09f52014-10-23 12:06:53 +0100525 mp_obj_t next;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100526 while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
Damien George5fa93b62014-01-22 14:35:10 +0000527 if (mp_obj_equal(next, lhs)) {
Damien George9aa2a522014-02-01 23:04:09 +0000528 return mp_const_true;
John R. Lentonb8698fc2014-01-11 00:58:59 +0000529 }
Damien7410e442013-11-02 19:47:57 +0000530 }
Damien George9aa2a522014-02-01 23:04:09 +0000531 return mp_const_false;
Damien7410e442013-11-02 19:47:57 +0000532 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000533
Damien George1e9a92f2014-11-06 17:36:16 +0000534 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100535 mp_raise_msg(&mp_type_TypeError, "object not iterable");
Damien George1e9a92f2014-11-06 17:36:16 +0000536 } else {
537 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
538 "'%s' object is not iterable", mp_obj_get_type_str(rhs)));
539 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000540 }
541
Damien George5fa93b62014-01-22 14:35:10 +0000542 // generic binary_op supplied by type
Damien George9d68e9c2014-03-12 15:38:15 +0000543 mp_obj_type_t *type;
544generic_binary_op:
545 type = mp_obj_get_type(lhs);
Damien George5fa93b62014-01-22 14:35:10 +0000546 if (type->binary_op != NULL) {
547 mp_obj_t result = type->binary_op(op, lhs, rhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100548 if (result != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000549 return result;
John R. Lentonc1bef212014-01-11 12:39:33 +0000550 }
Damien429d7192013-10-04 19:53:11 +0100551 }
Damiend99b0522013-12-21 18:17:45 +0000552
Damien George5fa93b62014-01-22 14:35:10 +0000553 // TODO implement dispatch for reverse binary ops
554
Damien Georgeae491052014-04-10 20:08:11 +0100555unsupported_op:
Damien George1e9a92f2014-11-06 17:36:16 +0000556 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100557 mp_raise_msg(&mp_type_TypeError, "unsupported type for operator");
Damien George1e9a92f2014-11-06 17:36:16 +0000558 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000559 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
Damien George044c4732015-04-11 13:03:37 +0100560 "unsupported types for %q: '%s', '%s'",
561 mp_binary_op_method_name[op], mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs)));
Damien George1e9a92f2014-11-06 17:36:16 +0000562 }
Damien George70f33cd2014-04-02 17:06:05 +0100563
564zero_division:
Damien George7d0d7212016-10-17 12:17:37 +1100565 mp_raise_msg(&mp_type_ZeroDivisionError, "division by zero");
Damien429d7192013-10-04 19:53:11 +0100566}
567
Damien Georged17926d2014-03-30 13:35:08 +0100568mp_obj_t mp_call_function_0(mp_obj_t fun) {
569 return mp_call_function_n_kw(fun, 0, 0, NULL);
Damieneb19efb2013-10-10 22:06:54 +0100570}
571
Damien Georged17926d2014-03-30 13:35:08 +0100572mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
573 return mp_call_function_n_kw(fun, 1, 0, &arg);
Damieneb19efb2013-10-10 22:06:54 +0100574}
575
Damien Georged17926d2014-03-30 13:35:08 +0100576mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
Damiend99b0522013-12-21 18:17:45 +0000577 mp_obj_t args[2];
Damien George20006db2014-01-18 14:10:48 +0000578 args[0] = arg1;
579 args[1] = arg2;
Damien Georged17926d2014-03-30 13:35:08 +0100580 return mp_call_function_n_kw(fun, 2, 0, args);
Damieneb19efb2013-10-10 22:06:54 +0100581}
582
Damien George20006db2014-01-18 14:10:48 +0000583// args contains, eg: arg0 arg1 key0 value0 key1 value1
Damien George4e3bac22017-02-16 15:32:34 +1100584mp_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) {
Damiend99b0522013-12-21 18:17:45 +0000585 // TODO improve this: fun object can specify its type and we parse here the arguments,
586 // passing to the function arrays of fixed and keyword arguments
Damieneb19efb2013-10-10 22:06:54 +0100587
Damien Georgeeaaebf32014-09-23 10:59:05 +0100588 DEBUG_OP_printf("calling function %p(n_args=" UINT_FMT ", n_kw=" UINT_FMT ", args=%p)\n", fun_in, n_args, n_kw, args);
John R. Lenton9c83ec02014-01-07 23:06:46 +0000589
Damien George8b56beb2014-01-31 23:49:49 +0000590 // get the type
591 mp_obj_type_t *type = mp_obj_get_type(fun_in);
592
593 // do the call
594 if (type->call != NULL) {
Damien George3f522622014-06-03 13:40:16 +0100595 return type->call(fun_in, n_args, n_kw, args);
John R. Lenton9c83ec02014-01-07 23:06:46 +0000596 }
Paul Sokolovsky755565d2014-04-25 21:15:16 +0300597
Damien George1e9a92f2014-11-06 17:36:16 +0000598 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100599 mp_raise_msg(&mp_type_TypeError, "object not callable");
Damien George1e9a92f2014-11-06 17:36:16 +0000600 } else {
601 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
602 "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
603 }
Damien86c7fc72013-11-26 15:16:41 +0000604}
605
Damien George20006db2014-01-18 14:10:48 +0000606// 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)
607// if n_args==0 and n_kw==0 then there are only fun and self/NULL
Damien George4e3bac22017-02-16 15:32:34 +1100608mp_obj_t mp_call_method_n_kw(size_t n_args, size_t n_kw, const mp_obj_t *args) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100609 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);
Damien George999cedb2015-11-27 17:01:44 +0000610 int adjust = (args[1] == MP_OBJ_NULL) ? 0 : 1;
Damien Georged17926d2014-03-30 13:35:08 +0100611 return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
Damien86c7fc72013-11-26 15:16:41 +0000612}
613
Damien George12a5e172015-04-01 23:31:30 +0100614// This function only needs to be exposed externally when in stackless mode.
615#if !MICROPY_STACKLESS
616STATIC
617#endif
Damien George4e3bac22017-02-16 15:32:34 +1100618void 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) {
Damien George230fec72014-03-30 21:21:24 +0100619 mp_obj_t fun = *args++;
620 mp_obj_t self = MP_OBJ_NULL;
621 if (have_self) {
622 self = *args++; // may be MP_OBJ_NULL
623 }
624 uint n_args = n_args_n_kw & 0xff;
625 uint n_kw = (n_args_n_kw >> 8) & 0xff;
Paul Sokolovskye104acd2015-03-03 21:37:37 +0200626 mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // may be MP_OBJ_NULL
627 mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // may be MP_OBJ_NULL
Damien George230fec72014-03-30 21:21:24 +0100628
629 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);
630
631 // We need to create the following array of objects:
632 // args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
633 // TODO: optimize one day to avoid constructing new arg array? Will be hard.
634
635 // The new args array
636 mp_obj_t *args2;
637 uint args2_alloc;
638 uint args2_len = 0;
639
640 // Try to get a hint for the size of the kw_dict
641 uint kw_dict_len = 0;
642 if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
643 kw_dict_len = mp_obj_dict_len(kw_dict);
644 }
645
646 // Extract the pos_seq sequence to the new args array.
647 // Note that it can be arbitrary iterator.
648 if (pos_seq == MP_OBJ_NULL) {
649 // no sequence
650
651 // allocate memory for the new array of args
652 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
653 args2 = m_new(mp_obj_t, args2_alloc);
654
655 // copy the self
656 if (self != MP_OBJ_NULL) {
657 args2[args2_len++] = self;
658 }
659
660 // copy the fixed pos args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300661 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100662 args2_len += n_args;
663
664 } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
665 // optimise the case of a tuple and list
666
667 // get the items
Damien George9c4cbe22014-08-30 14:04:14 +0100668 mp_uint_t len;
Damien George230fec72014-03-30 21:21:24 +0100669 mp_obj_t *items;
670 mp_obj_get_array(pos_seq, &len, &items);
671
672 // allocate memory for the new array of args
673 args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
674 args2 = m_new(mp_obj_t, args2_alloc);
675
676 // copy the self
677 if (self != MP_OBJ_NULL) {
678 args2[args2_len++] = self;
679 }
680
681 // copy the fixed and variable position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300682 mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100683 args2_len += n_args + len;
684
685 } else {
686 // generic iterator
687
688 // allocate memory for the new array of args
689 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
690 args2 = m_new(mp_obj_t, args2_alloc);
691
692 // copy the self
693 if (self != MP_OBJ_NULL) {
694 args2[args2_len++] = self;
695 }
696
697 // copy the fixed position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300698 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George7a996392015-12-03 17:59:49 +0000699 args2_len += n_args;
Damien George230fec72014-03-30 21:21:24 +0100700
701 // extract the variable position args from the iterator
Damien Georgeae8d8672016-01-09 23:14:54 +0000702 mp_obj_iter_buf_t iter_buf;
703 mp_obj_t iterable = mp_getiter(pos_seq, &iter_buf);
Damien George230fec72014-03-30 21:21:24 +0100704 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100705 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100706 if (args2_len >= args2_alloc) {
707 args2 = m_renew(mp_obj_t, args2, args2_alloc, args2_alloc * 2);
708 args2_alloc *= 2;
709 }
710 args2[args2_len++] = item;
711 }
712 }
713
714 // The size of the args2 array now is the number of positional args.
715 uint pos_args_len = args2_len;
716
717 // Copy the fixed kw args.
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300718 mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100719 args2_len += 2 * n_kw;
720
721 // Extract (key,value) pairs from kw_dict dictionary and append to args2.
722 // Note that it can be arbitrary iterator.
723 if (kw_dict == MP_OBJ_NULL) {
724 // pass
725 } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
726 // dictionary
727 mp_map_t *map = mp_obj_dict_get_map(kw_dict);
728 assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above
Damien George4e3bac22017-02-16 15:32:34 +1100729 for (size_t i = 0; i < map->alloc; i++) {
Damien Georgeb063b9b2014-12-21 16:24:09 +0000730 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Damien Georgefea40ad2016-04-21 16:51:36 +0100731 // the key must be a qstr, so intern it if it's a string
732 mp_obj_t key = map->table[i].key;
733 if (MP_OBJ_IS_TYPE(key, &mp_type_str)) {
734 key = mp_obj_str_intern(key);
735 }
736 args2[args2_len++] = key;
Damien George230fec72014-03-30 21:21:24 +0100737 args2[args2_len++] = map->table[i].value;
738 }
739 }
740 } else {
Damien George470c4292016-05-07 22:02:46 +0100741 // generic mapping:
742 // - call keys() to get an iterable of all keys in the mapping
743 // - call __getitem__ for each key to get the corresponding value
744
745 // get the keys iterable
746 mp_obj_t dest[3];
747 mp_load_method(kw_dict, MP_QSTR_keys, dest);
Damien Georgeae8d8672016-01-09 23:14:54 +0000748 mp_obj_iter_buf_t iter_buf;
749 mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest), &iter_buf);
Damien George470c4292016-05-07 22:02:46 +0100750
751 mp_obj_t key;
752 while ((key = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
753 // expand size of args array if needed
Damien George230fec72014-03-30 21:21:24 +0100754 if (args2_len + 1 >= args2_alloc) {
755 uint new_alloc = args2_alloc * 2;
756 if (new_alloc < 4) {
757 new_alloc = 4;
758 }
759 args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
760 args2_alloc = new_alloc;
761 }
Damien George470c4292016-05-07 22:02:46 +0100762
Damien Georgefea40ad2016-04-21 16:51:36 +0100763 // the key must be a qstr, so intern it if it's a string
Damien Georgefea40ad2016-04-21 16:51:36 +0100764 if (MP_OBJ_IS_TYPE(key, &mp_type_str)) {
765 key = mp_obj_str_intern(key);
766 }
Damien George470c4292016-05-07 22:02:46 +0100767
768 // get the value corresponding to the key
769 mp_load_method(kw_dict, MP_QSTR___getitem__, dest);
770 dest[2] = key;
771 mp_obj_t value = mp_call_method_n_kw(1, 0, dest);
772
773 // store the key/value pair in the argument array
Damien Georgefea40ad2016-04-21 16:51:36 +0100774 args2[args2_len++] = key;
Damien George470c4292016-05-07 22:02:46 +0100775 args2[args2_len++] = value;
Damien George230fec72014-03-30 21:21:24 +0100776 }
777 }
778
Paul Sokolovskye6c6fe32015-03-28 01:14:45 +0200779 out_args->fun = fun;
780 out_args->args = args2;
781 out_args->n_args = pos_args_len;
782 out_args->n_kw = (args2_len - pos_args_len) / 2;
783 out_args->n_alloc = args2_alloc;
784}
785
Damien George4e3bac22017-02-16 15:32:34 +1100786mp_obj_t mp_call_method_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args) {
Damien George12a5e172015-04-01 23:31:30 +0100787 mp_call_args_t out_args;
Paul Sokolovskye6c6fe32015-03-28 01:14:45 +0200788 mp_call_prepare_args_n_kw_var(have_self, n_args_n_kw, args, &out_args);
789
790 mp_obj_t res = mp_call_function_n_kw(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args);
791 m_del(mp_obj_t, out_args.args, out_args.n_alloc);
Damien George230fec72014-03-30 21:21:24 +0100792
793 return res;
794}
795
Damien George932bf1c2014-01-18 23:42:49 +0000796// unpacked items are stored in reverse order into the array pointed to by items
Damien George4e3bac22017-02-16 15:32:34 +1100797void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) {
Damien George9c4cbe22014-08-30 14:04:14 +0100798 mp_uint_t seq_len;
Damien George3e1a5c12014-03-29 13:43:38 +0000799 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
Damiend99b0522013-12-21 18:17:45 +0000800 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000801 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000802 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
803 } else {
804 mp_obj_list_get(seq_in, &seq_len, &seq_items);
Damien86c7fc72013-11-26 15:16:41 +0000805 }
Damiend99b0522013-12-21 18:17:45 +0000806 if (seq_len < num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200807 goto too_short;
Damiend99b0522013-12-21 18:17:45 +0000808 } else if (seq_len > num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200809 goto too_long;
Damiend99b0522013-12-21 18:17:45 +0000810 }
Damien George4e3bac22017-02-16 15:32:34 +1100811 for (size_t i = 0; i < num; i++) {
Damien George932bf1c2014-01-18 23:42:49 +0000812 items[i] = seq_items[num - 1 - i];
813 }
Damien86c7fc72013-11-26 15:16:41 +0000814 } else {
Damien Georgeae8d8672016-01-09 23:14:54 +0000815 mp_obj_iter_buf_t iter_buf;
816 mp_obj_t iterable = mp_getiter(seq_in, &iter_buf);
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200817
818 for (seq_len = 0; seq_len < num; seq_len++) {
Damien Georged17926d2014-03-30 13:35:08 +0100819 mp_obj_t el = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100820 if (el == MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200821 goto too_short;
822 }
823 items[num - 1 - seq_len] = el;
824 }
Damien Georgeea8d06c2014-04-17 23:19:36 +0100825 if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200826 goto too_long;
827 }
Damien86c7fc72013-11-26 15:16:41 +0000828 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200829 return;
830
831too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000832 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100833 mp_raise_msg(&mp_type_ValueError, "wrong number of values to unpack");
Damien George1e9a92f2014-11-06 17:36:16 +0000834 } else {
835 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George2a1cca22016-03-14 22:40:39 +0000836 "need more than %d values to unpack", (int)seq_len));
Damien George1e9a92f2014-11-06 17:36:16 +0000837 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200838too_long:
Damien George1e9a92f2014-11-06 17:36:16 +0000839 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100840 mp_raise_msg(&mp_type_ValueError, "wrong number of values to unpack");
Damien George1e9a92f2014-11-06 17:36:16 +0000841 } else {
842 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George2a1cca22016-03-14 22:40:39 +0000843 "too many values to unpack (expected %d)", (int)num));
Damien George1e9a92f2014-11-06 17:36:16 +0000844 }
Damien86c7fc72013-11-26 15:16:41 +0000845}
846
Damien George495d7812014-04-08 17:51:47 +0100847// unpacked items are stored in reverse order into the array pointed to by items
Damien George4e3bac22017-02-16 15:32:34 +1100848void mp_unpack_ex(mp_obj_t seq_in, size_t num_in, mp_obj_t *items) {
849 size_t num_left = num_in & 0xff;
850 size_t num_right = (num_in >> 8) & 0xff;
Damien Georgeeaaebf32014-09-23 10:59:05 +0100851 DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
Damien George9c4cbe22014-08-30 14:04:14 +0100852 mp_uint_t seq_len;
Damien George495d7812014-04-08 17:51:47 +0100853 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
854 mp_obj_t *seq_items;
855 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
856 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
857 } else {
858 if (num_left == 0 && num_right == 0) {
859 // *a, = b # sets a to b if b is a list
860 items[0] = seq_in;
861 return;
862 }
863 mp_obj_list_get(seq_in, &seq_len, &seq_items);
864 }
865 if (seq_len < num_left + num_right) {
866 goto too_short;
867 }
Damien George4e3bac22017-02-16 15:32:34 +1100868 for (size_t i = 0; i < num_right; i++) {
Damien George495d7812014-04-08 17:51:47 +0100869 items[i] = seq_items[seq_len - 1 - i];
870 }
871 items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
Damien George4e3bac22017-02-16 15:32:34 +1100872 for (size_t i = 0; i < num_left; i++) {
Damien George495d7812014-04-08 17:51:47 +0100873 items[num_right + 1 + i] = seq_items[num_left - 1 - i];
874 }
875 } else {
876 // Generic iterable; this gets a bit messy: we unpack known left length to the
877 // items destination array, then the rest to a dynamically created list. Once the
878 // iterable is exhausted, we take from this list for the right part of the items.
879 // TODO Improve to waste less memory in the dynamically created list.
Damien Georgeae8d8672016-01-09 23:14:54 +0000880 mp_obj_iter_buf_t iter_buf;
881 mp_obj_t iterable = mp_getiter(seq_in, &iter_buf);
Damien George495d7812014-04-08 17:51:47 +0100882 mp_obj_t item;
883 for (seq_len = 0; seq_len < num_left; seq_len++) {
884 item = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100885 if (item == MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100886 goto too_short;
887 }
888 items[num_left + num_right + 1 - 1 - seq_len] = item;
889 }
Damien George999cedb2015-11-27 17:01:44 +0000890 mp_obj_list_t *rest = MP_OBJ_TO_PTR(mp_obj_new_list(0, NULL));
Damien Georgeea8d06c2014-04-17 23:19:36 +0100891 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George999cedb2015-11-27 17:01:44 +0000892 mp_obj_list_append(MP_OBJ_FROM_PTR(rest), item);
Damien George495d7812014-04-08 17:51:47 +0100893 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100894 if (rest->len < num_right) {
Damien George495d7812014-04-08 17:51:47 +0100895 goto too_short;
896 }
Damien George999cedb2015-11-27 17:01:44 +0000897 items[num_right] = MP_OBJ_FROM_PTR(rest);
Damien George4e3bac22017-02-16 15:32:34 +1100898 for (size_t i = 0; i < num_right; i++) {
Damien Georgeca6d75f2014-08-30 15:17:47 +0100899 items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
Damien George495d7812014-04-08 17:51:47 +0100900 }
Damien George999cedb2015-11-27 17:01:44 +0000901 mp_obj_list_set_len(MP_OBJ_FROM_PTR(rest), rest->len - num_right);
Damien George495d7812014-04-08 17:51:47 +0100902 }
903 return;
904
905too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000906 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100907 mp_raise_msg(&mp_type_ValueError, "wrong number of values to unpack");
Damien George1e9a92f2014-11-06 17:36:16 +0000908 } else {
909 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George2a1cca22016-03-14 22:40:39 +0000910 "need more than %d values to unpack", (int)seq_len));
Damien George1e9a92f2014-11-06 17:36:16 +0000911 }
Damien George495d7812014-04-08 17:51:47 +0100912}
913
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300914mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
Damien George062478e2014-01-09 20:57:50 +0000915 DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300916 // use load_method
Damien George062478e2014-01-09 20:57:50 +0000917 mp_obj_t dest[2];
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300918 mp_load_method(base, attr, dest);
919 if (dest[1] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000920 // load_method returned just a normal attribute
Damien George20006db2014-01-18 14:10:48 +0000921 return dest[0];
Damien George062478e2014-01-09 20:57:50 +0000922 } else {
923 // load_method returned a method, so build a bound method object
924 return mp_obj_new_bound_meth(dest[0], dest[1]);
Damiend99b0522013-12-21 18:17:45 +0000925 }
Damiend99b0522013-12-21 18:17:45 +0000926}
927
Damien George06593fb2015-06-19 12:49:10 +0000928#if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
929
930// The following "checked fun" type is local to the mp_convert_member_lookup
931// function, and serves to check that the first argument to a builtin function
932// has the correct type.
933
934typedef struct _mp_obj_checked_fun_t {
935 mp_obj_base_t base;
936 const mp_obj_type_t *type;
937 mp_obj_t fun;
938} mp_obj_checked_fun_t;
939
Damien Georgea0c97812016-01-03 09:59:18 +0000940STATIC mp_obj_t checked_fun_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
Damien George999cedb2015-11-27 17:01:44 +0000941 mp_obj_checked_fun_t *self = MP_OBJ_TO_PTR(self_in);
Damien George06593fb2015-06-19 12:49:10 +0000942 if (n_args > 0) {
943 const mp_obj_type_t *arg0_type = mp_obj_get_type(args[0]);
944 if (arg0_type != self->type) {
945 if (MICROPY_ERROR_REPORTING != MICROPY_ERROR_REPORTING_DETAILED) {
Damien George7d0d7212016-10-17 12:17:37 +1100946 mp_raise_msg(&mp_type_TypeError, "argument has wrong type");
Damien George06593fb2015-06-19 12:49:10 +0000947 } else {
948 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
949 "argument should be a '%q' not a '%q'", self->type->name, arg0_type->name));
950 }
951 }
952 }
953 return mp_call_function_n_kw(self->fun, n_args, n_kw, args);
954}
955
956STATIC const mp_obj_type_t mp_type_checked_fun = {
957 { &mp_type_type },
958 .name = MP_QSTR_function,
959 .call = checked_fun_call,
960};
961
962STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) {
963 mp_obj_checked_fun_t *o = m_new_obj(mp_obj_checked_fun_t);
964 o->base.type = &mp_type_checked_fun;
965 o->type = type;
966 o->fun = fun;
Damien George999cedb2015-11-27 17:01:44 +0000967 return MP_OBJ_FROM_PTR(o);
Damien George06593fb2015-06-19 12:49:10 +0000968}
969
970#endif // MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
971
Damien George55b74d12015-03-21 14:21:54 +0000972// Given a member that was extracted from an instance, convert it correctly
973// and put the result in the dest[] array for a possible method call.
974// Conversion means dealing with static/class methods, callables, and values.
975// see http://docs.python.org/3/howto/descriptor.html
976void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) {
977 if (MP_OBJ_IS_TYPE(member, &mp_type_staticmethod)) {
978 // return just the function
Damien George999cedb2015-11-27 17:01:44 +0000979 dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
Damien George55b74d12015-03-21 14:21:54 +0000980 } else if (MP_OBJ_IS_TYPE(member, &mp_type_classmethod)) {
981 // return a bound method, with self being the type of this object
Damien George3ff259a2015-12-09 17:30:01 +0000982 // this type should be the type of the original instance, not the base
983 // type (which is what is passed in the 'type' argument to this function)
984 if (self != MP_OBJ_NULL) {
985 type = mp_obj_get_type(self);
986 }
Damien George999cedb2015-11-27 17:01:44 +0000987 dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
988 dest[1] = MP_OBJ_FROM_PTR(type);
Damien George55b74d12015-03-21 14:21:54 +0000989 } else if (MP_OBJ_IS_TYPE(member, &mp_type_type)) {
990 // Don't try to bind types (even though they're callable)
991 dest[0] = member;
Damien George78913212015-12-26 12:41:31 +0000992 } else if (MP_OBJ_IS_FUN(member)
993 || (MP_OBJ_IS_OBJ(member)
994 && (((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure
995 || ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) {
996 // only functions, closures and generators objects can be bound to self
Damien George06593fb2015-06-19 12:49:10 +0000997 #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
Damien George571e6f22016-10-18 11:49:27 +1100998 const mp_obj_type_t *m_type = ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type;
999 if (self == MP_OBJ_NULL
1000 && (m_type == &mp_type_fun_builtin_0
1001 || m_type == &mp_type_fun_builtin_1
1002 || m_type == &mp_type_fun_builtin_2
1003 || m_type == &mp_type_fun_builtin_3
1004 || m_type == &mp_type_fun_builtin_var)) {
Damien George06593fb2015-06-19 12:49:10 +00001005 // we extracted a builtin method without a first argument, so we must
1006 // wrap this function in a type checker
1007 dest[0] = mp_obj_new_checked_fun(type, member);
1008 } else
1009 #endif
1010 {
1011 // return a bound method, with self being this object
1012 dest[0] = member;
1013 dest[1] = self;
1014 }
Damien George55b74d12015-03-21 14:21:54 +00001015 } else {
1016 // class member is a value, so just return that value
1017 dest[0] = member;
1018 }
1019}
1020
Damien George7c9c6672014-01-25 00:17:36 +00001021// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
1022// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
1023// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +02001024void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) {
Damien George062478e2014-01-09 20:57:50 +00001025 // clear output to indicate no attribute/method found yet
1026 dest[0] = MP_OBJ_NULL;
1027 dest[1] = MP_OBJ_NULL;
1028
1029 // get the type
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +02001030 mp_obj_type_t *type = mp_obj_get_type(obj);
Damien George062478e2014-01-09 20:57:50 +00001031
Damien Georgee44d26a2014-03-31 22:57:56 +01001032 // look for built-in names
1033 if (0) {
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +03001034#if MICROPY_CPYTHON_COMPAT
Damien Georgee44d26a2014-03-31 22:57:56 +01001035 } else if (attr == MP_QSTR___class__) {
1036 // a.__class__ is equivalent to type(a)
Damien George999cedb2015-11-27 17:01:44 +00001037 dest[0] = MP_OBJ_FROM_PTR(type);
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +03001038#endif
Damien Georgee44d26a2014-03-31 22:57:56 +01001039
1040 } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
Damien George999cedb2015-11-27 17:01:44 +00001041 dest[0] = MP_OBJ_FROM_PTR(&mp_builtin_next_obj);
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +02001042 dest[1] = obj;
Damien Georgee44d26a2014-03-31 22:57:56 +01001043
Damien Georgeb1bbe962015-04-01 14:10:50 +00001044 } else if (type->attr != NULL) {
Damien Georgee44d26a2014-03-31 22:57:56 +01001045 // this type can do its own load, so call it
Damien Georgeb1bbe962015-04-01 14:10:50 +00001046 type->attr(obj, attr, dest);
Damien Georgee44d26a2014-03-31 22:57:56 +01001047
1048 } else if (type->locals_dict != NULL) {
1049 // generic method lookup
1050 // this is a lookup in the object (ie not class or type)
Damien George999cedb2015-11-27 17:01:44 +00001051 assert(type->locals_dict->base.type == &mp_type_dict); // Micro Python restriction, for now
1052 mp_map_t *locals_map = &type->locals_dict->map;
Damien Georgee44d26a2014-03-31 22:57:56 +01001053 mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
1054 if (elem != NULL) {
Damien George55b74d12015-03-21 14:21:54 +00001055 mp_convert_member_lookup(obj, type, elem->value, dest);
Damiend57eba52013-11-02 23:58:14 +00001056 }
Damiena3977762013-10-09 23:10:10 +01001057 }
Damien George7c9c6672014-01-25 00:17:36 +00001058}
Damiena3977762013-10-09 23:10:10 +01001059
Damien Georged17926d2014-03-30 13:35:08 +01001060void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George7c9c6672014-01-25 00:17:36 +00001061 DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
1062
Damien Georged17926d2014-03-30 13:35:08 +01001063 mp_load_method_maybe(base, attr, dest);
Damien George7c9c6672014-01-25 00:17:36 +00001064
1065 if (dest[0] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +00001066 // no attribute/method called attr
Damien George1e9a92f2014-11-06 17:36:16 +00001067 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001068 mp_raise_msg(&mp_type_AttributeError, "no such attribute");
Damien George062478e2014-01-09 20:57:50 +00001069 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001070 // following CPython, we give a more detailed error message for type objects
1071 if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
1072 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001073 "type object '%q' has no attribute '%q'",
Damien George999cedb2015-11-27 17:01:44 +00001074 ((mp_obj_type_t*)MP_OBJ_TO_PTR(base))->name, attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001075 } else {
1076 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001077 "'%s' object has no attribute '%q'",
1078 mp_obj_get_type_str(base), attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001079 }
Damien George062478e2014-01-09 20:57:50 +00001080 }
1081 }
Damiena3977762013-10-09 23:10:10 +01001082}
1083
Damien Georged17926d2014-03-30 13:35:08 +01001084void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien5ac1b2e2013-10-18 19:58:12 +01001085 DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
Damien George062478e2014-01-09 20:57:50 +00001086 mp_obj_type_t *type = mp_obj_get_type(base);
Damien Georgeb1bbe962015-04-01 14:10:50 +00001087 if (type->attr != NULL) {
1088 mp_obj_t dest[2] = {MP_OBJ_SENTINEL, value};
1089 type->attr(base, attr, dest);
1090 if (dest[0] == MP_OBJ_NULL) {
1091 // success
Damien George062478e2014-01-09 20:57:50 +00001092 return;
1093 }
Damiena3977762013-10-09 23:10:10 +01001094 }
Damien George1e9a92f2014-11-06 17:36:16 +00001095 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001096 mp_raise_msg(&mp_type_AttributeError, "no such attribute");
Damien George1e9a92f2014-11-06 17:36:16 +00001097 } else {
1098 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001099 "'%s' object has no attribute '%q'",
1100 mp_obj_get_type_str(base), attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001101 }
Damiena3977762013-10-09 23:10:10 +01001102}
1103
Damien Georgeae8d8672016-01-09 23:14:54 +00001104mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001105 assert(o_in);
Damien Georgef6532bb2015-02-15 01:10:13 +00001106
Damien Georgeae8d8672016-01-09 23:14:54 +00001107 // if caller did not provide a buffer then allocate one on the heap
1108 if (iter_buf == NULL) {
1109 iter_buf = m_new_obj(mp_obj_iter_buf_t);
1110 }
1111
Damien Georgef6532bb2015-02-15 01:10:13 +00001112 // check for native getiter (corresponds to __iter__)
Damien George5fa93b62014-01-22 14:35:10 +00001113 mp_obj_type_t *type = mp_obj_get_type(o_in);
1114 if (type->getiter != NULL) {
Damien Georgeae8d8672016-01-09 23:14:54 +00001115 mp_obj_t iter = type->getiter(o_in, iter_buf);
Damien Georgef6532bb2015-02-15 01:10:13 +00001116 if (iter != MP_OBJ_NULL) {
1117 return iter;
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001118 }
Damien Georgef6532bb2015-02-15 01:10:13 +00001119 }
1120
1121 // check for __getitem__
1122 mp_obj_t dest[2];
1123 mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
1124 if (dest[0] != MP_OBJ_NULL) {
1125 // __getitem__ exists, create and return an iterator
Damien Georgeae8d8672016-01-09 23:14:54 +00001126 return mp_obj_new_getitem_iter(dest, iter_buf);
Damien Georgef6532bb2015-02-15 01:10:13 +00001127 }
1128
1129 // object not iterable
1130 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001131 mp_raise_msg(&mp_type_TypeError, "object not iterable");
Damience89a212013-10-15 22:25:17 +01001132 } else {
Damien Georgef6532bb2015-02-15 01:10:13 +00001133 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1134 "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
Damience89a212013-10-15 22:25:17 +01001135 }
1136}
1137
Damien Georgeea8d06c2014-04-17 23:19:36 +01001138// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
Damien George66eaf842014-03-26 19:27:58 +00001139// may also raise StopIteration()
Damien Georged17926d2014-03-30 13:35:08 +01001140mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001141 mp_obj_type_t *type = mp_obj_get_type(o_in);
1142 if (type->iternext != NULL) {
1143 return type->iternext(o_in);
Damience89a212013-10-15 22:25:17 +01001144 } else {
Damien George9e6e9352014-03-26 18:37:06 +00001145 // check for __next__ method
1146 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001147 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001148 if (dest[0] != MP_OBJ_NULL) {
1149 // __next__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +01001150 return mp_call_method_n_kw(0, 0, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001151 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001152 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001153 mp_raise_msg(&mp_type_TypeError, "object not an iterator");
Damien George1e9a92f2014-11-06 17:36:16 +00001154 } else {
1155 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1156 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1157 }
Damien George9e6e9352014-03-26 18:37:06 +00001158 }
Damien Georgec5966122014-02-15 16:10:44 +00001159 }
1160}
1161
Damien Georgeea8d06c2014-04-17 23:19:36 +01001162// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
Damien George66eaf842014-03-26 19:27:58 +00001163// may raise other exceptions
Damien Georged17926d2014-03-30 13:35:08 +01001164mp_obj_t mp_iternext(mp_obj_t o_in) {
Damien George953c23b2015-06-03 22:19:41 +01001165 MP_STACK_CHECK(); // enumerate, filter, map and zip can recursively call mp_iternext
Damien George66eaf842014-03-26 19:27:58 +00001166 mp_obj_type_t *type = mp_obj_get_type(o_in);
1167 if (type->iternext != NULL) {
1168 return type->iternext(o_in);
1169 } else {
1170 // check for __next__ method
1171 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001172 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George66eaf842014-03-26 19:27:58 +00001173 if (dest[0] != MP_OBJ_NULL) {
1174 // __next__ exists, call it and return its result
1175 nlr_buf_t nlr;
1176 if (nlr_push(&nlr) == 0) {
Damien Georged17926d2014-03-30 13:35:08 +01001177 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
Damien George66eaf842014-03-26 19:27:58 +00001178 nlr_pop();
1179 return ret;
1180 } else {
Damien George999cedb2015-11-27 17:01:44 +00001181 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))) {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001182 return MP_OBJ_STOP_ITERATION;
Damien George66eaf842014-03-26 19:27:58 +00001183 } else {
Damien George999cedb2015-11-27 17:01:44 +00001184 nlr_jump(nlr.ret_val);
Damien George66eaf842014-03-26 19:27:58 +00001185 }
1186 }
1187 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001188 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001189 mp_raise_msg(&mp_type_TypeError, "object not an iterator");
Damien George1e9a92f2014-11-06 17:36:16 +00001190 } else {
1191 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1192 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1193 }
Damien George66eaf842014-03-26 19:27:58 +00001194 }
1195 }
1196}
1197
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001198// TODO: Unclear what to do with StopIterarion exception here.
1199mp_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) {
Paul Sokolovsky7da06602014-03-31 04:19:12 +03001200 assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001201 mp_obj_type_t *type = mp_obj_get_type(self_in);
1202
1203 if (type == &mp_type_gen_instance) {
1204 return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
1205 }
1206
1207 if (type->iternext != NULL && send_value == mp_const_none) {
1208 mp_obj_t ret = type->iternext(self_in);
Paul Sokolovsky4ed7b7f2015-05-10 00:41:34 +03001209 if (ret != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001210 *ret_val = ret;
1211 return MP_VM_RETURN_YIELD;
1212 } else {
1213 // Emulate raise StopIteration()
1214 // Special case, handled in vm.c
1215 *ret_val = MP_OBJ_NULL;
1216 return MP_VM_RETURN_NORMAL;
1217 }
1218 }
1219
1220 mp_obj_t dest[3]; // Reserve slot for send() arg
1221
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001222 // Python instance iterator protocol
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001223 if (send_value == mp_const_none) {
1224 mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1225 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001226 nlr_buf_t nlr;
1227 if (nlr_push(&nlr) == 0) {
1228 *ret_val = mp_call_method_n_kw(0, 0, dest);
1229 nlr_pop();
1230 return MP_VM_RETURN_YIELD;
1231 } else {
Paul Sokolovskya0b2c6a2016-11-15 01:40:23 +03001232 *ret_val = MP_OBJ_FROM_PTR(nlr.ret_val);
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001233 return MP_VM_RETURN_EXCEPTION;
1234 }
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001235 }
1236 }
1237
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001238 // Either python instance generator protocol, or native object
1239 // generator protocol.
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001240 if (send_value != MP_OBJ_NULL) {
1241 mp_load_method(self_in, MP_QSTR_send, dest);
1242 dest[2] = send_value;
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001243 // TODO: This should have exception wrapping like __next__ case
1244 // above. Not done right away to think how to optimize native
1245 // generators better, see:
1246 // https://github.com/micropython/micropython/issues/2628
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001247 *ret_val = mp_call_method_n_kw(1, 0, dest);
1248 return MP_VM_RETURN_YIELD;
1249 }
1250
Damien George40863fc2017-01-17 00:09:56 +11001251 assert(throw_value != MP_OBJ_NULL);
1252 {
Damien George999cedb2015-11-27 17:01:44 +00001253 if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(throw_value)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001254 mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1255 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovsky4a60cac2015-05-10 02:39:45 +03001256 // TODO: Exceptions raised in close() are not propagated,
1257 // printed to sys.stderr
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001258 *ret_val = mp_call_method_n_kw(0, 0, dest);
1259 // We assume one can't "yield" from close()
1260 return MP_VM_RETURN_NORMAL;
1261 }
Damien Georgeaeb26552017-01-17 00:10:49 +11001262 } else {
1263 mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1264 if (dest[0] != MP_OBJ_NULL) {
1265 dest[2] = throw_value;
1266 *ret_val = mp_call_method_n_kw(1, 0, dest);
1267 // If .throw() method returned, we assume it's value to yield
1268 // - any exception would be thrown with nlr_raise().
1269 return MP_VM_RETURN_YIELD;
1270 }
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001271 }
1272 // If there's nowhere to throw exception into, then we assume that object
1273 // is just incapable to handle it, so any exception thrown into it
1274 // will be propagated up. This behavior is approved by test_pep380.py
1275 // test_delegation_of_close_to_non_generator(),
1276 // test_delegating_throw_to_non_generator()
1277 *ret_val = throw_value;
1278 return MP_VM_RETURN_EXCEPTION;
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001279 }
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001280}
1281
Damien Georged17926d2014-03-30 13:35:08 +01001282mp_obj_t mp_make_raise_obj(mp_obj_t o) {
Damien Georgec5966122014-02-15 16:10:44 +00001283 DEBUG_printf("raise %p\n", o);
1284 if (mp_obj_is_exception_type(o)) {
1285 // o is an exception type (it is derived from BaseException (or is BaseException))
1286 // create and return a new exception instance by calling o
Damien George22a08652014-02-15 21:05:25 +00001287 // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1288 // could have const instances in ROM which we return here instead
Damien Georged17926d2014-03-30 13:35:08 +01001289 return mp_call_function_n_kw(o, 0, 0, NULL);
Damien Georgec5966122014-02-15 16:10:44 +00001290 } else if (mp_obj_is_exception_instance(o)) {
1291 // o is an instance of an exception, so use it as the exception
1292 return o;
1293 } else {
1294 // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1295 return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
Damience89a212013-10-15 22:25:17 +01001296 }
1297}
1298
Damien Georged17926d2014-03-30 13:35:08 +01001299mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
Paul Sokolovsky6557a092015-06-27 00:32:35 +03001300 DEBUG_printf("import name '%s' level=%d\n", qstr_str(name), MP_OBJ_SMALL_INT_VALUE(level));
Damien George64131f32014-02-06 20:31:44 +00001301
Damiendb4c3612013-12-10 17:27:24 +00001302 // build args array
Damiend99b0522013-12-21 18:17:45 +00001303 mp_obj_t args[5];
Damien George5fa93b62014-01-22 14:35:10 +00001304 args[0] = MP_OBJ_NEW_QSTR(name);
Damiend99b0522013-12-21 18:17:45 +00001305 args[1] = mp_const_none; // TODO should be globals
1306 args[2] = mp_const_none; // TODO should be locals
Damiendb4c3612013-12-10 17:27:24 +00001307 args[3] = fromlist;
1308 args[4] = level; // must be 0; we don't yet support other values
1309
1310 // TODO lookup __import__ and call that instead of going straight to builtin implementation
Damiend99b0522013-12-21 18:17:45 +00001311 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001312}
1313
Damien Georged17926d2014-03-30 13:35:08 +01001314mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
Damien George64131f32014-02-06 20:31:44 +00001315 DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1316
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001317 mp_obj_t dest[2];
1318
1319 mp_load_method_maybe(module, name, dest);
1320
1321 if (dest[1] != MP_OBJ_NULL) {
1322 // Hopefully we can't import bound method from an object
1323import_error:
Damien George044c4732015-04-11 13:03:37 +01001324 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %q", name));
Damiendb4c3612013-12-10 17:27:24 +00001325 }
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001326
1327 if (dest[0] != MP_OBJ_NULL) {
1328 return dest[0];
1329 }
1330
1331 // See if it's a package, then can try FS import
Paul Sokolovskye5a37592014-10-25 21:04:13 +03001332 if (!mp_obj_is_package(module)) {
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001333 goto import_error;
1334 }
1335
1336 mp_load_method_maybe(module, MP_QSTR___name__, dest);
Damien Georged182b982014-08-30 14:19:41 +01001337 mp_uint_t pkg_name_len;
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001338 const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1339
stijn01d6be42014-05-05 12:18:27 +02001340 const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1341 char *dot_name = alloca(dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001342 memcpy(dot_name, pkg_name, pkg_name_len);
1343 dot_name[pkg_name_len] = '.';
1344 memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
stijn01d6be42014-05-05 12:18:27 +02001345 qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001346
1347 mp_obj_t args[5];
1348 args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
1349 args[1] = mp_const_none; // TODO should be globals
1350 args[2] = mp_const_none; // TODO should be locals
1351 args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
Paul Sokolovsky69f18672014-04-12 02:47:46 +03001352 args[4] = MP_OBJ_NEW_SMALL_INT(0);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001353
1354 // TODO lookup __import__ and call that instead of going straight to builtin implementation
1355 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001356}
1357
Damien Georged17926d2014-03-30 13:35:08 +01001358void mp_import_all(mp_obj_t module) {
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001359 DEBUG_printf("import all %p\n", module);
1360
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001361 // TODO: Support __all__
Damien George999cedb2015-11-27 17:01:44 +00001362 mp_map_t *map = mp_obj_dict_get_map(MP_OBJ_FROM_PTR(mp_obj_module_get_globals(module)));
Damien George4e3bac22017-02-16 15:32:34 +11001363 for (size_t i = 0; i < map->alloc; i++) {
Damien George8b0535e2014-04-05 21:53:54 +01001364 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001365 qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
1366 if (*qstr_str(name) != '_') {
1367 mp_store_name(name, map->table[i].value);
1368 }
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001369 }
1370 }
1371}
1372
Damien Georgedd5353a2015-12-18 12:35:44 +00001373#if MICROPY_ENABLE_COMPILER
1374
Damien Georgec4d08682014-10-05 20:13:34 +01001375// this is implemented in this file so it can optimise access to locals/globals
1376mp_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) {
Damien George0bfc7632015-02-07 18:33:58 +00001377 // save context
1378 mp_obj_dict_t *volatile old_globals = mp_globals_get();
1379 mp_obj_dict_t *volatile old_locals = mp_locals_get();
Damien Georgec4d08682014-10-05 20:13:34 +01001380
Damien George0bfc7632015-02-07 18:33:58 +00001381 // set new context
Damien Georgec4d08682014-10-05 20:13:34 +01001382 mp_globals_set(globals);
1383 mp_locals_set(locals);
1384
Damien Georgec4d08682014-10-05 20:13:34 +01001385 nlr_buf_t nlr;
1386 if (nlr_push(&nlr) == 0) {
Damien George0bfc7632015-02-07 18:33:58 +00001387 qstr source_name = lex->source_name;
Damien George58e0f4a2015-09-23 10:50:43 +01001388 mp_parse_tree_t parse_tree = mp_parse(lex, parse_input_kind);
1389 mp_obj_t module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, false);
Damien George0bfc7632015-02-07 18:33:58 +00001390
1391 mp_obj_t ret;
1392 if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
1393 // for compile only, return value is the module function
1394 ret = module_fun;
1395 } else {
1396 // execute module function and get return value
1397 ret = mp_call_function_0(module_fun);
1398 }
1399
1400 // finish nlr block, restore context and return value
Damien Georgec4d08682014-10-05 20:13:34 +01001401 nlr_pop();
1402 mp_globals_set(old_globals);
1403 mp_locals_set(old_locals);
1404 return ret;
1405 } else {
1406 // exception; restore context and re-raise same exception
1407 mp_globals_set(old_globals);
1408 mp_locals_set(old_locals);
Damien George999cedb2015-11-27 17:01:44 +00001409 nlr_jump(nlr.ret_val);
Damien Georgec4d08682014-10-05 20:13:34 +01001410 }
1411}
1412
Damien Georgedd5353a2015-12-18 12:35:44 +00001413#endif // MICROPY_ENABLE_COMPILER
1414
Damien Georgeb0261342014-09-23 18:10:17 +01001415void *m_malloc_fail(size_t num_bytes) {
Damien George978d2e52016-01-08 13:49:58 +00001416 DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes);
Damien George40914452014-10-09 16:44:43 +01001417 if (0) {
1418 // dummy
1419 #if MICROPY_ENABLE_GC
1420 } else if (gc_is_locked()) {
Damien George7d0d7212016-10-17 12:17:37 +11001421 mp_raise_msg(&mp_type_MemoryError, "memory allocation failed, heap is locked");
Damien George40914452014-10-09 16:44:43 +01001422 #endif
Dave Hylands3556e452014-10-07 00:50:20 -07001423 } else {
Damien George40914452014-10-09 16:44:43 +01001424 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
Damien George978d2e52016-01-08 13:49:58 +00001425 "memory allocation failed, allocating %u bytes", (uint)num_bytes));
Dave Hylands3556e452014-10-07 00:50:20 -07001426 }
Damien George6902eed2014-04-04 10:52:59 +00001427}
1428
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001429NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg) {
1430 nlr_raise(mp_obj_new_exception_msg(exc_type, msg));
1431}
1432
1433NORETURN void mp_raise_ValueError(const char *msg) {
1434 mp_raise_msg(&mp_type_ValueError, msg);
1435}
1436
1437NORETURN void mp_raise_TypeError(const char *msg) {
1438 mp_raise_msg(&mp_type_TypeError, msg);
1439}
1440
Damien George3a0a7712016-10-07 13:31:59 +11001441NORETURN void mp_raise_OSError(int errno_) {
1442 nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno_)));
1443}
1444
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001445NORETURN void mp_not_implemented(const char *msg) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001446 mp_raise_msg(&mp_type_NotImplementedError, msg);
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001447}