blob: db6a6f18f91dd43745bc65347f90db973cdc2db2 [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 Georgee6003f42017-02-13 15:44:31 +1100748 mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest), NULL);
Damien George470c4292016-05-07 22:02:46 +0100749
750 mp_obj_t key;
751 while ((key = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
752 // expand size of args array if needed
Damien George230fec72014-03-30 21:21:24 +0100753 if (args2_len + 1 >= args2_alloc) {
754 uint new_alloc = args2_alloc * 2;
755 if (new_alloc < 4) {
756 new_alloc = 4;
757 }
758 args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
759 args2_alloc = new_alloc;
760 }
Damien George470c4292016-05-07 22:02:46 +0100761
Damien Georgefea40ad2016-04-21 16:51:36 +0100762 // the key must be a qstr, so intern it if it's a string
Damien Georgefea40ad2016-04-21 16:51:36 +0100763 if (MP_OBJ_IS_TYPE(key, &mp_type_str)) {
764 key = mp_obj_str_intern(key);
765 }
Damien George470c4292016-05-07 22:02:46 +0100766
767 // get the value corresponding to the key
768 mp_load_method(kw_dict, MP_QSTR___getitem__, dest);
769 dest[2] = key;
770 mp_obj_t value = mp_call_method_n_kw(1, 0, dest);
771
772 // store the key/value pair in the argument array
Damien Georgefea40ad2016-04-21 16:51:36 +0100773 args2[args2_len++] = key;
Damien George470c4292016-05-07 22:02:46 +0100774 args2[args2_len++] = value;
Damien George230fec72014-03-30 21:21:24 +0100775 }
776 }
777
Paul Sokolovskye6c6fe32015-03-28 01:14:45 +0200778 out_args->fun = fun;
779 out_args->args = args2;
780 out_args->n_args = pos_args_len;
781 out_args->n_kw = (args2_len - pos_args_len) / 2;
782 out_args->n_alloc = args2_alloc;
783}
784
Damien George4e3bac22017-02-16 15:32:34 +1100785mp_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 +0100786 mp_call_args_t out_args;
Paul Sokolovskye6c6fe32015-03-28 01:14:45 +0200787 mp_call_prepare_args_n_kw_var(have_self, n_args_n_kw, args, &out_args);
788
789 mp_obj_t res = mp_call_function_n_kw(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args);
790 m_del(mp_obj_t, out_args.args, out_args.n_alloc);
Damien George230fec72014-03-30 21:21:24 +0100791
792 return res;
793}
794
Damien George932bf1c2014-01-18 23:42:49 +0000795// unpacked items are stored in reverse order into the array pointed to by items
Damien George4e3bac22017-02-16 15:32:34 +1100796void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) {
Damien George9c4cbe22014-08-30 14:04:14 +0100797 mp_uint_t seq_len;
Damien George3e1a5c12014-03-29 13:43:38 +0000798 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 +0000799 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000800 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000801 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
802 } else {
803 mp_obj_list_get(seq_in, &seq_len, &seq_items);
Damien86c7fc72013-11-26 15:16:41 +0000804 }
Damiend99b0522013-12-21 18:17:45 +0000805 if (seq_len < num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200806 goto too_short;
Damiend99b0522013-12-21 18:17:45 +0000807 } else if (seq_len > num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200808 goto too_long;
Damiend99b0522013-12-21 18:17:45 +0000809 }
Damien George4e3bac22017-02-16 15:32:34 +1100810 for (size_t i = 0; i < num; i++) {
Damien George932bf1c2014-01-18 23:42:49 +0000811 items[i] = seq_items[num - 1 - i];
812 }
Damien86c7fc72013-11-26 15:16:41 +0000813 } else {
Damien Georgeae8d8672016-01-09 23:14:54 +0000814 mp_obj_iter_buf_t iter_buf;
815 mp_obj_t iterable = mp_getiter(seq_in, &iter_buf);
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200816
817 for (seq_len = 0; seq_len < num; seq_len++) {
Damien Georged17926d2014-03-30 13:35:08 +0100818 mp_obj_t el = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100819 if (el == MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200820 goto too_short;
821 }
822 items[num - 1 - seq_len] = el;
823 }
Damien Georgeea8d06c2014-04-17 23:19:36 +0100824 if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200825 goto too_long;
826 }
Damien86c7fc72013-11-26 15:16:41 +0000827 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200828 return;
829
830too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000831 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100832 mp_raise_msg(&mp_type_ValueError, "wrong number of values to unpack");
Damien George1e9a92f2014-11-06 17:36:16 +0000833 } else {
834 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George2a1cca22016-03-14 22:40:39 +0000835 "need more than %d values to unpack", (int)seq_len));
Damien George1e9a92f2014-11-06 17:36:16 +0000836 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200837too_long:
Damien George1e9a92f2014-11-06 17:36:16 +0000838 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100839 mp_raise_msg(&mp_type_ValueError, "wrong number of values to unpack");
Damien George1e9a92f2014-11-06 17:36:16 +0000840 } else {
841 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George2a1cca22016-03-14 22:40:39 +0000842 "too many values to unpack (expected %d)", (int)num));
Damien George1e9a92f2014-11-06 17:36:16 +0000843 }
Damien86c7fc72013-11-26 15:16:41 +0000844}
845
Damien George495d7812014-04-08 17:51:47 +0100846// unpacked items are stored in reverse order into the array pointed to by items
Damien George4e3bac22017-02-16 15:32:34 +1100847void mp_unpack_ex(mp_obj_t seq_in, size_t num_in, mp_obj_t *items) {
848 size_t num_left = num_in & 0xff;
849 size_t num_right = (num_in >> 8) & 0xff;
Damien Georgeeaaebf32014-09-23 10:59:05 +0100850 DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
Damien George9c4cbe22014-08-30 14:04:14 +0100851 mp_uint_t seq_len;
Damien George495d7812014-04-08 17:51:47 +0100852 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
853 mp_obj_t *seq_items;
854 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
855 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
856 } else {
857 if (num_left == 0 && num_right == 0) {
858 // *a, = b # sets a to b if b is a list
859 items[0] = seq_in;
860 return;
861 }
862 mp_obj_list_get(seq_in, &seq_len, &seq_items);
863 }
864 if (seq_len < num_left + num_right) {
865 goto too_short;
866 }
Damien George4e3bac22017-02-16 15:32:34 +1100867 for (size_t i = 0; i < num_right; i++) {
Damien George495d7812014-04-08 17:51:47 +0100868 items[i] = seq_items[seq_len - 1 - i];
869 }
870 items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
Damien George4e3bac22017-02-16 15:32:34 +1100871 for (size_t i = 0; i < num_left; i++) {
Damien George495d7812014-04-08 17:51:47 +0100872 items[num_right + 1 + i] = seq_items[num_left - 1 - i];
873 }
874 } else {
875 // Generic iterable; this gets a bit messy: we unpack known left length to the
876 // items destination array, then the rest to a dynamically created list. Once the
877 // iterable is exhausted, we take from this list for the right part of the items.
878 // TODO Improve to waste less memory in the dynamically created list.
Damien Georgee6003f42017-02-13 15:44:31 +1100879 mp_obj_t iterable = mp_getiter(seq_in, NULL);
Damien George495d7812014-04-08 17:51:47 +0100880 mp_obj_t item;
881 for (seq_len = 0; seq_len < num_left; seq_len++) {
882 item = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100883 if (item == MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100884 goto too_short;
885 }
886 items[num_left + num_right + 1 - 1 - seq_len] = item;
887 }
Damien George999cedb2015-11-27 17:01:44 +0000888 mp_obj_list_t *rest = MP_OBJ_TO_PTR(mp_obj_new_list(0, NULL));
Damien Georgeea8d06c2014-04-17 23:19:36 +0100889 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George999cedb2015-11-27 17:01:44 +0000890 mp_obj_list_append(MP_OBJ_FROM_PTR(rest), item);
Damien George495d7812014-04-08 17:51:47 +0100891 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100892 if (rest->len < num_right) {
Damien George495d7812014-04-08 17:51:47 +0100893 goto too_short;
894 }
Damien George999cedb2015-11-27 17:01:44 +0000895 items[num_right] = MP_OBJ_FROM_PTR(rest);
Damien George4e3bac22017-02-16 15:32:34 +1100896 for (size_t i = 0; i < num_right; i++) {
Damien Georgeca6d75f2014-08-30 15:17:47 +0100897 items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
Damien George495d7812014-04-08 17:51:47 +0100898 }
Damien George999cedb2015-11-27 17:01:44 +0000899 mp_obj_list_set_len(MP_OBJ_FROM_PTR(rest), rest->len - num_right);
Damien George495d7812014-04-08 17:51:47 +0100900 }
901 return;
902
903too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000904 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100905 mp_raise_msg(&mp_type_ValueError, "wrong number of values to unpack");
Damien George1e9a92f2014-11-06 17:36:16 +0000906 } else {
907 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George2a1cca22016-03-14 22:40:39 +0000908 "need more than %d values to unpack", (int)seq_len));
Damien George1e9a92f2014-11-06 17:36:16 +0000909 }
Damien George495d7812014-04-08 17:51:47 +0100910}
911
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300912mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
Damien George062478e2014-01-09 20:57:50 +0000913 DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300914 // use load_method
Damien George062478e2014-01-09 20:57:50 +0000915 mp_obj_t dest[2];
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300916 mp_load_method(base, attr, dest);
917 if (dest[1] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000918 // load_method returned just a normal attribute
Damien George20006db2014-01-18 14:10:48 +0000919 return dest[0];
Damien George062478e2014-01-09 20:57:50 +0000920 } else {
921 // load_method returned a method, so build a bound method object
922 return mp_obj_new_bound_meth(dest[0], dest[1]);
Damiend99b0522013-12-21 18:17:45 +0000923 }
Damiend99b0522013-12-21 18:17:45 +0000924}
925
Damien George06593fb2015-06-19 12:49:10 +0000926#if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
927
928// The following "checked fun" type is local to the mp_convert_member_lookup
929// function, and serves to check that the first argument to a builtin function
930// has the correct type.
931
932typedef struct _mp_obj_checked_fun_t {
933 mp_obj_base_t base;
934 const mp_obj_type_t *type;
935 mp_obj_t fun;
936} mp_obj_checked_fun_t;
937
Damien Georgea0c97812016-01-03 09:59:18 +0000938STATIC 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 +0000939 mp_obj_checked_fun_t *self = MP_OBJ_TO_PTR(self_in);
Damien George06593fb2015-06-19 12:49:10 +0000940 if (n_args > 0) {
941 const mp_obj_type_t *arg0_type = mp_obj_get_type(args[0]);
942 if (arg0_type != self->type) {
943 if (MICROPY_ERROR_REPORTING != MICROPY_ERROR_REPORTING_DETAILED) {
Damien George7d0d7212016-10-17 12:17:37 +1100944 mp_raise_msg(&mp_type_TypeError, "argument has wrong type");
Damien George06593fb2015-06-19 12:49:10 +0000945 } else {
946 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
947 "argument should be a '%q' not a '%q'", self->type->name, arg0_type->name));
948 }
949 }
950 }
951 return mp_call_function_n_kw(self->fun, n_args, n_kw, args);
952}
953
954STATIC const mp_obj_type_t mp_type_checked_fun = {
955 { &mp_type_type },
956 .name = MP_QSTR_function,
957 .call = checked_fun_call,
958};
959
960STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) {
961 mp_obj_checked_fun_t *o = m_new_obj(mp_obj_checked_fun_t);
962 o->base.type = &mp_type_checked_fun;
963 o->type = type;
964 o->fun = fun;
Damien George999cedb2015-11-27 17:01:44 +0000965 return MP_OBJ_FROM_PTR(o);
Damien George06593fb2015-06-19 12:49:10 +0000966}
967
968#endif // MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
969
Damien George55b74d12015-03-21 14:21:54 +0000970// Given a member that was extracted from an instance, convert it correctly
971// and put the result in the dest[] array for a possible method call.
972// Conversion means dealing with static/class methods, callables, and values.
973// see http://docs.python.org/3/howto/descriptor.html
974void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) {
975 if (MP_OBJ_IS_TYPE(member, &mp_type_staticmethod)) {
976 // return just the function
Damien George999cedb2015-11-27 17:01:44 +0000977 dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
Damien George55b74d12015-03-21 14:21:54 +0000978 } else if (MP_OBJ_IS_TYPE(member, &mp_type_classmethod)) {
979 // return a bound method, with self being the type of this object
Damien George3ff259a2015-12-09 17:30:01 +0000980 // this type should be the type of the original instance, not the base
981 // type (which is what is passed in the 'type' argument to this function)
982 if (self != MP_OBJ_NULL) {
983 type = mp_obj_get_type(self);
984 }
Damien George999cedb2015-11-27 17:01:44 +0000985 dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
986 dest[1] = MP_OBJ_FROM_PTR(type);
Damien George55b74d12015-03-21 14:21:54 +0000987 } else if (MP_OBJ_IS_TYPE(member, &mp_type_type)) {
988 // Don't try to bind types (even though they're callable)
989 dest[0] = member;
Damien George78913212015-12-26 12:41:31 +0000990 } else if (MP_OBJ_IS_FUN(member)
991 || (MP_OBJ_IS_OBJ(member)
992 && (((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure
993 || ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) {
994 // only functions, closures and generators objects can be bound to self
Damien George06593fb2015-06-19 12:49:10 +0000995 #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
Damien George571e6f22016-10-18 11:49:27 +1100996 const mp_obj_type_t *m_type = ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type;
997 if (self == MP_OBJ_NULL
998 && (m_type == &mp_type_fun_builtin_0
999 || m_type == &mp_type_fun_builtin_1
1000 || m_type == &mp_type_fun_builtin_2
1001 || m_type == &mp_type_fun_builtin_3
1002 || m_type == &mp_type_fun_builtin_var)) {
Damien George06593fb2015-06-19 12:49:10 +00001003 // we extracted a builtin method without a first argument, so we must
1004 // wrap this function in a type checker
1005 dest[0] = mp_obj_new_checked_fun(type, member);
1006 } else
1007 #endif
1008 {
1009 // return a bound method, with self being this object
1010 dest[0] = member;
1011 dest[1] = self;
1012 }
Damien George55b74d12015-03-21 14:21:54 +00001013 } else {
1014 // class member is a value, so just return that value
1015 dest[0] = member;
1016 }
1017}
1018
Damien George7c9c6672014-01-25 00:17:36 +00001019// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
1020// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
1021// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +02001022void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) {
Damien George062478e2014-01-09 20:57:50 +00001023 // clear output to indicate no attribute/method found yet
1024 dest[0] = MP_OBJ_NULL;
1025 dest[1] = MP_OBJ_NULL;
1026
1027 // get the type
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +02001028 mp_obj_type_t *type = mp_obj_get_type(obj);
Damien George062478e2014-01-09 20:57:50 +00001029
Damien Georgee44d26a2014-03-31 22:57:56 +01001030 // look for built-in names
1031 if (0) {
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +03001032#if MICROPY_CPYTHON_COMPAT
Damien Georgee44d26a2014-03-31 22:57:56 +01001033 } else if (attr == MP_QSTR___class__) {
1034 // a.__class__ is equivalent to type(a)
Damien George999cedb2015-11-27 17:01:44 +00001035 dest[0] = MP_OBJ_FROM_PTR(type);
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +03001036#endif
Damien Georgee44d26a2014-03-31 22:57:56 +01001037
1038 } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
Damien George999cedb2015-11-27 17:01:44 +00001039 dest[0] = MP_OBJ_FROM_PTR(&mp_builtin_next_obj);
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +02001040 dest[1] = obj;
Damien Georgee44d26a2014-03-31 22:57:56 +01001041
Damien Georgeb1bbe962015-04-01 14:10:50 +00001042 } else if (type->attr != NULL) {
Damien Georgee44d26a2014-03-31 22:57:56 +01001043 // this type can do its own load, so call it
Damien Georgeb1bbe962015-04-01 14:10:50 +00001044 type->attr(obj, attr, dest);
Damien Georgee44d26a2014-03-31 22:57:56 +01001045
1046 } else if (type->locals_dict != NULL) {
1047 // generic method lookup
1048 // this is a lookup in the object (ie not class or type)
Damien George999cedb2015-11-27 17:01:44 +00001049 assert(type->locals_dict->base.type == &mp_type_dict); // Micro Python restriction, for now
1050 mp_map_t *locals_map = &type->locals_dict->map;
Damien Georgee44d26a2014-03-31 22:57:56 +01001051 mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
1052 if (elem != NULL) {
Damien George55b74d12015-03-21 14:21:54 +00001053 mp_convert_member_lookup(obj, type, elem->value, dest);
Damiend57eba52013-11-02 23:58:14 +00001054 }
Damiena3977762013-10-09 23:10:10 +01001055 }
Damien George7c9c6672014-01-25 00:17:36 +00001056}
Damiena3977762013-10-09 23:10:10 +01001057
Damien Georged17926d2014-03-30 13:35:08 +01001058void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George7c9c6672014-01-25 00:17:36 +00001059 DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
1060
Damien Georged17926d2014-03-30 13:35:08 +01001061 mp_load_method_maybe(base, attr, dest);
Damien George7c9c6672014-01-25 00:17:36 +00001062
1063 if (dest[0] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +00001064 // no attribute/method called attr
Damien George1e9a92f2014-11-06 17:36:16 +00001065 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001066 mp_raise_msg(&mp_type_AttributeError, "no such attribute");
Damien George062478e2014-01-09 20:57:50 +00001067 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001068 // following CPython, we give a more detailed error message for type objects
1069 if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
1070 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001071 "type object '%q' has no attribute '%q'",
Damien George999cedb2015-11-27 17:01:44 +00001072 ((mp_obj_type_t*)MP_OBJ_TO_PTR(base))->name, attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001073 } else {
1074 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001075 "'%s' object has no attribute '%q'",
1076 mp_obj_get_type_str(base), attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001077 }
Damien George062478e2014-01-09 20:57:50 +00001078 }
1079 }
Damiena3977762013-10-09 23:10:10 +01001080}
1081
Damien Georged17926d2014-03-30 13:35:08 +01001082void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien5ac1b2e2013-10-18 19:58:12 +01001083 DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
Damien George062478e2014-01-09 20:57:50 +00001084 mp_obj_type_t *type = mp_obj_get_type(base);
Damien Georgeb1bbe962015-04-01 14:10:50 +00001085 if (type->attr != NULL) {
1086 mp_obj_t dest[2] = {MP_OBJ_SENTINEL, value};
1087 type->attr(base, attr, dest);
1088 if (dest[0] == MP_OBJ_NULL) {
1089 // success
Damien George062478e2014-01-09 20:57:50 +00001090 return;
1091 }
Damiena3977762013-10-09 23:10:10 +01001092 }
Damien George1e9a92f2014-11-06 17:36:16 +00001093 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001094 mp_raise_msg(&mp_type_AttributeError, "no such attribute");
Damien George1e9a92f2014-11-06 17:36:16 +00001095 } else {
1096 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001097 "'%s' object has no attribute '%q'",
1098 mp_obj_get_type_str(base), attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001099 }
Damiena3977762013-10-09 23:10:10 +01001100}
1101
Damien Georgeae8d8672016-01-09 23:14:54 +00001102mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001103 assert(o_in);
Damien Georgecb630062017-01-17 15:38:32 +11001104 mp_obj_type_t *type = mp_obj_get_type(o_in);
1105
1106 // Check for native getiter which is the identity. We handle this case explicitly
1107 // so we don't unnecessarily allocate any RAM for the iter_buf, which won't be used.
1108 if (type->getiter == mp_identity_getiter) {
1109 return o_in;
1110 }
Damien Georgef6532bb2015-02-15 01:10:13 +00001111
Damien Georgeae8d8672016-01-09 23:14:54 +00001112 // if caller did not provide a buffer then allocate one on the heap
1113 if (iter_buf == NULL) {
1114 iter_buf = m_new_obj(mp_obj_iter_buf_t);
1115 }
1116
Damien Georgef6532bb2015-02-15 01:10:13 +00001117 // check for native getiter (corresponds to __iter__)
Damien George5fa93b62014-01-22 14:35:10 +00001118 if (type->getiter != NULL) {
Damien Georgeae8d8672016-01-09 23:14:54 +00001119 mp_obj_t iter = type->getiter(o_in, iter_buf);
Damien Georgef6532bb2015-02-15 01:10:13 +00001120 if (iter != MP_OBJ_NULL) {
1121 return iter;
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001122 }
Damien Georgef6532bb2015-02-15 01:10:13 +00001123 }
1124
1125 // check for __getitem__
1126 mp_obj_t dest[2];
1127 mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
1128 if (dest[0] != MP_OBJ_NULL) {
1129 // __getitem__ exists, create and return an iterator
Damien Georgeae8d8672016-01-09 23:14:54 +00001130 return mp_obj_new_getitem_iter(dest, iter_buf);
Damien Georgef6532bb2015-02-15 01:10:13 +00001131 }
1132
1133 // object not iterable
1134 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001135 mp_raise_msg(&mp_type_TypeError, "object not iterable");
Damience89a212013-10-15 22:25:17 +01001136 } else {
Damien Georgef6532bb2015-02-15 01:10:13 +00001137 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1138 "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
Damience89a212013-10-15 22:25:17 +01001139 }
1140}
1141
Damien Georgeea8d06c2014-04-17 23:19:36 +01001142// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
Damien George66eaf842014-03-26 19:27:58 +00001143// may also raise StopIteration()
Damien Georged17926d2014-03-30 13:35:08 +01001144mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001145 mp_obj_type_t *type = mp_obj_get_type(o_in);
1146 if (type->iternext != NULL) {
1147 return type->iternext(o_in);
Damience89a212013-10-15 22:25:17 +01001148 } else {
Damien George9e6e9352014-03-26 18:37:06 +00001149 // check for __next__ method
1150 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001151 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001152 if (dest[0] != MP_OBJ_NULL) {
1153 // __next__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +01001154 return mp_call_method_n_kw(0, 0, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001155 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001156 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001157 mp_raise_msg(&mp_type_TypeError, "object not an iterator");
Damien George1e9a92f2014-11-06 17:36:16 +00001158 } else {
1159 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1160 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1161 }
Damien George9e6e9352014-03-26 18:37:06 +00001162 }
Damien Georgec5966122014-02-15 16:10:44 +00001163 }
1164}
1165
Damien Georgeea8d06c2014-04-17 23:19:36 +01001166// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
Damien George66eaf842014-03-26 19:27:58 +00001167// may raise other exceptions
Damien Georged17926d2014-03-30 13:35:08 +01001168mp_obj_t mp_iternext(mp_obj_t o_in) {
Damien George953c23b2015-06-03 22:19:41 +01001169 MP_STACK_CHECK(); // enumerate, filter, map and zip can recursively call mp_iternext
Damien George66eaf842014-03-26 19:27:58 +00001170 mp_obj_type_t *type = mp_obj_get_type(o_in);
1171 if (type->iternext != NULL) {
1172 return type->iternext(o_in);
1173 } else {
1174 // check for __next__ method
1175 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001176 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George66eaf842014-03-26 19:27:58 +00001177 if (dest[0] != MP_OBJ_NULL) {
1178 // __next__ exists, call it and return its result
1179 nlr_buf_t nlr;
1180 if (nlr_push(&nlr) == 0) {
Damien Georged17926d2014-03-30 13:35:08 +01001181 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
Damien George66eaf842014-03-26 19:27:58 +00001182 nlr_pop();
1183 return ret;
1184 } else {
Damien George999cedb2015-11-27 17:01:44 +00001185 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 +01001186 return MP_OBJ_STOP_ITERATION;
Damien George66eaf842014-03-26 19:27:58 +00001187 } else {
Damien George999cedb2015-11-27 17:01:44 +00001188 nlr_jump(nlr.ret_val);
Damien George66eaf842014-03-26 19:27:58 +00001189 }
1190 }
1191 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001192 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +11001193 mp_raise_msg(&mp_type_TypeError, "object not an iterator");
Damien George1e9a92f2014-11-06 17:36:16 +00001194 } else {
1195 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1196 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1197 }
Damien George66eaf842014-03-26 19:27:58 +00001198 }
1199 }
1200}
1201
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001202// TODO: Unclear what to do with StopIterarion exception here.
1203mp_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 +03001204 assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001205 mp_obj_type_t *type = mp_obj_get_type(self_in);
1206
1207 if (type == &mp_type_gen_instance) {
1208 return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
1209 }
1210
1211 if (type->iternext != NULL && send_value == mp_const_none) {
1212 mp_obj_t ret = type->iternext(self_in);
Paul Sokolovsky4ed7b7f2015-05-10 00:41:34 +03001213 if (ret != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001214 *ret_val = ret;
1215 return MP_VM_RETURN_YIELD;
1216 } else {
1217 // Emulate raise StopIteration()
1218 // Special case, handled in vm.c
1219 *ret_val = MP_OBJ_NULL;
1220 return MP_VM_RETURN_NORMAL;
1221 }
1222 }
1223
1224 mp_obj_t dest[3]; // Reserve slot for send() arg
1225
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001226 // Python instance iterator protocol
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001227 if (send_value == mp_const_none) {
1228 mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1229 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001230 nlr_buf_t nlr;
1231 if (nlr_push(&nlr) == 0) {
1232 *ret_val = mp_call_method_n_kw(0, 0, dest);
1233 nlr_pop();
1234 return MP_VM_RETURN_YIELD;
1235 } else {
Paul Sokolovskya0b2c6a2016-11-15 01:40:23 +03001236 *ret_val = MP_OBJ_FROM_PTR(nlr.ret_val);
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001237 return MP_VM_RETURN_EXCEPTION;
1238 }
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001239 }
1240 }
1241
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001242 // Either python instance generator protocol, or native object
1243 // generator protocol.
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001244 if (send_value != MP_OBJ_NULL) {
1245 mp_load_method(self_in, MP_QSTR_send, dest);
1246 dest[2] = send_value;
Paul Sokolovsky79d996a2016-11-15 01:10:34 +03001247 // TODO: This should have exception wrapping like __next__ case
1248 // above. Not done right away to think how to optimize native
1249 // generators better, see:
1250 // https://github.com/micropython/micropython/issues/2628
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001251 *ret_val = mp_call_method_n_kw(1, 0, dest);
1252 return MP_VM_RETURN_YIELD;
1253 }
1254
Damien George40863fc2017-01-17 00:09:56 +11001255 assert(throw_value != MP_OBJ_NULL);
1256 {
Damien George999cedb2015-11-27 17:01:44 +00001257 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 +03001258 mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1259 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovsky4a60cac2015-05-10 02:39:45 +03001260 // TODO: Exceptions raised in close() are not propagated,
1261 // printed to sys.stderr
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001262 *ret_val = mp_call_method_n_kw(0, 0, dest);
1263 // We assume one can't "yield" from close()
1264 return MP_VM_RETURN_NORMAL;
1265 }
Damien Georgeaeb26552017-01-17 00:10:49 +11001266 } else {
1267 mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1268 if (dest[0] != MP_OBJ_NULL) {
1269 dest[2] = throw_value;
1270 *ret_val = mp_call_method_n_kw(1, 0, dest);
1271 // If .throw() method returned, we assume it's value to yield
1272 // - any exception would be thrown with nlr_raise().
1273 return MP_VM_RETURN_YIELD;
1274 }
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001275 }
1276 // If there's nowhere to throw exception into, then we assume that object
1277 // is just incapable to handle it, so any exception thrown into it
1278 // will be propagated up. This behavior is approved by test_pep380.py
1279 // test_delegation_of_close_to_non_generator(),
1280 // test_delegating_throw_to_non_generator()
1281 *ret_val = throw_value;
1282 return MP_VM_RETURN_EXCEPTION;
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001283 }
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001284}
1285
Damien Georged17926d2014-03-30 13:35:08 +01001286mp_obj_t mp_make_raise_obj(mp_obj_t o) {
Damien Georgec5966122014-02-15 16:10:44 +00001287 DEBUG_printf("raise %p\n", o);
1288 if (mp_obj_is_exception_type(o)) {
1289 // o is an exception type (it is derived from BaseException (or is BaseException))
1290 // create and return a new exception instance by calling o
Damien George22a08652014-02-15 21:05:25 +00001291 // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1292 // could have const instances in ROM which we return here instead
Damien Georged17926d2014-03-30 13:35:08 +01001293 return mp_call_function_n_kw(o, 0, 0, NULL);
Damien Georgec5966122014-02-15 16:10:44 +00001294 } else if (mp_obj_is_exception_instance(o)) {
1295 // o is an instance of an exception, so use it as the exception
1296 return o;
1297 } else {
1298 // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1299 return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
Damience89a212013-10-15 22:25:17 +01001300 }
1301}
1302
Damien Georged17926d2014-03-30 13:35:08 +01001303mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
Paul Sokolovsky6557a092015-06-27 00:32:35 +03001304 DEBUG_printf("import name '%s' level=%d\n", qstr_str(name), MP_OBJ_SMALL_INT_VALUE(level));
Damien George64131f32014-02-06 20:31:44 +00001305
Damiendb4c3612013-12-10 17:27:24 +00001306 // build args array
Damiend99b0522013-12-21 18:17:45 +00001307 mp_obj_t args[5];
Damien George5fa93b62014-01-22 14:35:10 +00001308 args[0] = MP_OBJ_NEW_QSTR(name);
Damiend99b0522013-12-21 18:17:45 +00001309 args[1] = mp_const_none; // TODO should be globals
1310 args[2] = mp_const_none; // TODO should be locals
Damiendb4c3612013-12-10 17:27:24 +00001311 args[3] = fromlist;
1312 args[4] = level; // must be 0; we don't yet support other values
1313
1314 // TODO lookup __import__ and call that instead of going straight to builtin implementation
Damiend99b0522013-12-21 18:17:45 +00001315 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001316}
1317
Damien Georged17926d2014-03-30 13:35:08 +01001318mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
Damien George64131f32014-02-06 20:31:44 +00001319 DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1320
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001321 mp_obj_t dest[2];
1322
1323 mp_load_method_maybe(module, name, dest);
1324
1325 if (dest[1] != MP_OBJ_NULL) {
1326 // Hopefully we can't import bound method from an object
1327import_error:
Damien George044c4732015-04-11 13:03:37 +01001328 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %q", name));
Damiendb4c3612013-12-10 17:27:24 +00001329 }
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001330
1331 if (dest[0] != MP_OBJ_NULL) {
1332 return dest[0];
1333 }
1334
1335 // See if it's a package, then can try FS import
Paul Sokolovskye5a37592014-10-25 21:04:13 +03001336 if (!mp_obj_is_package(module)) {
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001337 goto import_error;
1338 }
1339
1340 mp_load_method_maybe(module, MP_QSTR___name__, dest);
Damien Georged182b982014-08-30 14:19:41 +01001341 mp_uint_t pkg_name_len;
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001342 const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1343
stijn01d6be42014-05-05 12:18:27 +02001344 const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1345 char *dot_name = alloca(dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001346 memcpy(dot_name, pkg_name, pkg_name_len);
1347 dot_name[pkg_name_len] = '.';
1348 memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
stijn01d6be42014-05-05 12:18:27 +02001349 qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001350
1351 mp_obj_t args[5];
1352 args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
1353 args[1] = mp_const_none; // TODO should be globals
1354 args[2] = mp_const_none; // TODO should be locals
1355 args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
Paul Sokolovsky69f18672014-04-12 02:47:46 +03001356 args[4] = MP_OBJ_NEW_SMALL_INT(0);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001357
1358 // TODO lookup __import__ and call that instead of going straight to builtin implementation
1359 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001360}
1361
Damien Georged17926d2014-03-30 13:35:08 +01001362void mp_import_all(mp_obj_t module) {
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001363 DEBUG_printf("import all %p\n", module);
1364
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001365 // TODO: Support __all__
Damien George999cedb2015-11-27 17:01:44 +00001366 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 +11001367 for (size_t i = 0; i < map->alloc; i++) {
Damien George8b0535e2014-04-05 21:53:54 +01001368 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001369 qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
1370 if (*qstr_str(name) != '_') {
1371 mp_store_name(name, map->table[i].value);
1372 }
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001373 }
1374 }
1375}
1376
Damien Georgedd5353a2015-12-18 12:35:44 +00001377#if MICROPY_ENABLE_COMPILER
1378
Damien Georgec4d08682014-10-05 20:13:34 +01001379// this is implemented in this file so it can optimise access to locals/globals
1380mp_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 +00001381 // save context
1382 mp_obj_dict_t *volatile old_globals = mp_globals_get();
1383 mp_obj_dict_t *volatile old_locals = mp_locals_get();
Damien Georgec4d08682014-10-05 20:13:34 +01001384
Damien George0bfc7632015-02-07 18:33:58 +00001385 // set new context
Damien Georgec4d08682014-10-05 20:13:34 +01001386 mp_globals_set(globals);
1387 mp_locals_set(locals);
1388
Damien Georgec4d08682014-10-05 20:13:34 +01001389 nlr_buf_t nlr;
1390 if (nlr_push(&nlr) == 0) {
Damien George0bfc7632015-02-07 18:33:58 +00001391 qstr source_name = lex->source_name;
Damien George58e0f4a2015-09-23 10:50:43 +01001392 mp_parse_tree_t parse_tree = mp_parse(lex, parse_input_kind);
1393 mp_obj_t module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, false);
Damien George0bfc7632015-02-07 18:33:58 +00001394
1395 mp_obj_t ret;
1396 if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
1397 // for compile only, return value is the module function
1398 ret = module_fun;
1399 } else {
1400 // execute module function and get return value
1401 ret = mp_call_function_0(module_fun);
1402 }
1403
1404 // finish nlr block, restore context and return value
Damien Georgec4d08682014-10-05 20:13:34 +01001405 nlr_pop();
1406 mp_globals_set(old_globals);
1407 mp_locals_set(old_locals);
1408 return ret;
1409 } else {
1410 // exception; restore context and re-raise same exception
1411 mp_globals_set(old_globals);
1412 mp_locals_set(old_locals);
Damien George999cedb2015-11-27 17:01:44 +00001413 nlr_jump(nlr.ret_val);
Damien Georgec4d08682014-10-05 20:13:34 +01001414 }
1415}
1416
Damien Georgedd5353a2015-12-18 12:35:44 +00001417#endif // MICROPY_ENABLE_COMPILER
1418
Damien Georgeb0261342014-09-23 18:10:17 +01001419void *m_malloc_fail(size_t num_bytes) {
Damien George978d2e52016-01-08 13:49:58 +00001420 DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes);
Damien George40914452014-10-09 16:44:43 +01001421 if (0) {
1422 // dummy
1423 #if MICROPY_ENABLE_GC
1424 } else if (gc_is_locked()) {
Damien George7d0d7212016-10-17 12:17:37 +11001425 mp_raise_msg(&mp_type_MemoryError, "memory allocation failed, heap is locked");
Damien George40914452014-10-09 16:44:43 +01001426 #endif
Dave Hylands3556e452014-10-07 00:50:20 -07001427 } else {
Damien George40914452014-10-09 16:44:43 +01001428 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
Damien George978d2e52016-01-08 13:49:58 +00001429 "memory allocation failed, allocating %u bytes", (uint)num_bytes));
Dave Hylands3556e452014-10-07 00:50:20 -07001430 }
Damien George6902eed2014-04-04 10:52:59 +00001431}
1432
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001433NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg) {
1434 nlr_raise(mp_obj_new_exception_msg(exc_type, msg));
1435}
1436
1437NORETURN void mp_raise_ValueError(const char *msg) {
1438 mp_raise_msg(&mp_type_ValueError, msg);
1439}
1440
1441NORETURN void mp_raise_TypeError(const char *msg) {
1442 mp_raise_msg(&mp_type_TypeError, msg);
1443}
1444
Damien George3a0a7712016-10-07 13:31:59 +11001445NORETURN void mp_raise_OSError(int errno_) {
1446 nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno_)));
1447}
1448
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001449NORETURN void mp_not_implemented(const char *msg) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001450 mp_raise_msg(&mp_type_NotImplementedError, msg);
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001451}