blob: 080d061cd10a8aa001acc904ffd8941b778f226b [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"
35#include "py/objtuple.h"
36#include "py/objlist.h"
37#include "py/objmodule.h"
38#include "py/objgenerator.h"
39#include "py/smallint.h"
40#include "py/runtime0.h"
41#include "py/runtime.h"
42#include "py/builtin.h"
43#include "py/stackctrl.h"
44#include "py/gc.h"
Damien660365e2013-12-17 18:27:24 +000045
Damien7f5dacf2013-10-10 11:24:39 +010046#if 0 // print debugging info
Damiena1ddfcc2013-10-10 23:25:50 +010047#define DEBUG_PRINT (1)
Paul Sokolovsky44739e22014-02-16 18:11:42 +020048#define DEBUG_printf DEBUG_printf
Damien George41eb6082014-02-26 22:40:35 +000049#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
Damien7f5dacf2013-10-10 11:24:39 +010050#else // don't print debugging info
Damien George41eb6082014-02-26 22:40:35 +000051#define DEBUG_printf(...) (void)0
52#define DEBUG_OP_printf(...) (void)0
Damien7f5dacf2013-10-10 11:24:39 +010053#endif
Damien429d7192013-10-04 19:53:11 +010054
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030055const mp_obj_module_t mp_module___main__ = {
56 .base = { &mp_type_module },
57 .name = MP_QSTR___main__,
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 Sokolovskycaa73342014-07-01 02:13:42 +030063 mp_stack_ctrl_init();
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030064
Damien George124df6f2014-10-25 18:19:55 +010065 // no pending exceptions to start with
Damien Georgeb4b10fd2015-01-01 23:30:53 +000066 MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
Damien George124df6f2014-10-25 18:19:55 +010067
Damien George8dbbbbc2014-08-04 10:05:16 +010068#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
69 mp_init_emergency_exception_buf();
70#endif
71
Damien George97f9a282014-05-12 23:07:34 +010072 // call port specific initialization if any
stijn72521a12014-05-03 11:28:29 +020073#ifdef MICROPY_PORT_INIT_FUNC
74 MICROPY_PORT_INIT_FUNC;
75#endif
76
Paul Sokolovskyd3439d02014-06-02 19:37:55 +030077 // optimization disabled by default
Damien Georgeb4b10fd2015-01-01 23:30:53 +000078 MP_STATE_VM(mp_optimise_value) = 0;
Damien George97f9a282014-05-12 23:07:34 +010079
Damien Georgecaac5422014-03-25 14:18:18 +000080 // init global module stuff
81 mp_module_init();
Damien George0d028742014-01-22 23:59:20 +000082
Damien George7efc5b32014-04-05 22:36:42 +010083 // initialise the __main__ module
Damien Georgeb4b10fd2015-01-01 23:30:53 +000084 mp_obj_dict_init(&MP_STATE_VM(dict_main), 1);
85 mp_obj_dict_store(&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 +030086
87 // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
Damien Georgeb4b10fd2015-01-01 23:30:53 +000088 MP_STATE_CTX(dict_locals) = MP_STATE_CTX(dict_globals) = &MP_STATE_VM(dict_main);
Damien George78d702c2014-12-09 16:19:48 +000089
90 #if MICROPY_CAN_OVERRIDE_BUILTINS
91 // start with no extensions to builtins
Damien Georgeb4b10fd2015-01-01 23:30:53 +000092 MP_STATE_VM(mp_module_builtins_override_dict) = NULL;
Damien George78d702c2014-12-09 16:19:48 +000093 #endif
Damien429d7192013-10-04 19:53:11 +010094}
95
Damien Georged17926d2014-03-30 13:35:08 +010096void mp_deinit(void) {
Damien George7efc5b32014-04-05 22:36:42 +010097 //mp_obj_dict_free(&dict_main);
Damien George2326d522014-03-27 23:26:35 +000098 mp_module_deinit();
stijn5ed284a2014-05-08 10:56:33 +020099
100 // call port specific deinitialization if any
101#ifdef MICROPY_PORT_INIT_FUNC
102 MICROPY_PORT_DEINIT_FUNC;
103#endif
Damien429d7192013-10-04 19:53:11 +0100104}
105
Damien George50912e72015-01-20 11:55:10 +0000106mp_obj_t mp_load_const_int(qstr qst) {
107 DEBUG_OP_printf("load '%s'\n", qstr_str(qst));
Damien George39dc1452014-10-03 19:52:22 +0100108 mp_uint_t len;
Damien George50912e72015-01-20 11:55:10 +0000109 const byte* data = qstr_data(qst, &len);
Damien George503d6112014-05-28 14:07:21 +0100110 return mp_parse_num_integer((const char*)data, len, 0);
111}
112
Damien George50912e72015-01-20 11:55:10 +0000113mp_obj_t mp_load_const_dec(qstr qst) {
114 DEBUG_OP_printf("load '%s'\n", qstr_str(qst));
Damien George39dc1452014-10-03 19:52:22 +0100115 mp_uint_t len;
Damien George50912e72015-01-20 11:55:10 +0000116 const byte* data = qstr_data(qst, &len);
Damien George6e48f7f2014-03-21 11:45:46 +0000117 return mp_parse_num_decimal((const char*)data, len, true, false);
Damien7410e442013-11-02 19:47:57 +0000118}
119
Damien George50912e72015-01-20 11:55:10 +0000120mp_obj_t mp_load_const_str(qstr qst) {
121 DEBUG_OP_printf("load '%s'\n", qstr_str(qst));
122 return MP_OBJ_NEW_QSTR(qst);
Damien429d7192013-10-04 19:53:11 +0100123}
124
Damien George50912e72015-01-20 11:55:10 +0000125mp_obj_t mp_load_const_bytes(qstr qst) {
126 DEBUG_OP_printf("load b'%s'\n", qstr_str(qst));
Damien George39dc1452014-10-03 19:52:22 +0100127 mp_uint_t len;
Damien George50912e72015-01-20 11:55:10 +0000128 const byte *data = qstr_data(qst, &len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200129 return mp_obj_new_bytes(data, len);
130}
131
Damien George50912e72015-01-20 11:55:10 +0000132mp_obj_t mp_load_name(qstr qst) {
Damien429d7192013-10-04 19:53:11 +0100133 // logic: search locals, globals, builtins
Damien George50912e72015-01-20 11:55:10 +0000134 DEBUG_OP_printf("load name %s\n", qstr_str(qst));
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300135 // If we're at the outer scope (locals == globals), dispatch to load_global right away
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000136 if (MP_STATE_CTX(dict_locals) != MP_STATE_CTX(dict_globals)) {
Damien George50912e72015-01-20 11:55:10 +0000137 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 +0300138 if (elem != NULL) {
139 return elem->value;
140 }
Damiena3977762013-10-09 23:10:10 +0100141 }
Damien George50912e72015-01-20 11:55:10 +0000142 return mp_load_global(qst);
Damiena3977762013-10-09 23:10:10 +0100143}
144
Damien George50912e72015-01-20 11:55:10 +0000145mp_obj_t mp_load_global(qstr qst) {
Damiena3977762013-10-09 23:10:10 +0100146 // logic: search globals, builtins
Damien George50912e72015-01-20 11:55:10 +0000147 DEBUG_OP_printf("load global %s\n", qstr_str(qst));
148 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 +0100149 if (elem == NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000150 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000151 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000152 // lookup in additional dynamic table of builtins first
Damien George50912e72015-01-20 11:55:10 +0000153 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 +0000154 if (elem != NULL) {
155 return elem->value;
156 }
157 }
158 #endif
Damien George50912e72015-01-20 11:55:10 +0000159 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 +0100160 if (elem == NULL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000161 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
162 nlr_raise(mp_obj_new_exception_msg(&mp_type_NameError,
163 "name not defined"));
164 } else {
165 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
Damien George50912e72015-01-20 11:55:10 +0000166 "name '%s' is not defined", qstr_str(qst)));
Damien George1e9a92f2014-11-06 17:36:16 +0000167 }
Damien429d7192013-10-04 19:53:11 +0100168 }
169 }
170 return elem->value;
171}
172
Damien Georged17926d2014-03-30 13:35:08 +0100173mp_obj_t mp_load_build_class(void) {
Damien429d7192013-10-04 19:53:11 +0100174 DEBUG_OP_printf("load_build_class\n");
Damien George78d702c2014-12-09 16:19:48 +0000175 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000176 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000177 // lookup in additional dynamic table of builtins first
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000178 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 +0000179 if (elem != NULL) {
180 return elem->value;
181 }
182 }
183 #endif
Damien George7efc5b32014-04-05 22:36:42 +0100184 return (mp_obj_t)&mp_builtin___build_class___obj;
Damien429d7192013-10-04 19:53:11 +0100185}
186
Damien George50912e72015-01-20 11:55:10 +0000187void mp_store_name(qstr qst, mp_obj_t obj) {
188 DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qst), obj);
189 mp_obj_dict_store(MP_STATE_CTX(dict_locals), MP_OBJ_NEW_QSTR(qst), obj);
Damiena3977762013-10-09 23:10:10 +0100190}
191
Damien George50912e72015-01-20 11:55:10 +0000192void mp_delete_name(qstr qst) {
193 DEBUG_OP_printf("delete name %s\n", qstr_str(qst));
194 // TODO convert KeyError to NameError if qst not found
195 mp_obj_dict_delete(MP_STATE_CTX(dict_locals), MP_OBJ_NEW_QSTR(qst));
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200196}
197
Damien George50912e72015-01-20 11:55:10 +0000198void mp_store_global(qstr qst, mp_obj_t obj) {
199 DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qst), obj);
200 mp_obj_dict_store(MP_STATE_CTX(dict_globals), MP_OBJ_NEW_QSTR(qst), obj);
Damien429d7192013-10-04 19:53:11 +0100201}
202
Damien George50912e72015-01-20 11:55:10 +0000203void mp_delete_global(qstr qst) {
204 DEBUG_OP_printf("delete global %s\n", qstr_str(qst));
205 // TODO convert KeyError to NameError if qst not found
206 mp_obj_dict_delete(MP_STATE_CTX(dict_globals), MP_OBJ_NEW_QSTR(qst));
Damien George1d24ea52014-04-08 21:11:49 +0100207}
208
Damien George4abff752014-08-30 14:59:21 +0100209mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100210 DEBUG_OP_printf("unary " UINT_FMT " %p\n", op, arg);
Damien George9aa2a522014-02-01 23:04:09 +0000211
Damiend99b0522013-12-21 18:17:45 +0000212 if (MP_OBJ_IS_SMALL_INT(arg)) {
Damien George40f3c022014-07-03 13:25:24 +0100213 mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
Damien7410e442013-11-02 19:47:57 +0000214 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100215 case MP_UNARY_OP_BOOL:
Damien George9d68e9c2014-03-12 15:38:15 +0000216 return MP_BOOL(val != 0);
Damien Georged17926d2014-03-30 13:35:08 +0100217 case MP_UNARY_OP_POSITIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000218 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100219 case MP_UNARY_OP_NEGATIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000220 // check for overflow
221 if (val == MP_SMALL_INT_MIN) {
222 return mp_obj_new_int(-val);
223 } else {
224 return MP_OBJ_NEW_SMALL_INT(-val);
225 }
Damien Georged17926d2014-03-30 13:35:08 +0100226 case MP_UNARY_OP_INVERT:
Damien George9d68e9c2014-03-12 15:38:15 +0000227 return MP_OBJ_NEW_SMALL_INT(~val);
228 default:
229 assert(0);
230 return arg;
Damien7410e442013-11-02 19:47:57 +0000231 }
Damien George1e708fe2014-01-23 18:27:51 +0000232 } else {
233 mp_obj_type_t *type = mp_obj_get_type(arg);
234 if (type->unary_op != NULL) {
235 mp_obj_t result = type->unary_op(op, arg);
Damien George6ac5dce2014-05-21 19:42:43 +0100236 if (result != MP_OBJ_NULL) {
Damiend99b0522013-12-21 18:17:45 +0000237 return result;
238 }
Damien7410e442013-11-02 19:47:57 +0000239 }
Damien George1e9a92f2014-11-06 17:36:16 +0000240 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
241 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
242 "unsupported type for operator"));
243 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000244 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
Damien Georgea5efcd42015-01-27 18:02:25 +0000245 "unsupported type for %s: '%s'",
246 qstr_str(mp_unary_op_method_name[op]), mp_obj_get_type_str(arg)));
Damien George1e9a92f2014-11-06 17:36:16 +0000247 }
Damien7410e442013-11-02 19:47:57 +0000248 }
Damien429d7192013-10-04 19:53:11 +0100249}
250
Damien George4abff752014-08-30 14:59:21 +0100251mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100252 DEBUG_OP_printf("binary " UINT_FMT " %p %p\n", op, lhs, rhs);
Damien George14f945c2014-01-03 14:09:31 +0000253
254 // TODO correctly distinguish inplace operators for mutable objects
255 // lookup logic that CPython uses for +=:
256 // check for implemented +=
257 // then check for implemented +
258 // then check for implemented seq.inplace_concat
259 // then check for implemented seq.concat
260 // then fail
261 // note that list does not implement + or +=, so that inplace_concat is reached first for +=
262
Damien George9aa2a522014-02-01 23:04:09 +0000263 // deal with is
Damien Georged17926d2014-03-30 13:35:08 +0100264 if (op == MP_BINARY_OP_IS) {
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200265 return MP_BOOL(lhs == rhs);
266 }
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200267
Damien Georgebcbeea02014-01-11 10:47:22 +0000268 // deal with == and != for all types
Damien Georged17926d2014-03-30 13:35:08 +0100269 if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000270 if (mp_obj_equal(lhs, rhs)) {
Damien Georged17926d2014-03-30 13:35:08 +0100271 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000272 return mp_const_true;
273 } else {
274 return mp_const_false;
275 }
276 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100277 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000278 return mp_const_false;
279 } else {
280 return mp_const_true;
281 }
282 }
283 }
284
285 // deal with exception_match for all types
Damien Georged17926d2014-03-30 13:35:08 +0100286 if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
Damien Georgec5966122014-02-15 16:10:44 +0000287 // rhs must be issubclass(rhs, BaseException)
288 if (mp_obj_is_exception_type(rhs)) {
Damien George4bcd04b2014-09-24 14:05:40 +0100289 if (mp_obj_exception_match(lhs, rhs)) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000290 return mp_const_true;
291 } else {
292 return mp_const_false;
293 }
Damien George4bcd04b2014-09-24 14:05:40 +0100294 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
295 mp_obj_tuple_t *tuple = rhs;
296 for (mp_uint_t i = 0; i < tuple->len; i++) {
297 rhs = tuple->items[i];
298 if (!mp_obj_is_exception_type(rhs)) {
299 goto unsupported_op;
300 }
301 if (mp_obj_exception_match(lhs, rhs)) {
302 return mp_const_true;
303 }
304 }
305 return mp_const_false;
Damien Georgebcbeea02014-01-11 10:47:22 +0000306 }
Damien George4bcd04b2014-09-24 14:05:40 +0100307 goto unsupported_op;
Damien Georgebcbeea02014-01-11 10:47:22 +0000308 }
309
Damien George1a9951d2014-01-06 22:13:00 +0000310 if (MP_OBJ_IS_SMALL_INT(lhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100311 mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
Damien George1a9951d2014-01-06 22:13:00 +0000312 if (MP_OBJ_IS_SMALL_INT(rhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100313 mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
Damien George9d68e9c2014-03-12 15:38:15 +0000314 // This is a binary operation: lhs_val op rhs_val
315 // We need to be careful to handle overflow; see CERT INT32-C
316 // Operations that can overflow:
Damien George40f3c022014-07-03 13:25:24 +0100317 // + result always fits in mp_int_t, then handled by SMALL_INT check
318 // - result always fits in mp_int_t, then handled by SMALL_INT check
Damien George9d68e9c2014-03-12 15:38:15 +0000319 // * checked explicitly
Damien George40f3c022014-07-03 13:25:24 +0100320 // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
321 // % 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 +0000322 // << checked explicitly
Damien George1a9951d2014-01-06 22:13:00 +0000323 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100324 case MP_BINARY_OP_OR:
325 case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
326 case MP_BINARY_OP_XOR:
327 case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
328 case MP_BINARY_OP_AND:
329 case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
330 case MP_BINARY_OP_LSHIFT:
331 case MP_BINARY_OP_INPLACE_LSHIFT: {
Damien George9d68e9c2014-03-12 15:38:15 +0000332 if (rhs_val < 0) {
333 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100334 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George963a5a32015-01-16 17:47:07 +0000335 } 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 +0000336 // left-shift will overflow, so use higher precision integer
337 lhs = mp_obj_new_int_from_ll(lhs_val);
338 goto generic_binary_op;
339 } else {
340 // use standard precision
341 lhs_val <<= rhs_val;
342 }
343 break;
344 }
Damien Georged17926d2014-03-30 13:35:08 +0100345 case MP_BINARY_OP_RSHIFT:
346 case MP_BINARY_OP_INPLACE_RSHIFT:
Damien George9d68e9c2014-03-12 15:38:15 +0000347 if (rhs_val < 0) {
348 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100349 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000350 } else {
351 // standard precision is enough for right-shift
Damien George963a5a32015-01-16 17:47:07 +0000352 if (rhs_val >= (mp_int_t)BITS_PER_WORD) {
Paul Sokolovsky039887a2014-11-02 02:39:41 +0200353 // Shifting to big amounts is underfined behavior
354 // in C and is CPU-dependent; propagate sign bit.
355 rhs_val = BITS_PER_WORD - 1;
356 }
Damien George9d68e9c2014-03-12 15:38:15 +0000357 lhs_val >>= rhs_val;
358 }
359 break;
Damien Georged17926d2014-03-30 13:35:08 +0100360 case MP_BINARY_OP_ADD:
361 case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
362 case MP_BINARY_OP_SUBTRACT:
363 case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
364 case MP_BINARY_OP_MULTIPLY:
365 case MP_BINARY_OP_INPLACE_MULTIPLY: {
Damien George9d68e9c2014-03-12 15:38:15 +0000366
Damien George40f3c022014-07-03 13:25:24 +0100367 // If long long type exists and is larger than mp_int_t, then
Damien George9d68e9c2014-03-12 15:38:15 +0000368 // we can use the following code to perform overflow-checked multiplication.
Damien Georgeecf5b772014-04-04 11:13:51 +0000369 // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
Damien George9d68e9c2014-03-12 15:38:15 +0000370 #if 0
371 // compute result using long long precision
372 long long res = (long long)lhs_val * (long long)rhs_val;
373 if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
374 // result overflowed SMALL_INT, so return higher precision integer
375 return mp_obj_new_int_from_ll(res);
376 } else {
377 // use standard precision
Damien George40f3c022014-07-03 13:25:24 +0100378 lhs_val = (mp_int_t)res;
Damien George9d68e9c2014-03-12 15:38:15 +0000379 }
380 #endif
381
Damien Georgeecf5b772014-04-04 11:13:51 +0000382 if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
383 // use higher precision
384 lhs = mp_obj_new_int_from_ll(lhs_val);
385 goto generic_binary_op;
386 } else {
387 // use standard precision
388 return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
389 }
Damien George9d68e9c2014-03-12 15:38:15 +0000390 break;
391 }
Damien Georged17926d2014-03-30 13:35:08 +0100392 case MP_BINARY_OP_FLOOR_DIVIDE:
393 case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300394 if (rhs_val == 0) {
395 goto zero_division;
396 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000397 lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
Rachel Dowdall56402792014-03-22 20:19:24 +0000398 break;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300399
Damien Georgefb510b32014-06-01 13:32:54 +0100400 #if MICROPY_PY_BUILTINS_FLOAT
Damien Georged17926d2014-03-30 13:35:08 +0100401 case MP_BINARY_OP_TRUE_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300402 case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
403 if (rhs_val == 0) {
Damien George70f33cd2014-04-02 17:06:05 +0100404 goto zero_division;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300405 }
406 return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000407 #endif
Damiena3dcd9e2013-12-17 21:35:38 +0000408
Damien Georged17926d2014-03-30 13:35:08 +0100409 case MP_BINARY_OP_MODULO:
Damien Georgeecf5b772014-04-04 11:13:51 +0000410 case MP_BINARY_OP_INPLACE_MODULO: {
411 lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
Rachel Dowdallcde86312014-03-22 17:29:27 +0000412 break;
413 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000414
Damien Georged17926d2014-03-30 13:35:08 +0100415 case MP_BINARY_OP_POWER:
416 case MP_BINARY_OP_INPLACE_POWER:
Damien George9d68e9c2014-03-12 15:38:15 +0000417 if (rhs_val < 0) {
Damien Georgefb510b32014-06-01 13:32:54 +0100418 #if MICROPY_PY_BUILTINS_FLOAT
Damien George9d68e9c2014-03-12 15:38:15 +0000419 lhs = mp_obj_new_float(lhs_val);
420 goto generic_binary_op;
421 #else
Damien Georgeea13f402014-04-05 18:32:08 +0100422 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative power with no float support"));
Damien George9d68e9c2014-03-12 15:38:15 +0000423 #endif
424 } else {
Damien George40f3c022014-07-03 13:25:24 +0100425 mp_int_t ans = 1;
Damien George9d68e9c2014-03-12 15:38:15 +0000426 while (rhs_val > 0) {
427 if (rhs_val & 1) {
Damien Georgeecf5b772014-04-04 11:13:51 +0000428 if (mp_small_int_mul_overflow(ans, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100429 goto power_overflow;
430 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000431 ans *= lhs_val;
Damien George9d68e9c2014-03-12 15:38:15 +0000432 }
Damien George5bf565e2014-04-04 00:16:32 +0100433 if (rhs_val == 1) {
434 break;
435 }
Damien George9d68e9c2014-03-12 15:38:15 +0000436 rhs_val /= 2;
Damien Georgeecf5b772014-04-04 11:13:51 +0000437 if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100438 goto power_overflow;
439 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000440 lhs_val *= lhs_val;
Damien George1a9951d2014-01-06 22:13:00 +0000441 }
Damien George9d68e9c2014-03-12 15:38:15 +0000442 lhs_val = ans;
Damiena3dcd9e2013-12-17 21:35:38 +0000443 }
Damien George1a9951d2014-01-06 22:13:00 +0000444 break;
Damien George5bf565e2014-04-04 00:16:32 +0100445
446 power_overflow:
447 // use higher precision
448 lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
449 goto generic_binary_op;
450
Damien Georged17926d2014-03-30 13:35:08 +0100451 case MP_BINARY_OP_LESS: return MP_BOOL(lhs_val < rhs_val); break;
452 case MP_BINARY_OP_MORE: return MP_BOOL(lhs_val > rhs_val); break;
453 case MP_BINARY_OP_LESS_EQUAL: return MP_BOOL(lhs_val <= rhs_val); break;
454 case MP_BINARY_OP_MORE_EQUAL: return MP_BOOL(lhs_val >= rhs_val); break;
Damiena3dcd9e2013-12-17 21:35:38 +0000455
Damien George8bcb9862014-04-17 16:26:50 +0100456 default:
457 goto unsupported_op;
Damien George1a9951d2014-01-06 22:13:00 +0000458 }
Paul Sokolovsky757ac812014-01-12 17:06:25 +0200459 // TODO: We just should make mp_obj_new_int() inline and use that
Damien Georged1e355e2014-05-28 14:51:12 +0100460 if (MP_SMALL_INT_FITS(lhs_val)) {
Damien George1a9951d2014-01-06 22:13:00 +0000461 return MP_OBJ_NEW_SMALL_INT(lhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000462 } else {
463 return mp_obj_new_int(lhs_val);
Damien George1a9951d2014-01-06 22:13:00 +0000464 }
Damien Georgefb510b32014-06-01 13:32:54 +0100465#if MICROPY_PY_BUILTINS_FLOAT
Damien George0c36da02014-03-08 15:24:39 +0000466 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_float)) {
Damien Georgeae491052014-04-10 20:08:11 +0100467 mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
468 if (res == MP_OBJ_NULL) {
469 goto unsupported_op;
470 } else {
471 return res;
472 }
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300473#if MICROPY_PY_BUILTINS_COMPLEX
Damien George0c36da02014-03-08 15:24:39 +0000474 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
Damien Georgeae491052014-04-10 20:08:11 +0100475 mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
476 if (res == MP_OBJ_NULL) {
477 goto unsupported_op;
478 } else {
479 return res;
480 }
Damien George3f759b72014-01-31 00:42:12 +0000481#endif
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300482#endif
Damien429d7192013-10-04 19:53:11 +0100483 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000484 }
John R. Lentonb8698fc2014-01-11 00:58:59 +0000485
Damien George9aa2a522014-02-01 23:04:09 +0000486 /* deal with `in`
John R. Lentonc1bef212014-01-11 12:39:33 +0000487 *
488 * NOTE `a in b` is `b.__contains__(a)`, hence why the generic dispatch
Damien George48697f12014-02-01 23:32:29 +0000489 * needs to go below with swapped arguments
John R. Lentonc1bef212014-01-11 12:39:33 +0000490 */
Damien Georged17926d2014-03-30 13:35:08 +0100491 if (op == MP_BINARY_OP_IN) {
Damien George5fa93b62014-01-22 14:35:10 +0000492 mp_obj_type_t *type = mp_obj_get_type(rhs);
493 if (type->binary_op != NULL) {
494 mp_obj_t res = type->binary_op(op, rhs, lhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100495 if (res != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000496 return res;
497 }
498 }
499 if (type->getiter != NULL) {
500 /* second attempt, walk the iterator */
Damien Georged17926d2014-03-30 13:35:08 +0100501 mp_obj_t iter = mp_getiter(rhs);
Damien George3aa09f52014-10-23 12:06:53 +0100502 mp_obj_t next;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100503 while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
Damien George5fa93b62014-01-22 14:35:10 +0000504 if (mp_obj_equal(next, lhs)) {
Damien George9aa2a522014-02-01 23:04:09 +0000505 return mp_const_true;
John R. Lentonb8698fc2014-01-11 00:58:59 +0000506 }
Damien7410e442013-11-02 19:47:57 +0000507 }
Damien George9aa2a522014-02-01 23:04:09 +0000508 return mp_const_false;
Damien7410e442013-11-02 19:47:57 +0000509 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000510
Damien George1e9a92f2014-11-06 17:36:16 +0000511 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
512 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
513 "object not iterable"));
514 } else {
515 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
516 "'%s' object is not iterable", mp_obj_get_type_str(rhs)));
517 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000518 }
519
Damien George5fa93b62014-01-22 14:35:10 +0000520 // generic binary_op supplied by type
Damien George9d68e9c2014-03-12 15:38:15 +0000521 mp_obj_type_t *type;
522generic_binary_op:
523 type = mp_obj_get_type(lhs);
Damien George5fa93b62014-01-22 14:35:10 +0000524 if (type->binary_op != NULL) {
525 mp_obj_t result = type->binary_op(op, lhs, rhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100526 if (result != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000527 return result;
John R. Lentonc1bef212014-01-11 12:39:33 +0000528 }
Damien429d7192013-10-04 19:53:11 +0100529 }
Damiend99b0522013-12-21 18:17:45 +0000530
Damien George5fa93b62014-01-22 14:35:10 +0000531 // TODO implement dispatch for reverse binary ops
532
Damien Georgeae491052014-04-10 20:08:11 +0100533unsupported_op:
Damien George1e9a92f2014-11-06 17:36:16 +0000534 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
535 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
536 "unsupported type for operator"));
537 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000538 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
Damien Georgea5efcd42015-01-27 18:02:25 +0000539 "unsupported types for %s: '%s', '%s'",
540 qstr_str(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 +0000541 }
Damien George70f33cd2014-04-02 17:06:05 +0100542
543zero_division:
Damien Georgeea13f402014-04-05 18:32:08 +0100544 nlr_raise(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero"));
Damien429d7192013-10-04 19:53:11 +0100545}
546
Damien Georged17926d2014-03-30 13:35:08 +0100547mp_obj_t mp_call_function_0(mp_obj_t fun) {
548 return mp_call_function_n_kw(fun, 0, 0, NULL);
Damieneb19efb2013-10-10 22:06:54 +0100549}
550
Damien Georged17926d2014-03-30 13:35:08 +0100551mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
552 return mp_call_function_n_kw(fun, 1, 0, &arg);
Damieneb19efb2013-10-10 22:06:54 +0100553}
554
Damien Georged17926d2014-03-30 13:35:08 +0100555mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
Damiend99b0522013-12-21 18:17:45 +0000556 mp_obj_t args[2];
Damien George20006db2014-01-18 14:10:48 +0000557 args[0] = arg1;
558 args[1] = arg2;
Damien Georged17926d2014-03-30 13:35:08 +0100559 return mp_call_function_n_kw(fun, 2, 0, args);
Damieneb19efb2013-10-10 22:06:54 +0100560}
561
Damien George20006db2014-01-18 14:10:48 +0000562// args contains, eg: arg0 arg1 key0 value0 key1 value1
Damien George4abff752014-08-30 14:59:21 +0100563mp_obj_t mp_call_function_n_kw(mp_obj_t fun_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Damiend99b0522013-12-21 18:17:45 +0000564 // TODO improve this: fun object can specify its type and we parse here the arguments,
565 // passing to the function arrays of fixed and keyword arguments
Damieneb19efb2013-10-10 22:06:54 +0100566
Damien Georgeeaaebf32014-09-23 10:59:05 +0100567 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 +0000568
Damien George8b56beb2014-01-31 23:49:49 +0000569 // get the type
570 mp_obj_type_t *type = mp_obj_get_type(fun_in);
571
572 // do the call
573 if (type->call != NULL) {
Damien George3f522622014-06-03 13:40:16 +0100574 return type->call(fun_in, n_args, n_kw, args);
John R. Lenton9c83ec02014-01-07 23:06:46 +0000575 }
Paul Sokolovsky755565d2014-04-25 21:15:16 +0300576
Damien George1e9a92f2014-11-06 17:36:16 +0000577 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
578 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
579 "object not callable"));
580 } else {
581 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
582 "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
583 }
Damien86c7fc72013-11-26 15:16:41 +0000584}
585
Damien George20006db2014-01-18 14:10:48 +0000586// 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)
587// if n_args==0 and n_kw==0 then there are only fun and self/NULL
Damien George4abff752014-08-30 14:59:21 +0100588mp_obj_t mp_call_method_n_kw(mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100589 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 George20006db2014-01-18 14:10:48 +0000590 int adjust = (args[1] == NULL) ? 0 : 1;
Damien Georged17926d2014-03-30 13:35:08 +0100591 return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
Damien86c7fc72013-11-26 15:16:41 +0000592}
593
Damien George4abff752014-08-30 14:59:21 +0100594mp_obj_t mp_call_method_n_kw_var(bool have_self, mp_uint_t n_args_n_kw, const mp_obj_t *args) {
Damien George230fec72014-03-30 21:21:24 +0100595 mp_obj_t fun = *args++;
596 mp_obj_t self = MP_OBJ_NULL;
597 if (have_self) {
598 self = *args++; // may be MP_OBJ_NULL
599 }
600 uint n_args = n_args_n_kw & 0xff;
601 uint n_kw = (n_args_n_kw >> 8) & 0xff;
Damien George523b5752014-03-31 11:59:23 +0100602 mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // map be MP_OBJ_NULL
603 mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // map be MP_OBJ_NULL
Damien George230fec72014-03-30 21:21:24 +0100604
605 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);
606
607 // We need to create the following array of objects:
608 // args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
609 // TODO: optimize one day to avoid constructing new arg array? Will be hard.
610
611 // The new args array
612 mp_obj_t *args2;
613 uint args2_alloc;
614 uint args2_len = 0;
615
616 // Try to get a hint for the size of the kw_dict
617 uint kw_dict_len = 0;
618 if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
619 kw_dict_len = mp_obj_dict_len(kw_dict);
620 }
621
622 // Extract the pos_seq sequence to the new args array.
623 // Note that it can be arbitrary iterator.
624 if (pos_seq == MP_OBJ_NULL) {
625 // no sequence
626
627 // allocate memory for the new array of args
628 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
629 args2 = m_new(mp_obj_t, args2_alloc);
630
631 // copy the self
632 if (self != MP_OBJ_NULL) {
633 args2[args2_len++] = self;
634 }
635
636 // copy the fixed pos args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300637 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100638 args2_len += n_args;
639
640 } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
641 // optimise the case of a tuple and list
642
643 // get the items
Damien George9c4cbe22014-08-30 14:04:14 +0100644 mp_uint_t len;
Damien George230fec72014-03-30 21:21:24 +0100645 mp_obj_t *items;
646 mp_obj_get_array(pos_seq, &len, &items);
647
648 // allocate memory for the new array of args
649 args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
650 args2 = m_new(mp_obj_t, args2_alloc);
651
652 // copy the self
653 if (self != MP_OBJ_NULL) {
654 args2[args2_len++] = self;
655 }
656
657 // copy the fixed and variable position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300658 mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100659 args2_len += n_args + len;
660
661 } else {
662 // generic iterator
663
664 // allocate memory for the new array of args
665 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
666 args2 = m_new(mp_obj_t, args2_alloc);
667
668 // copy the self
669 if (self != MP_OBJ_NULL) {
670 args2[args2_len++] = self;
671 }
672
673 // copy the fixed position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300674 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100675
676 // extract the variable position args from the iterator
677 mp_obj_t iterable = mp_getiter(pos_seq);
678 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100679 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100680 if (args2_len >= args2_alloc) {
681 args2 = m_renew(mp_obj_t, args2, args2_alloc, args2_alloc * 2);
682 args2_alloc *= 2;
683 }
684 args2[args2_len++] = item;
685 }
686 }
687
688 // The size of the args2 array now is the number of positional args.
689 uint pos_args_len = args2_len;
690
691 // Copy the fixed kw args.
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300692 mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100693 args2_len += 2 * n_kw;
694
695 // Extract (key,value) pairs from kw_dict dictionary and append to args2.
696 // Note that it can be arbitrary iterator.
697 if (kw_dict == MP_OBJ_NULL) {
698 // pass
699 } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
700 // dictionary
701 mp_map_t *map = mp_obj_dict_get_map(kw_dict);
702 assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above
Damien Georgeb063b9b2014-12-21 16:24:09 +0000703 for (mp_uint_t i = 0; i < map->alloc; i++) {
704 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Damien George230fec72014-03-30 21:21:24 +0100705 args2[args2_len++] = map->table[i].key;
706 args2[args2_len++] = map->table[i].value;
707 }
708 }
709 } else {
710 // generic mapping
711 // TODO is calling 'items' on the mapping the correct thing to do here?
712 mp_obj_t dest[2];
713 mp_load_method(kw_dict, MP_QSTR_items, dest);
714 mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest));
715 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100716 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100717 if (args2_len + 1 >= args2_alloc) {
718 uint new_alloc = args2_alloc * 2;
719 if (new_alloc < 4) {
720 new_alloc = 4;
721 }
722 args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
723 args2_alloc = new_alloc;
724 }
725 mp_obj_t *items;
726 mp_obj_get_array_fixed_n(item, 2, &items);
727 args2[args2_len++] = items[0];
728 args2[args2_len++] = items[1];
729 }
730 }
731
732 mp_obj_t res = mp_call_function_n_kw(fun, pos_args_len, (args2_len - pos_args_len) / 2, args2);
733 m_del(mp_obj_t, args2, args2_alloc);
734
735 return res;
736}
737
Damien George932bf1c2014-01-18 23:42:49 +0000738// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100739void mp_unpack_sequence(mp_obj_t seq_in, mp_uint_t num, mp_obj_t *items) {
Damien George9c4cbe22014-08-30 14:04:14 +0100740 mp_uint_t seq_len;
Damien George3e1a5c12014-03-29 13:43:38 +0000741 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 +0000742 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000743 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000744 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
745 } else {
746 mp_obj_list_get(seq_in, &seq_len, &seq_items);
Damien86c7fc72013-11-26 15:16:41 +0000747 }
Damiend99b0522013-12-21 18:17:45 +0000748 if (seq_len < num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200749 goto too_short;
Damiend99b0522013-12-21 18:17:45 +0000750 } else if (seq_len > num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200751 goto too_long;
Damiend99b0522013-12-21 18:17:45 +0000752 }
Damien George4abff752014-08-30 14:59:21 +0100753 for (mp_uint_t i = 0; i < num; i++) {
Damien George932bf1c2014-01-18 23:42:49 +0000754 items[i] = seq_items[num - 1 - i];
755 }
Damien86c7fc72013-11-26 15:16:41 +0000756 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100757 mp_obj_t iterable = mp_getiter(seq_in);
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200758
759 for (seq_len = 0; seq_len < num; seq_len++) {
Damien Georged17926d2014-03-30 13:35:08 +0100760 mp_obj_t el = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100761 if (el == MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200762 goto too_short;
763 }
764 items[num - 1 - seq_len] = el;
765 }
Damien Georgeea8d06c2014-04-17 23:19:36 +0100766 if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200767 goto too_long;
768 }
Damien86c7fc72013-11-26 15:16:41 +0000769 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200770 return;
771
772too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000773 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
774 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
775 "wrong number of values to unpack"));
776 } else {
777 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
778 "need more than %d values to unpack", seq_len));
779 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200780too_long:
Damien George1e9a92f2014-11-06 17:36:16 +0000781 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
782 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
783 "wrong number of values to unpack"));
784 } else {
785 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
786 "too many values to unpack (expected %d)", num));
787 }
Damien86c7fc72013-11-26 15:16:41 +0000788}
789
Damien George495d7812014-04-08 17:51:47 +0100790// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100791void mp_unpack_ex(mp_obj_t seq_in, mp_uint_t num_in, mp_obj_t *items) {
792 mp_uint_t num_left = num_in & 0xff;
793 mp_uint_t num_right = (num_in >> 8) & 0xff;
Damien Georgeeaaebf32014-09-23 10:59:05 +0100794 DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
Damien George9c4cbe22014-08-30 14:04:14 +0100795 mp_uint_t seq_len;
Damien George495d7812014-04-08 17:51:47 +0100796 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
797 mp_obj_t *seq_items;
798 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
799 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
800 } else {
801 if (num_left == 0 && num_right == 0) {
802 // *a, = b # sets a to b if b is a list
803 items[0] = seq_in;
804 return;
805 }
806 mp_obj_list_get(seq_in, &seq_len, &seq_items);
807 }
808 if (seq_len < num_left + num_right) {
809 goto too_short;
810 }
Damien George4abff752014-08-30 14:59:21 +0100811 for (mp_uint_t i = 0; i < num_right; i++) {
Damien George495d7812014-04-08 17:51:47 +0100812 items[i] = seq_items[seq_len - 1 - i];
813 }
814 items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
Damien George4abff752014-08-30 14:59:21 +0100815 for (mp_uint_t i = 0; i < num_left; i++) {
Damien George495d7812014-04-08 17:51:47 +0100816 items[num_right + 1 + i] = seq_items[num_left - 1 - i];
817 }
818 } else {
819 // Generic iterable; this gets a bit messy: we unpack known left length to the
820 // items destination array, then the rest to a dynamically created list. Once the
821 // iterable is exhausted, we take from this list for the right part of the items.
822 // TODO Improve to waste less memory in the dynamically created list.
823 mp_obj_t iterable = mp_getiter(seq_in);
824 mp_obj_t item;
825 for (seq_len = 0; seq_len < num_left; seq_len++) {
826 item = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100827 if (item == MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100828 goto too_short;
829 }
830 items[num_left + num_right + 1 - 1 - seq_len] = item;
831 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100832 mp_obj_list_t *rest = mp_obj_new_list(0, NULL);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100833 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100834 mp_obj_list_append(rest, item);
835 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100836 if (rest->len < num_right) {
Damien George495d7812014-04-08 17:51:47 +0100837 goto too_short;
838 }
839 items[num_right] = rest;
Damien George4abff752014-08-30 14:59:21 +0100840 for (mp_uint_t i = 0; i < num_right; i++) {
Damien Georgeca6d75f2014-08-30 15:17:47 +0100841 items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
Damien George495d7812014-04-08 17:51:47 +0100842 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100843 mp_obj_list_set_len(rest, rest->len - num_right);
Damien George495d7812014-04-08 17:51:47 +0100844 }
845 return;
846
847too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000848 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
849 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
850 "wrong number of values to unpack"));
851 } else {
852 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
853 "need more than %d values to unpack", seq_len));
854 }
Damien George495d7812014-04-08 17:51:47 +0100855}
856
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300857mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
Damien George062478e2014-01-09 20:57:50 +0000858 DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300859 // use load_method
Damien George062478e2014-01-09 20:57:50 +0000860 mp_obj_t dest[2];
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300861 mp_load_method(base, attr, dest);
862 if (dest[1] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000863 // load_method returned just a normal attribute
Damien George20006db2014-01-18 14:10:48 +0000864 return dest[0];
Damien George062478e2014-01-09 20:57:50 +0000865 } else {
866 // load_method returned a method, so build a bound method object
867 return mp_obj_new_bound_meth(dest[0], dest[1]);
Damiend99b0522013-12-21 18:17:45 +0000868 }
Damiend99b0522013-12-21 18:17:45 +0000869}
870
Damien George7c9c6672014-01-25 00:17:36 +0000871// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
872// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
873// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
Damien Georgee44d26a2014-03-31 22:57:56 +0100874void mp_load_method_maybe(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George062478e2014-01-09 20:57:50 +0000875 // clear output to indicate no attribute/method found yet
876 dest[0] = MP_OBJ_NULL;
877 dest[1] = MP_OBJ_NULL;
878
879 // get the type
880 mp_obj_type_t *type = mp_obj_get_type(base);
881
Damien Georgee44d26a2014-03-31 22:57:56 +0100882 // look for built-in names
883 if (0) {
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300884#if MICROPY_CPYTHON_COMPAT
Damien Georgee44d26a2014-03-31 22:57:56 +0100885 } else if (attr == MP_QSTR___class__) {
886 // a.__class__ is equivalent to type(a)
887 dest[0] = type;
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300888#endif
Damien Georgee44d26a2014-03-31 22:57:56 +0100889
890 } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
891 dest[0] = (mp_obj_t)&mp_builtin_next_obj;
892 dest[1] = base;
893
894 } else if (type->load_attr != NULL) {
895 // this type can do its own load, so call it
896 type->load_attr(base, attr, dest);
897
898 } else if (type->locals_dict != NULL) {
899 // generic method lookup
900 // this is a lookup in the object (ie not class or type)
901 assert(MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)); // Micro Python restriction, for now
902 mp_map_t *locals_map = mp_obj_dict_get_map(type->locals_dict);
903 mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
904 if (elem != NULL) {
905 // check if the methods are functions, static or class methods
Chris Angelicodaf973a2014-06-06 03:51:03 +1000906 // see http://docs.python.org/3/howto/descriptor.html
Damien Georgee44d26a2014-03-31 22:57:56 +0100907 if (MP_OBJ_IS_TYPE(elem->value, &mp_type_staticmethod)) {
908 // return just the function
909 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
910 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_classmethod)) {
911 // return a bound method, with self being the type of this object
912 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
913 dest[1] = mp_obj_get_type(base);
Paul Sokolovsky9511f602014-05-11 03:12:36 +0300914 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_type)) {
915 // Don't try to bind types
916 dest[0] = elem->value;
Damien Georgee44d26a2014-03-31 22:57:56 +0100917 } else if (mp_obj_is_callable(elem->value)) {
918 // return a bound method, with self being this object
919 dest[0] = elem->value;
920 dest[1] = base;
921 } else {
922 // class member is a value, so just return that value
923 dest[0] = elem->value;
Damiend57eba52013-11-02 23:58:14 +0000924 }
925 }
Damiena3977762013-10-09 23:10:10 +0100926 }
Damien George7c9c6672014-01-25 00:17:36 +0000927}
Damiena3977762013-10-09 23:10:10 +0100928
Damien Georged17926d2014-03-30 13:35:08 +0100929void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George7c9c6672014-01-25 00:17:36 +0000930 DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
931
Damien Georged17926d2014-03-30 13:35:08 +0100932 mp_load_method_maybe(base, attr, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000933
934 if (dest[0] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000935 // no attribute/method called attr
Damien George1e9a92f2014-11-06 17:36:16 +0000936 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
937 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
938 "no such attribute"));
Damien George062478e2014-01-09 20:57:50 +0000939 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000940 // following CPython, we give a more detailed error message for type objects
941 if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
942 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
943 "type object '%s' has no attribute '%s'",
944 qstr_str(((mp_obj_type_t*)base)->name), qstr_str(attr)));
945 } else {
946 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
947 "'%s' object has no attribute '%s'",
948 mp_obj_get_type_str(base), qstr_str(attr)));
949 }
Damien George062478e2014-01-09 20:57:50 +0000950 }
951 }
Damiena3977762013-10-09 23:10:10 +0100952}
953
Damien Georged17926d2014-03-30 13:35:08 +0100954void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien5ac1b2e2013-10-18 19:58:12 +0100955 DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
Damien George062478e2014-01-09 20:57:50 +0000956 mp_obj_type_t *type = mp_obj_get_type(base);
957 if (type->store_attr != NULL) {
958 if (type->store_attr(base, attr, value)) {
959 return;
960 }
Damiena3977762013-10-09 23:10:10 +0100961 }
Damien George1e9a92f2014-11-06 17:36:16 +0000962 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
963 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
964 "no such attribute"));
965 } else {
966 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
967 "'%s' object has no attribute '%s'",
968 mp_obj_get_type_str(base), qstr_str(attr)));
969 }
Damiena3977762013-10-09 23:10:10 +0100970}
971
Damien Georged17926d2014-03-30 13:35:08 +0100972mp_obj_t mp_getiter(mp_obj_t o_in) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300973 assert(o_in);
Damien George5fa93b62014-01-22 14:35:10 +0000974 mp_obj_type_t *type = mp_obj_get_type(o_in);
975 if (type->getiter != NULL) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300976 mp_obj_t iter = type->getiter(o_in);
977 if (iter == MP_OBJ_NULL) {
978 goto not_iterable;
979 }
980 return iter;
Damience89a212013-10-15 22:25:17 +0100981 } else {
Damien George9e6e9352014-03-26 18:37:06 +0000982 // check for __iter__ method
Damien George7c9c6672014-01-25 00:17:36 +0000983 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +0100984 mp_load_method_maybe(o_in, MP_QSTR___iter__, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000985 if (dest[0] != MP_OBJ_NULL) {
Damien George9e6e9352014-03-26 18:37:06 +0000986 // __iter__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +0100987 return mp_call_method_n_kw(0, 0, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000988 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100989 mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
Damien George9e6e9352014-03-26 18:37:06 +0000990 if (dest[0] != MP_OBJ_NULL) {
991 // __getitem__ exists, create an iterator
992 return mp_obj_new_getitem_iter(dest);
993 } else {
994 // object not iterable
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300995not_iterable:
Damien George1e9a92f2014-11-06 17:36:16 +0000996 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
997 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
998 "object not iterable"));
999 } else {
1000 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1001 "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
1002 }
Damien George9e6e9352014-03-26 18:37:06 +00001003 }
Damien George7c9c6672014-01-25 00:17:36 +00001004 }
Damience89a212013-10-15 22:25:17 +01001005 }
1006}
1007
Damien Georgeea8d06c2014-04-17 23:19:36 +01001008// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
Damien George66eaf842014-03-26 19:27:58 +00001009// may also raise StopIteration()
Damien Georged17926d2014-03-30 13:35:08 +01001010mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001011 mp_obj_type_t *type = mp_obj_get_type(o_in);
1012 if (type->iternext != NULL) {
1013 return type->iternext(o_in);
Damience89a212013-10-15 22:25:17 +01001014 } else {
Damien George9e6e9352014-03-26 18:37:06 +00001015 // check for __next__ method
1016 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001017 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001018 if (dest[0] != MP_OBJ_NULL) {
1019 // __next__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +01001020 return mp_call_method_n_kw(0, 0, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001021 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001022 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1023 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1024 "object not an iterator"));
1025 } else {
1026 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1027 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1028 }
Damien George9e6e9352014-03-26 18:37:06 +00001029 }
Damien Georgec5966122014-02-15 16:10:44 +00001030 }
1031}
1032
Damien Georgeea8d06c2014-04-17 23:19:36 +01001033// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
Damien George66eaf842014-03-26 19:27:58 +00001034// may raise other exceptions
Damien Georged17926d2014-03-30 13:35:08 +01001035mp_obj_t mp_iternext(mp_obj_t o_in) {
Damien George66eaf842014-03-26 19:27:58 +00001036 mp_obj_type_t *type = mp_obj_get_type(o_in);
1037 if (type->iternext != NULL) {
1038 return type->iternext(o_in);
1039 } else {
1040 // check for __next__ method
1041 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001042 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George66eaf842014-03-26 19:27:58 +00001043 if (dest[0] != MP_OBJ_NULL) {
1044 // __next__ exists, call it and return its result
1045 nlr_buf_t nlr;
1046 if (nlr_push(&nlr) == 0) {
Damien Georged17926d2014-03-30 13:35:08 +01001047 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
Damien George66eaf842014-03-26 19:27:58 +00001048 nlr_pop();
1049 return ret;
1050 } else {
1051 if (mp_obj_is_subclass_fast(mp_obj_get_type(nlr.ret_val), &mp_type_StopIteration)) {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001052 return MP_OBJ_STOP_ITERATION;
Damien George66eaf842014-03-26 19:27:58 +00001053 } else {
Damien Georgeea13f402014-04-05 18:32:08 +01001054 nlr_raise(nlr.ret_val);
Damien George66eaf842014-03-26 19:27:58 +00001055 }
1056 }
1057 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001058 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1059 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1060 "object not an iterator"));
1061 } else {
1062 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1063 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1064 }
Damien George66eaf842014-03-26 19:27:58 +00001065 }
1066 }
1067}
1068
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001069// TODO: Unclear what to do with StopIterarion exception here.
1070mp_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 +03001071 assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001072 mp_obj_type_t *type = mp_obj_get_type(self_in);
1073
1074 if (type == &mp_type_gen_instance) {
1075 return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
1076 }
1077
1078 if (type->iternext != NULL && send_value == mp_const_none) {
1079 mp_obj_t ret = type->iternext(self_in);
1080 if (ret != MP_OBJ_NULL) {
1081 *ret_val = ret;
1082 return MP_VM_RETURN_YIELD;
1083 } else {
1084 // Emulate raise StopIteration()
1085 // Special case, handled in vm.c
1086 *ret_val = MP_OBJ_NULL;
1087 return MP_VM_RETURN_NORMAL;
1088 }
1089 }
1090
1091 mp_obj_t dest[3]; // Reserve slot for send() arg
1092
1093 if (send_value == mp_const_none) {
1094 mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1095 if (dest[0] != MP_OBJ_NULL) {
1096 *ret_val = mp_call_method_n_kw(0, 0, dest);
1097 return MP_VM_RETURN_YIELD;
1098 }
1099 }
1100
1101 if (send_value != MP_OBJ_NULL) {
1102 mp_load_method(self_in, MP_QSTR_send, dest);
1103 dest[2] = send_value;
1104 *ret_val = mp_call_method_n_kw(1, 0, dest);
1105 return MP_VM_RETURN_YIELD;
1106 }
1107
1108 if (throw_value != MP_OBJ_NULL) {
1109 if (mp_obj_is_subclass_fast(mp_obj_get_type(throw_value), &mp_type_GeneratorExit)) {
1110 mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1111 if (dest[0] != MP_OBJ_NULL) {
1112 *ret_val = mp_call_method_n_kw(0, 0, dest);
1113 // We assume one can't "yield" from close()
1114 return MP_VM_RETURN_NORMAL;
1115 }
1116 }
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001117 mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1118 if (dest[0] != MP_OBJ_NULL) {
1119 *ret_val = mp_call_method_n_kw(1, 0, &throw_value);
1120 // If .throw() method returned, we assume it's value to yield
Damien Georgeea13f402014-04-05 18:32:08 +01001121 // - any exception would be thrown with nlr_raise().
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001122 return MP_VM_RETURN_YIELD;
1123 }
1124 // If there's nowhere to throw exception into, then we assume that object
1125 // is just incapable to handle it, so any exception thrown into it
1126 // will be propagated up. This behavior is approved by test_pep380.py
1127 // test_delegation_of_close_to_non_generator(),
1128 // test_delegating_throw_to_non_generator()
1129 *ret_val = throw_value;
1130 return MP_VM_RETURN_EXCEPTION;
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001131 }
1132
1133 assert(0);
1134 return MP_VM_RETURN_NORMAL; // Should be unreachable
1135}
1136
Damien Georged17926d2014-03-30 13:35:08 +01001137mp_obj_t mp_make_raise_obj(mp_obj_t o) {
Damien Georgec5966122014-02-15 16:10:44 +00001138 DEBUG_printf("raise %p\n", o);
1139 if (mp_obj_is_exception_type(o)) {
1140 // o is an exception type (it is derived from BaseException (or is BaseException))
1141 // create and return a new exception instance by calling o
Damien George22a08652014-02-15 21:05:25 +00001142 // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1143 // could have const instances in ROM which we return here instead
Damien Georged17926d2014-03-30 13:35:08 +01001144 return mp_call_function_n_kw(o, 0, 0, NULL);
Damien Georgec5966122014-02-15 16:10:44 +00001145 } else if (mp_obj_is_exception_instance(o)) {
1146 // o is an instance of an exception, so use it as the exception
1147 return o;
1148 } else {
1149 // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1150 return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
Damience89a212013-10-15 22:25:17 +01001151 }
1152}
1153
Damien Georged17926d2014-03-30 13:35:08 +01001154mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
Damien George64131f32014-02-06 20:31:44 +00001155 DEBUG_printf("import name %s\n", qstr_str(name));
1156
Damiendb4c3612013-12-10 17:27:24 +00001157 // build args array
Damiend99b0522013-12-21 18:17:45 +00001158 mp_obj_t args[5];
Damien George5fa93b62014-01-22 14:35:10 +00001159 args[0] = MP_OBJ_NEW_QSTR(name);
Damiend99b0522013-12-21 18:17:45 +00001160 args[1] = mp_const_none; // TODO should be globals
1161 args[2] = mp_const_none; // TODO should be locals
Damiendb4c3612013-12-10 17:27:24 +00001162 args[3] = fromlist;
1163 args[4] = level; // must be 0; we don't yet support other values
1164
1165 // TODO lookup __import__ and call that instead of going straight to builtin implementation
Damiend99b0522013-12-21 18:17:45 +00001166 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001167}
1168
Damien Georged17926d2014-03-30 13:35:08 +01001169mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
Damien George64131f32014-02-06 20:31:44 +00001170 DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1171
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001172 mp_obj_t dest[2];
1173
1174 mp_load_method_maybe(module, name, dest);
1175
1176 if (dest[1] != MP_OBJ_NULL) {
1177 // Hopefully we can't import bound method from an object
1178import_error:
Paul Sokolovsky42453dc2014-04-12 03:00:40 +03001179 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %s", qstr_str(name)));
Damiendb4c3612013-12-10 17:27:24 +00001180 }
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001181
1182 if (dest[0] != MP_OBJ_NULL) {
1183 return dest[0];
1184 }
1185
1186 // See if it's a package, then can try FS import
Paul Sokolovskye5a37592014-10-25 21:04:13 +03001187 if (!mp_obj_is_package(module)) {
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001188 goto import_error;
1189 }
1190
1191 mp_load_method_maybe(module, MP_QSTR___name__, dest);
Damien Georged182b982014-08-30 14:19:41 +01001192 mp_uint_t pkg_name_len;
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001193 const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1194
stijn01d6be42014-05-05 12:18:27 +02001195 const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1196 char *dot_name = alloca(dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001197 memcpy(dot_name, pkg_name, pkg_name_len);
1198 dot_name[pkg_name_len] = '.';
1199 memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
stijn01d6be42014-05-05 12:18:27 +02001200 qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001201
1202 mp_obj_t args[5];
1203 args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
1204 args[1] = mp_const_none; // TODO should be globals
1205 args[2] = mp_const_none; // TODO should be locals
1206 args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
Paul Sokolovsky69f18672014-04-12 02:47:46 +03001207 args[4] = MP_OBJ_NEW_SMALL_INT(0);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001208
1209 // TODO lookup __import__ and call that instead of going straight to builtin implementation
1210 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001211}
1212
Damien Georged17926d2014-03-30 13:35:08 +01001213void mp_import_all(mp_obj_t module) {
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001214 DEBUG_printf("import all %p\n", module);
1215
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001216 // TODO: Support __all__
Damien George8b0535e2014-04-05 21:53:54 +01001217 mp_map_t *map = mp_obj_dict_get_map(mp_obj_module_get_globals(module));
Damien Georgeb063b9b2014-12-21 16:24:09 +00001218 for (mp_uint_t i = 0; i < map->alloc; i++) {
Damien George8b0535e2014-04-05 21:53:54 +01001219 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001220 qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
1221 if (*qstr_str(name) != '_') {
1222 mp_store_name(name, map->table[i].value);
1223 }
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001224 }
1225 }
1226}
1227
Damien Georgec4d08682014-10-05 20:13:34 +01001228// this is implemented in this file so it can optimise access to locals/globals
1229mp_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 +00001230 // save context
1231 mp_obj_dict_t *volatile old_globals = mp_globals_get();
1232 mp_obj_dict_t *volatile old_locals = mp_locals_get();
Damien Georgec4d08682014-10-05 20:13:34 +01001233
Damien George0bfc7632015-02-07 18:33:58 +00001234 // set new context
Damien Georgec4d08682014-10-05 20:13:34 +01001235 mp_globals_set(globals);
1236 mp_locals_set(locals);
1237
Damien Georgec4d08682014-10-05 20:13:34 +01001238 nlr_buf_t nlr;
1239 if (nlr_push(&nlr) == 0) {
Damien George0bfc7632015-02-07 18:33:58 +00001240 qstr source_name = lex->source_name;
1241 mp_parse_node_t pn = mp_parse(lex, parse_input_kind);
1242 mp_obj_t module_fun = mp_compile(pn, source_name, MP_EMIT_OPT_NONE, false);
1243
1244 mp_obj_t ret;
1245 if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
1246 // for compile only, return value is the module function
1247 ret = module_fun;
1248 } else {
1249 // execute module function and get return value
1250 ret = mp_call_function_0(module_fun);
1251 }
1252
1253 // finish nlr block, restore context and return value
Damien Georgec4d08682014-10-05 20:13:34 +01001254 nlr_pop();
1255 mp_globals_set(old_globals);
1256 mp_locals_set(old_locals);
1257 return ret;
1258 } else {
1259 // exception; restore context and re-raise same exception
1260 mp_globals_set(old_globals);
1261 mp_locals_set(old_locals);
1262 nlr_raise(nlr.ret_val);
1263 }
1264}
1265
Damien Georgeb0261342014-09-23 18:10:17 +01001266void *m_malloc_fail(size_t num_bytes) {
1267 DEBUG_printf("memory allocation failed, allocating " UINT_FMT " bytes\n", num_bytes);
Damien George40914452014-10-09 16:44:43 +01001268 if (0) {
1269 // dummy
1270 #if MICROPY_ENABLE_GC
1271 } else if (gc_is_locked()) {
1272 nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001273 "memory allocation failed, heap is locked"));
Damien George40914452014-10-09 16:44:43 +01001274 #endif
Dave Hylands3556e452014-10-07 00:50:20 -07001275 } else {
Damien George40914452014-10-09 16:44:43 +01001276 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001277 "memory allocation failed, allocating " UINT_FMT " bytes", num_bytes));
1278 }
Damien George6902eed2014-04-04 10:52:59 +00001279}
1280
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001281NORETURN void mp_not_implemented(const char *msg) {
1282 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, msg));
1283}