blob: 54d120796abd77f823e3984c81a9429d2402450a [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"
33#include "py/parsehelper.h"
34#include "py/parsenum.h"
35#include "py/compile.h"
36#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 },
58 .name = MP_QSTR___main__,
Damien Georgeb4b10fd2015-01-01 23:30:53 +000059 .globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main),
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030060};
61
Damien Georged17926d2014-03-30 13:35:08 +010062void mp_init(void) {
Damien George8dbbbbc2014-08-04 10:05:16 +010063 qstr_init();
Paul Sokolovskycaa73342014-07-01 02:13:42 +030064 mp_stack_ctrl_init();
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030065
Damien George124df6f2014-10-25 18:19:55 +010066 // no pending exceptions to start with
Damien Georgeb4b10fd2015-01-01 23:30:53 +000067 MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
Damien George124df6f2014-10-25 18:19:55 +010068
Damien George8dbbbbc2014-08-04 10:05:16 +010069#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
70 mp_init_emergency_exception_buf();
71#endif
72
Damien George97f9a282014-05-12 23:07:34 +010073 // call port specific initialization if any
stijn72521a12014-05-03 11:28:29 +020074#ifdef MICROPY_PORT_INIT_FUNC
75 MICROPY_PORT_INIT_FUNC;
76#endif
77
Paul Sokolovskyd3439d02014-06-02 19:37:55 +030078 // optimization disabled by default
Damien Georgeb4b10fd2015-01-01 23:30:53 +000079 MP_STATE_VM(mp_optimise_value) = 0;
Damien George97f9a282014-05-12 23:07:34 +010080
Damien Georgecaac5422014-03-25 14:18:18 +000081 // init global module stuff
82 mp_module_init();
Damien George0d028742014-01-22 23:59:20 +000083
Damien George7efc5b32014-04-05 22:36:42 +010084 // initialise the __main__ module
Damien Georgeb4b10fd2015-01-01 23:30:53 +000085 mp_obj_dict_init(&MP_STATE_VM(dict_main), 1);
86 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 +030087
88 // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
Damien Georgeb4b10fd2015-01-01 23:30:53 +000089 MP_STATE_CTX(dict_locals) = MP_STATE_CTX(dict_globals) = &MP_STATE_VM(dict_main);
Damien George78d702c2014-12-09 16:19:48 +000090
91 #if MICROPY_CAN_OVERRIDE_BUILTINS
92 // start with no extensions to builtins
Damien Georgeb4b10fd2015-01-01 23:30:53 +000093 MP_STATE_VM(mp_module_builtins_override_dict) = NULL;
Damien George78d702c2014-12-09 16:19:48 +000094 #endif
Damien429d7192013-10-04 19:53:11 +010095}
96
Damien Georged17926d2014-03-30 13:35:08 +010097void mp_deinit(void) {
Damien George7efc5b32014-04-05 22:36:42 +010098 //mp_obj_dict_free(&dict_main);
Damien George2326d522014-03-27 23:26:35 +000099 mp_module_deinit();
stijn5ed284a2014-05-08 10:56:33 +0200100
101 // call port specific deinitialization if any
102#ifdef MICROPY_PORT_INIT_FUNC
103 MICROPY_PORT_DEINIT_FUNC;
104#endif
Damien429d7192013-10-04 19:53:11 +0100105}
106
Damien George503d6112014-05-28 14:07:21 +0100107mp_obj_t mp_load_const_int(qstr qstr) {
108 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100109 mp_uint_t len;
Damien George503d6112014-05-28 14:07:21 +0100110 const byte* data = qstr_data(qstr, &len);
111 return mp_parse_num_integer((const char*)data, len, 0);
112}
113
Damien Georged17926d2014-03-30 13:35:08 +0100114mp_obj_t mp_load_const_dec(qstr qstr) {
Damien7410e442013-11-02 19:47:57 +0000115 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100116 mp_uint_t len;
Damien George20773972014-02-22 18:12:43 +0000117 const byte* data = qstr_data(qstr, &len);
Damien George6e48f7f2014-03-21 11:45:46 +0000118 return mp_parse_num_decimal((const char*)data, len, true, false);
Damien7410e442013-11-02 19:47:57 +0000119}
120
Damien Georged17926d2014-03-30 13:35:08 +0100121mp_obj_t mp_load_const_str(qstr qstr) {
Damien429d7192013-10-04 19:53:11 +0100122 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George5fa93b62014-01-22 14:35:10 +0000123 return MP_OBJ_NEW_QSTR(qstr);
Damien429d7192013-10-04 19:53:11 +0100124}
125
Damien Georged17926d2014-03-30 13:35:08 +0100126mp_obj_t mp_load_const_bytes(qstr qstr) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200127 DEBUG_OP_printf("load b'%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100128 mp_uint_t len;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200129 const byte *data = qstr_data(qstr, &len);
130 return mp_obj_new_bytes(data, len);
131}
132
Damien Georged17926d2014-03-30 13:35:08 +0100133mp_obj_t mp_load_name(qstr qstr) {
Damien429d7192013-10-04 19:53:11 +0100134 // logic: search locals, globals, builtins
Damien George7efc5b32014-04-05 22:36:42 +0100135 DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300136 // If we're at the outer scope (locals == globals), dispatch to load_global right away
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000137 if (MP_STATE_CTX(dict_locals) != MP_STATE_CTX(dict_globals)) {
138 mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_locals)->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300139 if (elem != NULL) {
140 return elem->value;
141 }
Damiena3977762013-10-09 23:10:10 +0100142 }
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300143 return mp_load_global(qstr);
Damiena3977762013-10-09 23:10:10 +0100144}
145
Damien Georged17926d2014-03-30 13:35:08 +0100146mp_obj_t mp_load_global(qstr qstr) {
Damiena3977762013-10-09 23:10:10 +0100147 // logic: search globals, builtins
148 DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000149 mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_globals)->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100150 if (elem == NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000151 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000152 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000153 // lookup in additional dynamic table of builtins first
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000154 elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
Damien George78d702c2014-12-09 16:19:48 +0000155 if (elem != NULL) {
156 return elem->value;
157 }
158 }
159 #endif
160 elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100161 if (elem == NULL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000162 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
163 nlr_raise(mp_obj_new_exception_msg(&mp_type_NameError,
164 "name not defined"));
165 } else {
166 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
167 "name '%s' is not defined", qstr_str(qstr)));
168 }
Damien429d7192013-10-04 19:53:11 +0100169 }
170 }
171 return elem->value;
172}
173
Damien Georged17926d2014-03-30 13:35:08 +0100174mp_obj_t mp_load_build_class(void) {
Damien429d7192013-10-04 19:53:11 +0100175 DEBUG_OP_printf("load_build_class\n");
Damien George78d702c2014-12-09 16:19:48 +0000176 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000177 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000178 // lookup in additional dynamic table of builtins first
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000179 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 +0000180 if (elem != NULL) {
181 return elem->value;
182 }
183 }
184 #endif
Damien George7efc5b32014-04-05 22:36:42 +0100185 return (mp_obj_t)&mp_builtin___build_class___obj;
Damien429d7192013-10-04 19:53:11 +0100186}
187
Damien Georged17926d2014-03-30 13:35:08 +0100188void mp_store_name(qstr qstr, mp_obj_t obj) {
Damiena3977762013-10-09 23:10:10 +0100189 DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000190 mp_obj_dict_store(MP_STATE_CTX(dict_locals), MP_OBJ_NEW_QSTR(qstr), obj);
Damiena3977762013-10-09 23:10:10 +0100191}
192
Damien Georged17926d2014-03-30 13:35:08 +0100193void mp_delete_name(qstr qstr) {
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200194 DEBUG_OP_printf("delete name %s\n", qstr_str(qstr));
Damien George1d24ea52014-04-08 21:11:49 +0100195 // TODO convert KeyError to NameError if qstr not found
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000196 mp_obj_dict_delete(MP_STATE_CTX(dict_locals), MP_OBJ_NEW_QSTR(qstr));
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200197}
198
Damien Georged17926d2014-03-30 13:35:08 +0100199void mp_store_global(qstr qstr, mp_obj_t obj) {
Damiena3977762013-10-09 23:10:10 +0100200 DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qstr), obj);
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000201 mp_obj_dict_store(MP_STATE_CTX(dict_globals), MP_OBJ_NEW_QSTR(qstr), obj);
Damien429d7192013-10-04 19:53:11 +0100202}
203
Damien George1d24ea52014-04-08 21:11:49 +0100204void mp_delete_global(qstr qstr) {
205 DEBUG_OP_printf("delete global %s\n", qstr_str(qstr));
206 // TODO convert KeyError to NameError if qstr not found
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000207 mp_obj_dict_delete(MP_STATE_CTX(dict_globals), MP_OBJ_NEW_QSTR(qstr));
Damien George1d24ea52014-04-08 21:11:49 +0100208}
209
Damien George4abff752014-08-30 14:59:21 +0100210mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100211 DEBUG_OP_printf("unary " UINT_FMT " %p\n", op, arg);
Damien George9aa2a522014-02-01 23:04:09 +0000212
Damiend99b0522013-12-21 18:17:45 +0000213 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:
Damien George9d68e9c2014-03-12 15:38:15 +0000217 return MP_BOOL(val != 0);
Damien Georged17926d2014-03-30 13:35:08 +0100218 case MP_UNARY_OP_POSITIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000219 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100220 case MP_UNARY_OP_NEGATIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000221 // check for overflow
222 if (val == MP_SMALL_INT_MIN) {
223 return mp_obj_new_int(-val);
224 } else {
225 return MP_OBJ_NEW_SMALL_INT(-val);
226 }
Damien Georged17926d2014-03-30 13:35:08 +0100227 case MP_UNARY_OP_INVERT:
Damien George9d68e9c2014-03-12 15:38:15 +0000228 return MP_OBJ_NEW_SMALL_INT(~val);
229 default:
230 assert(0);
231 return arg;
Damien7410e442013-11-02 19:47:57 +0000232 }
Damien George1e708fe2014-01-23 18:27:51 +0000233 } else {
234 mp_obj_type_t *type = mp_obj_get_type(arg);
235 if (type->unary_op != NULL) {
236 mp_obj_t result = type->unary_op(op, arg);
Damien George6ac5dce2014-05-21 19:42:43 +0100237 if (result != MP_OBJ_NULL) {
Damiend99b0522013-12-21 18:17:45 +0000238 return result;
239 }
Damien7410e442013-11-02 19:47:57 +0000240 }
Damien George1e9a92f2014-11-06 17:36:16 +0000241 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
242 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
243 "unsupported type for operator"));
244 } else {
245 // TODO specify in error message what the operator is
246 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
247 "bad operand type for unary operator: '%s'",
248 mp_obj_get_type_str(arg)));
249 }
Damien7410e442013-11-02 19:47:57 +0000250 }
Damien429d7192013-10-04 19:53:11 +0100251}
252
Damien George4abff752014-08-30 14:59:21 +0100253mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100254 DEBUG_OP_printf("binary " UINT_FMT " %p %p\n", op, lhs, rhs);
Damien George14f945c2014-01-03 14:09:31 +0000255
256 // TODO correctly distinguish inplace operators for mutable objects
257 // lookup logic that CPython uses for +=:
258 // check for implemented +=
259 // then check for implemented +
260 // then check for implemented seq.inplace_concat
261 // then check for implemented seq.concat
262 // then fail
263 // note that list does not implement + or +=, so that inplace_concat is reached first for +=
264
Damien George9aa2a522014-02-01 23:04:09 +0000265 // deal with is
Damien Georged17926d2014-03-30 13:35:08 +0100266 if (op == MP_BINARY_OP_IS) {
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200267 return MP_BOOL(lhs == rhs);
268 }
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200269
Damien Georgebcbeea02014-01-11 10:47:22 +0000270 // deal with == and != for all types
Damien Georged17926d2014-03-30 13:35:08 +0100271 if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000272 if (mp_obj_equal(lhs, rhs)) {
Damien Georged17926d2014-03-30 13:35:08 +0100273 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000274 return mp_const_true;
275 } else {
276 return mp_const_false;
277 }
278 } else {
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_false;
281 } else {
282 return mp_const_true;
283 }
284 }
285 }
286
287 // deal with exception_match for all types
Damien Georged17926d2014-03-30 13:35:08 +0100288 if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
Damien Georgec5966122014-02-15 16:10:44 +0000289 // rhs must be issubclass(rhs, BaseException)
290 if (mp_obj_is_exception_type(rhs)) {
Damien George4bcd04b2014-09-24 14:05:40 +0100291 if (mp_obj_exception_match(lhs, rhs)) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000292 return mp_const_true;
293 } else {
294 return mp_const_false;
295 }
Damien George4bcd04b2014-09-24 14:05:40 +0100296 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
297 mp_obj_tuple_t *tuple = rhs;
298 for (mp_uint_t i = 0; i < tuple->len; i++) {
299 rhs = tuple->items[i];
300 if (!mp_obj_is_exception_type(rhs)) {
301 goto unsupported_op;
302 }
303 if (mp_obj_exception_match(lhs, rhs)) {
304 return mp_const_true;
305 }
306 }
307 return mp_const_false;
Damien Georgebcbeea02014-01-11 10:47:22 +0000308 }
Damien George4bcd04b2014-09-24 14:05:40 +0100309 goto unsupported_op;
Damien Georgebcbeea02014-01-11 10:47:22 +0000310 }
311
Damien George1a9951d2014-01-06 22:13:00 +0000312 if (MP_OBJ_IS_SMALL_INT(lhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100313 mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
Damien George1a9951d2014-01-06 22:13:00 +0000314 if (MP_OBJ_IS_SMALL_INT(rhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100315 mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
Damien George9d68e9c2014-03-12 15:38:15 +0000316 // This is a binary operation: lhs_val op rhs_val
317 // We need to be careful to handle overflow; see CERT INT32-C
318 // Operations that can overflow:
Damien George40f3c022014-07-03 13:25:24 +0100319 // + result always fits in mp_int_t, then handled by SMALL_INT check
320 // - result always fits in mp_int_t, then handled by SMALL_INT check
Damien George9d68e9c2014-03-12 15:38:15 +0000321 // * checked explicitly
Damien George40f3c022014-07-03 13:25:24 +0100322 // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
323 // % 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 +0000324 // << checked explicitly
Damien George1a9951d2014-01-06 22:13:00 +0000325 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100326 case MP_BINARY_OP_OR:
327 case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
328 case MP_BINARY_OP_XOR:
329 case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
330 case MP_BINARY_OP_AND:
331 case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
332 case MP_BINARY_OP_LSHIFT:
333 case MP_BINARY_OP_INPLACE_LSHIFT: {
Damien George9d68e9c2014-03-12 15:38:15 +0000334 if (rhs_val < 0) {
335 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100336 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000337 } else if (rhs_val >= BITS_PER_WORD || lhs_val > (MP_SMALL_INT_MAX >> rhs_val) || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
338 // left-shift will overflow, so use higher precision integer
339 lhs = mp_obj_new_int_from_ll(lhs_val);
340 goto generic_binary_op;
341 } else {
342 // use standard precision
343 lhs_val <<= rhs_val;
344 }
345 break;
346 }
Damien Georged17926d2014-03-30 13:35:08 +0100347 case MP_BINARY_OP_RSHIFT:
348 case MP_BINARY_OP_INPLACE_RSHIFT:
Damien George9d68e9c2014-03-12 15:38:15 +0000349 if (rhs_val < 0) {
350 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100351 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000352 } else {
353 // standard precision is enough for right-shift
Paul Sokolovsky039887a2014-11-02 02:39:41 +0200354 if (rhs_val >= BITS_PER_WORD) {
355 // Shifting to big amounts is underfined behavior
356 // in C and is CPU-dependent; propagate sign bit.
357 rhs_val = BITS_PER_WORD - 1;
358 }
Damien George9d68e9c2014-03-12 15:38:15 +0000359 lhs_val >>= rhs_val;
360 }
361 break;
Damien Georged17926d2014-03-30 13:35:08 +0100362 case MP_BINARY_OP_ADD:
363 case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
364 case MP_BINARY_OP_SUBTRACT:
365 case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
366 case MP_BINARY_OP_MULTIPLY:
367 case MP_BINARY_OP_INPLACE_MULTIPLY: {
Damien George9d68e9c2014-03-12 15:38:15 +0000368
Damien George40f3c022014-07-03 13:25:24 +0100369 // If long long type exists and is larger than mp_int_t, then
Damien George9d68e9c2014-03-12 15:38:15 +0000370 // we can use the following code to perform overflow-checked multiplication.
Damien Georgeecf5b772014-04-04 11:13:51 +0000371 // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
Damien George9d68e9c2014-03-12 15:38:15 +0000372 #if 0
373 // compute result using long long precision
374 long long res = (long long)lhs_val * (long long)rhs_val;
375 if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
376 // result overflowed SMALL_INT, so return higher precision integer
377 return mp_obj_new_int_from_ll(res);
378 } else {
379 // use standard precision
Damien George40f3c022014-07-03 13:25:24 +0100380 lhs_val = (mp_int_t)res;
Damien George9d68e9c2014-03-12 15:38:15 +0000381 }
382 #endif
383
Damien Georgeecf5b772014-04-04 11:13:51 +0000384 if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
385 // use higher precision
386 lhs = mp_obj_new_int_from_ll(lhs_val);
387 goto generic_binary_op;
388 } else {
389 // use standard precision
390 return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
391 }
Damien George9d68e9c2014-03-12 15:38:15 +0000392 break;
393 }
Damien Georged17926d2014-03-30 13:35:08 +0100394 case MP_BINARY_OP_FLOOR_DIVIDE:
395 case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300396 if (rhs_val == 0) {
397 goto zero_division;
398 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000399 lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
Rachel Dowdall56402792014-03-22 20:19:24 +0000400 break;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300401
Damien Georgefb510b32014-06-01 13:32:54 +0100402 #if MICROPY_PY_BUILTINS_FLOAT
Damien Georged17926d2014-03-30 13:35:08 +0100403 case MP_BINARY_OP_TRUE_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300404 case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
405 if (rhs_val == 0) {
Damien George70f33cd2014-04-02 17:06:05 +0100406 goto zero_division;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300407 }
408 return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000409 #endif
Damiena3dcd9e2013-12-17 21:35:38 +0000410
Damien Georged17926d2014-03-30 13:35:08 +0100411 case MP_BINARY_OP_MODULO:
Damien Georgeecf5b772014-04-04 11:13:51 +0000412 case MP_BINARY_OP_INPLACE_MODULO: {
413 lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
Rachel Dowdallcde86312014-03-22 17:29:27 +0000414 break;
415 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000416
Damien Georged17926d2014-03-30 13:35:08 +0100417 case MP_BINARY_OP_POWER:
418 case MP_BINARY_OP_INPLACE_POWER:
Damien George9d68e9c2014-03-12 15:38:15 +0000419 if (rhs_val < 0) {
Damien Georgefb510b32014-06-01 13:32:54 +0100420 #if MICROPY_PY_BUILTINS_FLOAT
Damien George9d68e9c2014-03-12 15:38:15 +0000421 lhs = mp_obj_new_float(lhs_val);
422 goto generic_binary_op;
423 #else
Damien Georgeea13f402014-04-05 18:32:08 +0100424 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative power with no float support"));
Damien George9d68e9c2014-03-12 15:38:15 +0000425 #endif
426 } else {
Damien George40f3c022014-07-03 13:25:24 +0100427 mp_int_t ans = 1;
Damien George9d68e9c2014-03-12 15:38:15 +0000428 while (rhs_val > 0) {
429 if (rhs_val & 1) {
Damien Georgeecf5b772014-04-04 11:13:51 +0000430 if (mp_small_int_mul_overflow(ans, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100431 goto power_overflow;
432 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000433 ans *= lhs_val;
Damien George9d68e9c2014-03-12 15:38:15 +0000434 }
Damien George5bf565e2014-04-04 00:16:32 +0100435 if (rhs_val == 1) {
436 break;
437 }
Damien George9d68e9c2014-03-12 15:38:15 +0000438 rhs_val /= 2;
Damien Georgeecf5b772014-04-04 11:13:51 +0000439 if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100440 goto power_overflow;
441 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000442 lhs_val *= lhs_val;
Damien George1a9951d2014-01-06 22:13:00 +0000443 }
Damien George9d68e9c2014-03-12 15:38:15 +0000444 lhs_val = ans;
Damiena3dcd9e2013-12-17 21:35:38 +0000445 }
Damien George1a9951d2014-01-06 22:13:00 +0000446 break;
Damien George5bf565e2014-04-04 00:16:32 +0100447
448 power_overflow:
449 // use higher precision
450 lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
451 goto generic_binary_op;
452
Damien Georged17926d2014-03-30 13:35:08 +0100453 case MP_BINARY_OP_LESS: return MP_BOOL(lhs_val < rhs_val); break;
454 case MP_BINARY_OP_MORE: return MP_BOOL(lhs_val > rhs_val); break;
455 case MP_BINARY_OP_LESS_EQUAL: return MP_BOOL(lhs_val <= rhs_val); break;
456 case MP_BINARY_OP_MORE_EQUAL: return MP_BOOL(lhs_val >= rhs_val); break;
Damiena3dcd9e2013-12-17 21:35:38 +0000457
Damien George8bcb9862014-04-17 16:26:50 +0100458 default:
459 goto unsupported_op;
Damien George1a9951d2014-01-06 22:13:00 +0000460 }
Paul Sokolovsky757ac812014-01-12 17:06:25 +0200461 // TODO: We just should make mp_obj_new_int() inline and use that
Damien Georged1e355e2014-05-28 14:51:12 +0100462 if (MP_SMALL_INT_FITS(lhs_val)) {
Damien George1a9951d2014-01-06 22:13:00 +0000463 return MP_OBJ_NEW_SMALL_INT(lhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000464 } else {
465 return mp_obj_new_int(lhs_val);
Damien George1a9951d2014-01-06 22:13:00 +0000466 }
Damien Georgefb510b32014-06-01 13:32:54 +0100467#if MICROPY_PY_BUILTINS_FLOAT
Damien George0c36da02014-03-08 15:24:39 +0000468 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_float)) {
Damien Georgeae491052014-04-10 20:08:11 +0100469 mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
470 if (res == MP_OBJ_NULL) {
471 goto unsupported_op;
472 } else {
473 return res;
474 }
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300475#if MICROPY_PY_BUILTINS_COMPLEX
Damien George0c36da02014-03-08 15:24:39 +0000476 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
Damien Georgeae491052014-04-10 20:08:11 +0100477 mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
478 if (res == MP_OBJ_NULL) {
479 goto unsupported_op;
480 } else {
481 return res;
482 }
Damien George3f759b72014-01-31 00:42:12 +0000483#endif
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300484#endif
Damien429d7192013-10-04 19:53:11 +0100485 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000486 }
John R. Lentonb8698fc2014-01-11 00:58:59 +0000487
Damien George9aa2a522014-02-01 23:04:09 +0000488 /* deal with `in`
John R. Lentonc1bef212014-01-11 12:39:33 +0000489 *
490 * NOTE `a in b` is `b.__contains__(a)`, hence why the generic dispatch
Damien George48697f12014-02-01 23:32:29 +0000491 * needs to go below with swapped arguments
John R. Lentonc1bef212014-01-11 12:39:33 +0000492 */
Damien Georged17926d2014-03-30 13:35:08 +0100493 if (op == MP_BINARY_OP_IN) {
Damien George5fa93b62014-01-22 14:35:10 +0000494 mp_obj_type_t *type = mp_obj_get_type(rhs);
495 if (type->binary_op != NULL) {
496 mp_obj_t res = type->binary_op(op, rhs, lhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100497 if (res != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000498 return res;
499 }
500 }
501 if (type->getiter != NULL) {
502 /* second attempt, walk the iterator */
Damien Georged17926d2014-03-30 13:35:08 +0100503 mp_obj_t iter = mp_getiter(rhs);
Damien George3aa09f52014-10-23 12:06:53 +0100504 mp_obj_t next;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100505 while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
Damien George5fa93b62014-01-22 14:35:10 +0000506 if (mp_obj_equal(next, lhs)) {
Damien George9aa2a522014-02-01 23:04:09 +0000507 return mp_const_true;
John R. Lentonb8698fc2014-01-11 00:58:59 +0000508 }
Damien7410e442013-11-02 19:47:57 +0000509 }
Damien George9aa2a522014-02-01 23:04:09 +0000510 return mp_const_false;
Damien7410e442013-11-02 19:47:57 +0000511 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000512
Damien George1e9a92f2014-11-06 17:36:16 +0000513 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
514 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
515 "object not iterable"));
516 } else {
517 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
518 "'%s' object is not iterable", mp_obj_get_type_str(rhs)));
519 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000520 }
521
Damien George5fa93b62014-01-22 14:35:10 +0000522 // generic binary_op supplied by type
Damien George9d68e9c2014-03-12 15:38:15 +0000523 mp_obj_type_t *type;
524generic_binary_op:
525 type = mp_obj_get_type(lhs);
Damien George5fa93b62014-01-22 14:35:10 +0000526 if (type->binary_op != NULL) {
527 mp_obj_t result = type->binary_op(op, lhs, rhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100528 if (result != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000529 return result;
John R. Lentonc1bef212014-01-11 12:39:33 +0000530 }
Damien429d7192013-10-04 19:53:11 +0100531 }
Damiend99b0522013-12-21 18:17:45 +0000532
Damien George5fa93b62014-01-22 14:35:10 +0000533 // TODO implement dispatch for reverse binary ops
534
Damien Georgeae491052014-04-10 20:08:11 +0100535unsupported_op:
Damien George1e9a92f2014-11-06 17:36:16 +0000536 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
537 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
538 "unsupported type for operator"));
539 } else {
540 // TODO specify in error message what the operator is
541 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
542 "unsupported operand types for binary operator: '%s', '%s'",
543 mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs)));
544 }
Damien George70f33cd2014-04-02 17:06:05 +0100545
546zero_division:
Damien Georgeea13f402014-04-05 18:32:08 +0100547 nlr_raise(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero"));
Damien429d7192013-10-04 19:53:11 +0100548}
549
Damien Georged17926d2014-03-30 13:35:08 +0100550mp_obj_t mp_call_function_0(mp_obj_t fun) {
551 return mp_call_function_n_kw(fun, 0, 0, NULL);
Damieneb19efb2013-10-10 22:06:54 +0100552}
553
Damien Georged17926d2014-03-30 13:35:08 +0100554mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
555 return mp_call_function_n_kw(fun, 1, 0, &arg);
Damieneb19efb2013-10-10 22:06:54 +0100556}
557
Damien Georged17926d2014-03-30 13:35:08 +0100558mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
Damiend99b0522013-12-21 18:17:45 +0000559 mp_obj_t args[2];
Damien George20006db2014-01-18 14:10:48 +0000560 args[0] = arg1;
561 args[1] = arg2;
Damien Georged17926d2014-03-30 13:35:08 +0100562 return mp_call_function_n_kw(fun, 2, 0, args);
Damieneb19efb2013-10-10 22:06:54 +0100563}
564
Damien George20006db2014-01-18 14:10:48 +0000565// args contains, eg: arg0 arg1 key0 value0 key1 value1
Damien George4abff752014-08-30 14:59:21 +0100566mp_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 +0000567 // TODO improve this: fun object can specify its type and we parse here the arguments,
568 // passing to the function arrays of fixed and keyword arguments
Damieneb19efb2013-10-10 22:06:54 +0100569
Damien Georgeeaaebf32014-09-23 10:59:05 +0100570 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 +0000571
Damien George8b56beb2014-01-31 23:49:49 +0000572 // get the type
573 mp_obj_type_t *type = mp_obj_get_type(fun_in);
574
575 // do the call
576 if (type->call != NULL) {
Damien George3f522622014-06-03 13:40:16 +0100577 return type->call(fun_in, n_args, n_kw, args);
John R. Lenton9c83ec02014-01-07 23:06:46 +0000578 }
Paul Sokolovsky755565d2014-04-25 21:15:16 +0300579
Damien George1e9a92f2014-11-06 17:36:16 +0000580 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
581 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
582 "object not callable"));
583 } else {
584 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
585 "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
586 }
Damien86c7fc72013-11-26 15:16:41 +0000587}
588
Damien George20006db2014-01-18 14:10:48 +0000589// 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)
590// if n_args==0 and n_kw==0 then there are only fun and self/NULL
Damien George4abff752014-08-30 14:59:21 +0100591mp_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 +0100592 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 +0000593 int adjust = (args[1] == NULL) ? 0 : 1;
Damien Georged17926d2014-03-30 13:35:08 +0100594 return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
Damien86c7fc72013-11-26 15:16:41 +0000595}
596
Damien George4abff752014-08-30 14:59:21 +0100597mp_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 +0100598 mp_obj_t fun = *args++;
599 mp_obj_t self = MP_OBJ_NULL;
600 if (have_self) {
601 self = *args++; // may be MP_OBJ_NULL
602 }
603 uint n_args = n_args_n_kw & 0xff;
604 uint n_kw = (n_args_n_kw >> 8) & 0xff;
Damien George523b5752014-03-31 11:59:23 +0100605 mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // map be MP_OBJ_NULL
606 mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // map be MP_OBJ_NULL
Damien George230fec72014-03-30 21:21:24 +0100607
608 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);
609
610 // We need to create the following array of objects:
611 // args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
612 // TODO: optimize one day to avoid constructing new arg array? Will be hard.
613
614 // The new args array
615 mp_obj_t *args2;
616 uint args2_alloc;
617 uint args2_len = 0;
618
619 // Try to get a hint for the size of the kw_dict
620 uint kw_dict_len = 0;
621 if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
622 kw_dict_len = mp_obj_dict_len(kw_dict);
623 }
624
625 // Extract the pos_seq sequence to the new args array.
626 // Note that it can be arbitrary iterator.
627 if (pos_seq == MP_OBJ_NULL) {
628 // no sequence
629
630 // allocate memory for the new array of args
631 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
632 args2 = m_new(mp_obj_t, args2_alloc);
633
634 // copy the self
635 if (self != MP_OBJ_NULL) {
636 args2[args2_len++] = self;
637 }
638
639 // copy the fixed pos args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300640 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100641 args2_len += n_args;
642
643 } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
644 // optimise the case of a tuple and list
645
646 // get the items
Damien George9c4cbe22014-08-30 14:04:14 +0100647 mp_uint_t len;
Damien George230fec72014-03-30 21:21:24 +0100648 mp_obj_t *items;
649 mp_obj_get_array(pos_seq, &len, &items);
650
651 // allocate memory for the new array of args
652 args2_alloc = 1 + n_args + len + 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 and variable position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300661 mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100662 args2_len += n_args + len;
663
664 } else {
665 // generic iterator
666
667 // allocate memory for the new array of args
668 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
669 args2 = m_new(mp_obj_t, args2_alloc);
670
671 // copy the self
672 if (self != MP_OBJ_NULL) {
673 args2[args2_len++] = self;
674 }
675
676 // copy the fixed position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300677 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100678
679 // extract the variable position args from the iterator
680 mp_obj_t iterable = mp_getiter(pos_seq);
681 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100682 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100683 if (args2_len >= args2_alloc) {
684 args2 = m_renew(mp_obj_t, args2, args2_alloc, args2_alloc * 2);
685 args2_alloc *= 2;
686 }
687 args2[args2_len++] = item;
688 }
689 }
690
691 // The size of the args2 array now is the number of positional args.
692 uint pos_args_len = args2_len;
693
694 // Copy the fixed kw args.
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300695 mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100696 args2_len += 2 * n_kw;
697
698 // Extract (key,value) pairs from kw_dict dictionary and append to args2.
699 // Note that it can be arbitrary iterator.
700 if (kw_dict == MP_OBJ_NULL) {
701 // pass
702 } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
703 // dictionary
704 mp_map_t *map = mp_obj_dict_get_map(kw_dict);
705 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 +0000706 for (mp_uint_t i = 0; i < map->alloc; i++) {
707 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Damien George230fec72014-03-30 21:21:24 +0100708 args2[args2_len++] = map->table[i].key;
709 args2[args2_len++] = map->table[i].value;
710 }
711 }
712 } else {
713 // generic mapping
714 // TODO is calling 'items' on the mapping the correct thing to do here?
715 mp_obj_t dest[2];
716 mp_load_method(kw_dict, MP_QSTR_items, dest);
717 mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest));
718 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100719 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100720 if (args2_len + 1 >= args2_alloc) {
721 uint new_alloc = args2_alloc * 2;
722 if (new_alloc < 4) {
723 new_alloc = 4;
724 }
725 args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
726 args2_alloc = new_alloc;
727 }
728 mp_obj_t *items;
729 mp_obj_get_array_fixed_n(item, 2, &items);
730 args2[args2_len++] = items[0];
731 args2[args2_len++] = items[1];
732 }
733 }
734
735 mp_obj_t res = mp_call_function_n_kw(fun, pos_args_len, (args2_len - pos_args_len) / 2, args2);
736 m_del(mp_obj_t, args2, args2_alloc);
737
738 return res;
739}
740
Damien George932bf1c2014-01-18 23:42:49 +0000741// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100742void mp_unpack_sequence(mp_obj_t seq_in, mp_uint_t num, mp_obj_t *items) {
Damien George9c4cbe22014-08-30 14:04:14 +0100743 mp_uint_t seq_len;
Damien George3e1a5c12014-03-29 13:43:38 +0000744 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 +0000745 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000746 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000747 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
748 } else {
749 mp_obj_list_get(seq_in, &seq_len, &seq_items);
Damien86c7fc72013-11-26 15:16:41 +0000750 }
Damiend99b0522013-12-21 18:17:45 +0000751 if (seq_len < num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200752 goto too_short;
Damiend99b0522013-12-21 18:17:45 +0000753 } else if (seq_len > num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200754 goto too_long;
Damiend99b0522013-12-21 18:17:45 +0000755 }
Damien George4abff752014-08-30 14:59:21 +0100756 for (mp_uint_t i = 0; i < num; i++) {
Damien George932bf1c2014-01-18 23:42:49 +0000757 items[i] = seq_items[num - 1 - i];
758 }
Damien86c7fc72013-11-26 15:16:41 +0000759 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100760 mp_obj_t iterable = mp_getiter(seq_in);
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200761
762 for (seq_len = 0; seq_len < num; seq_len++) {
Damien Georged17926d2014-03-30 13:35:08 +0100763 mp_obj_t el = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100764 if (el == MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200765 goto too_short;
766 }
767 items[num - 1 - seq_len] = el;
768 }
Damien Georgeea8d06c2014-04-17 23:19:36 +0100769 if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200770 goto too_long;
771 }
Damien86c7fc72013-11-26 15:16:41 +0000772 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200773 return;
774
775too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000776 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
777 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
778 "wrong number of values to unpack"));
779 } else {
780 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
781 "need more than %d values to unpack", seq_len));
782 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200783too_long:
Damien George1e9a92f2014-11-06 17:36:16 +0000784 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
785 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
786 "wrong number of values to unpack"));
787 } else {
788 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
789 "too many values to unpack (expected %d)", num));
790 }
Damien86c7fc72013-11-26 15:16:41 +0000791}
792
Damien George495d7812014-04-08 17:51:47 +0100793// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100794void mp_unpack_ex(mp_obj_t seq_in, mp_uint_t num_in, mp_obj_t *items) {
795 mp_uint_t num_left = num_in & 0xff;
796 mp_uint_t num_right = (num_in >> 8) & 0xff;
Damien Georgeeaaebf32014-09-23 10:59:05 +0100797 DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
Damien George9c4cbe22014-08-30 14:04:14 +0100798 mp_uint_t seq_len;
Damien George495d7812014-04-08 17:51:47 +0100799 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
800 mp_obj_t *seq_items;
801 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
802 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
803 } else {
804 if (num_left == 0 && num_right == 0) {
805 // *a, = b # sets a to b if b is a list
806 items[0] = seq_in;
807 return;
808 }
809 mp_obj_list_get(seq_in, &seq_len, &seq_items);
810 }
811 if (seq_len < num_left + num_right) {
812 goto too_short;
813 }
Damien George4abff752014-08-30 14:59:21 +0100814 for (mp_uint_t i = 0; i < num_right; i++) {
Damien George495d7812014-04-08 17:51:47 +0100815 items[i] = seq_items[seq_len - 1 - i];
816 }
817 items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
Damien George4abff752014-08-30 14:59:21 +0100818 for (mp_uint_t i = 0; i < num_left; i++) {
Damien George495d7812014-04-08 17:51:47 +0100819 items[num_right + 1 + i] = seq_items[num_left - 1 - i];
820 }
821 } else {
822 // Generic iterable; this gets a bit messy: we unpack known left length to the
823 // items destination array, then the rest to a dynamically created list. Once the
824 // iterable is exhausted, we take from this list for the right part of the items.
825 // TODO Improve to waste less memory in the dynamically created list.
826 mp_obj_t iterable = mp_getiter(seq_in);
827 mp_obj_t item;
828 for (seq_len = 0; seq_len < num_left; seq_len++) {
829 item = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100830 if (item == MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100831 goto too_short;
832 }
833 items[num_left + num_right + 1 - 1 - seq_len] = item;
834 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100835 mp_obj_list_t *rest = mp_obj_new_list(0, NULL);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100836 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100837 mp_obj_list_append(rest, item);
838 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100839 if (rest->len < num_right) {
Damien George495d7812014-04-08 17:51:47 +0100840 goto too_short;
841 }
842 items[num_right] = rest;
Damien George4abff752014-08-30 14:59:21 +0100843 for (mp_uint_t i = 0; i < num_right; i++) {
Damien Georgeca6d75f2014-08-30 15:17:47 +0100844 items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
Damien George495d7812014-04-08 17:51:47 +0100845 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100846 mp_obj_list_set_len(rest, rest->len - num_right);
Damien George495d7812014-04-08 17:51:47 +0100847 }
848 return;
849
850too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000851 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
852 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
853 "wrong number of values to unpack"));
854 } else {
855 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
856 "need more than %d values to unpack", seq_len));
857 }
Damien George495d7812014-04-08 17:51:47 +0100858}
859
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300860mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
Damien George062478e2014-01-09 20:57:50 +0000861 DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300862 // use load_method
Damien George062478e2014-01-09 20:57:50 +0000863 mp_obj_t dest[2];
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300864 mp_load_method(base, attr, dest);
865 if (dest[1] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000866 // load_method returned just a normal attribute
Damien George20006db2014-01-18 14:10:48 +0000867 return dest[0];
Damien George062478e2014-01-09 20:57:50 +0000868 } else {
869 // load_method returned a method, so build a bound method object
870 return mp_obj_new_bound_meth(dest[0], dest[1]);
Damiend99b0522013-12-21 18:17:45 +0000871 }
Damiend99b0522013-12-21 18:17:45 +0000872}
873
Damien George7c9c6672014-01-25 00:17:36 +0000874// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
875// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
876// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
Damien Georgee44d26a2014-03-31 22:57:56 +0100877void mp_load_method_maybe(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George062478e2014-01-09 20:57:50 +0000878 // clear output to indicate no attribute/method found yet
879 dest[0] = MP_OBJ_NULL;
880 dest[1] = MP_OBJ_NULL;
881
882 // get the type
883 mp_obj_type_t *type = mp_obj_get_type(base);
884
Damien Georgee44d26a2014-03-31 22:57:56 +0100885 // look for built-in names
886 if (0) {
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300887#if MICROPY_CPYTHON_COMPAT
Damien Georgee44d26a2014-03-31 22:57:56 +0100888 } else if (attr == MP_QSTR___class__) {
889 // a.__class__ is equivalent to type(a)
890 dest[0] = type;
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300891#endif
Damien Georgee44d26a2014-03-31 22:57:56 +0100892
893 } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
894 dest[0] = (mp_obj_t)&mp_builtin_next_obj;
895 dest[1] = base;
896
897 } else if (type->load_attr != NULL) {
898 // this type can do its own load, so call it
899 type->load_attr(base, attr, dest);
900
901 } else if (type->locals_dict != NULL) {
902 // generic method lookup
903 // this is a lookup in the object (ie not class or type)
904 assert(MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)); // Micro Python restriction, for now
905 mp_map_t *locals_map = mp_obj_dict_get_map(type->locals_dict);
906 mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
907 if (elem != NULL) {
908 // check if the methods are functions, static or class methods
Chris Angelicodaf973a2014-06-06 03:51:03 +1000909 // see http://docs.python.org/3/howto/descriptor.html
Damien Georgee44d26a2014-03-31 22:57:56 +0100910 if (MP_OBJ_IS_TYPE(elem->value, &mp_type_staticmethod)) {
911 // return just the function
912 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
913 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_classmethod)) {
914 // return a bound method, with self being the type of this object
915 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
916 dest[1] = mp_obj_get_type(base);
Paul Sokolovsky9511f602014-05-11 03:12:36 +0300917 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_type)) {
918 // Don't try to bind types
919 dest[0] = elem->value;
Damien Georgee44d26a2014-03-31 22:57:56 +0100920 } else if (mp_obj_is_callable(elem->value)) {
921 // return a bound method, with self being this object
922 dest[0] = elem->value;
923 dest[1] = base;
924 } else {
925 // class member is a value, so just return that value
926 dest[0] = elem->value;
Damiend57eba52013-11-02 23:58:14 +0000927 }
928 }
Damiena3977762013-10-09 23:10:10 +0100929 }
Damien George7c9c6672014-01-25 00:17:36 +0000930}
Damiena3977762013-10-09 23:10:10 +0100931
Damien Georged17926d2014-03-30 13:35:08 +0100932void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George7c9c6672014-01-25 00:17:36 +0000933 DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
934
Damien Georged17926d2014-03-30 13:35:08 +0100935 mp_load_method_maybe(base, attr, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000936
937 if (dest[0] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000938 // no attribute/method called attr
Damien George1e9a92f2014-11-06 17:36:16 +0000939 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
940 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
941 "no such attribute"));
Damien George062478e2014-01-09 20:57:50 +0000942 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000943 // following CPython, we give a more detailed error message for type objects
944 if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
945 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
946 "type object '%s' has no attribute '%s'",
947 qstr_str(((mp_obj_type_t*)base)->name), qstr_str(attr)));
948 } else {
949 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
950 "'%s' object has no attribute '%s'",
951 mp_obj_get_type_str(base), qstr_str(attr)));
952 }
Damien George062478e2014-01-09 20:57:50 +0000953 }
954 }
Damiena3977762013-10-09 23:10:10 +0100955}
956
Damien Georged17926d2014-03-30 13:35:08 +0100957void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien5ac1b2e2013-10-18 19:58:12 +0100958 DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
Damien George062478e2014-01-09 20:57:50 +0000959 mp_obj_type_t *type = mp_obj_get_type(base);
960 if (type->store_attr != NULL) {
961 if (type->store_attr(base, attr, value)) {
962 return;
963 }
Damiena3977762013-10-09 23:10:10 +0100964 }
Damien George1e9a92f2014-11-06 17:36:16 +0000965 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
966 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
967 "no such attribute"));
968 } else {
969 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
970 "'%s' object has no attribute '%s'",
971 mp_obj_get_type_str(base), qstr_str(attr)));
972 }
Damiena3977762013-10-09 23:10:10 +0100973}
974
Damien Georged17926d2014-03-30 13:35:08 +0100975mp_obj_t mp_getiter(mp_obj_t o_in) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300976 assert(o_in);
Damien George5fa93b62014-01-22 14:35:10 +0000977 mp_obj_type_t *type = mp_obj_get_type(o_in);
978 if (type->getiter != NULL) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300979 mp_obj_t iter = type->getiter(o_in);
980 if (iter == MP_OBJ_NULL) {
981 goto not_iterable;
982 }
983 return iter;
Damience89a212013-10-15 22:25:17 +0100984 } else {
Damien George9e6e9352014-03-26 18:37:06 +0000985 // check for __iter__ method
Damien George7c9c6672014-01-25 00:17:36 +0000986 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +0100987 mp_load_method_maybe(o_in, MP_QSTR___iter__, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000988 if (dest[0] != MP_OBJ_NULL) {
Damien George9e6e9352014-03-26 18:37:06 +0000989 // __iter__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +0100990 return mp_call_method_n_kw(0, 0, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000991 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100992 mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
Damien George9e6e9352014-03-26 18:37:06 +0000993 if (dest[0] != MP_OBJ_NULL) {
994 // __getitem__ exists, create an iterator
995 return mp_obj_new_getitem_iter(dest);
996 } else {
997 // object not iterable
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300998not_iterable:
Damien George1e9a92f2014-11-06 17:36:16 +0000999 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1000 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1001 "object not iterable"));
1002 } else {
1003 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1004 "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
1005 }
Damien George9e6e9352014-03-26 18:37:06 +00001006 }
Damien George7c9c6672014-01-25 00:17:36 +00001007 }
Damience89a212013-10-15 22:25:17 +01001008 }
1009}
1010
Damien Georgeea8d06c2014-04-17 23:19:36 +01001011// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
Damien George66eaf842014-03-26 19:27:58 +00001012// may also raise StopIteration()
Damien Georged17926d2014-03-30 13:35:08 +01001013mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001014 mp_obj_type_t *type = mp_obj_get_type(o_in);
1015 if (type->iternext != NULL) {
1016 return type->iternext(o_in);
Damience89a212013-10-15 22:25:17 +01001017 } else {
Damien George9e6e9352014-03-26 18:37:06 +00001018 // check for __next__ method
1019 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001020 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001021 if (dest[0] != MP_OBJ_NULL) {
1022 // __next__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +01001023 return mp_call_method_n_kw(0, 0, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001024 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001025 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1026 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1027 "object not an iterator"));
1028 } else {
1029 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1030 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1031 }
Damien George9e6e9352014-03-26 18:37:06 +00001032 }
Damien Georgec5966122014-02-15 16:10:44 +00001033 }
1034}
1035
Damien Georgeea8d06c2014-04-17 23:19:36 +01001036// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
Damien George66eaf842014-03-26 19:27:58 +00001037// may raise other exceptions
Damien Georged17926d2014-03-30 13:35:08 +01001038mp_obj_t mp_iternext(mp_obj_t o_in) {
Damien George66eaf842014-03-26 19:27:58 +00001039 mp_obj_type_t *type = mp_obj_get_type(o_in);
1040 if (type->iternext != NULL) {
1041 return type->iternext(o_in);
1042 } else {
1043 // check for __next__ method
1044 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001045 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George66eaf842014-03-26 19:27:58 +00001046 if (dest[0] != MP_OBJ_NULL) {
1047 // __next__ exists, call it and return its result
1048 nlr_buf_t nlr;
1049 if (nlr_push(&nlr) == 0) {
Damien Georged17926d2014-03-30 13:35:08 +01001050 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
Damien George66eaf842014-03-26 19:27:58 +00001051 nlr_pop();
1052 return ret;
1053 } else {
1054 if (mp_obj_is_subclass_fast(mp_obj_get_type(nlr.ret_val), &mp_type_StopIteration)) {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001055 return MP_OBJ_STOP_ITERATION;
Damien George66eaf842014-03-26 19:27:58 +00001056 } else {
Damien Georgeea13f402014-04-05 18:32:08 +01001057 nlr_raise(nlr.ret_val);
Damien George66eaf842014-03-26 19:27:58 +00001058 }
1059 }
1060 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001061 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1062 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1063 "object not an iterator"));
1064 } else {
1065 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1066 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1067 }
Damien George66eaf842014-03-26 19:27:58 +00001068 }
1069 }
1070}
1071
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001072// TODO: Unclear what to do with StopIterarion exception here.
1073mp_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 +03001074 assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001075 mp_obj_type_t *type = mp_obj_get_type(self_in);
1076
1077 if (type == &mp_type_gen_instance) {
1078 return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
1079 }
1080
1081 if (type->iternext != NULL && send_value == mp_const_none) {
1082 mp_obj_t ret = type->iternext(self_in);
1083 if (ret != MP_OBJ_NULL) {
1084 *ret_val = ret;
1085 return MP_VM_RETURN_YIELD;
1086 } else {
1087 // Emulate raise StopIteration()
1088 // Special case, handled in vm.c
1089 *ret_val = MP_OBJ_NULL;
1090 return MP_VM_RETURN_NORMAL;
1091 }
1092 }
1093
1094 mp_obj_t dest[3]; // Reserve slot for send() arg
1095
1096 if (send_value == mp_const_none) {
1097 mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1098 if (dest[0] != MP_OBJ_NULL) {
1099 *ret_val = mp_call_method_n_kw(0, 0, dest);
1100 return MP_VM_RETURN_YIELD;
1101 }
1102 }
1103
1104 if (send_value != MP_OBJ_NULL) {
1105 mp_load_method(self_in, MP_QSTR_send, dest);
1106 dest[2] = send_value;
1107 *ret_val = mp_call_method_n_kw(1, 0, dest);
1108 return MP_VM_RETURN_YIELD;
1109 }
1110
1111 if (throw_value != MP_OBJ_NULL) {
1112 if (mp_obj_is_subclass_fast(mp_obj_get_type(throw_value), &mp_type_GeneratorExit)) {
1113 mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1114 if (dest[0] != MP_OBJ_NULL) {
1115 *ret_val = mp_call_method_n_kw(0, 0, dest);
1116 // We assume one can't "yield" from close()
1117 return MP_VM_RETURN_NORMAL;
1118 }
1119 }
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001120 mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1121 if (dest[0] != MP_OBJ_NULL) {
1122 *ret_val = mp_call_method_n_kw(1, 0, &throw_value);
1123 // If .throw() method returned, we assume it's value to yield
Damien Georgeea13f402014-04-05 18:32:08 +01001124 // - any exception would be thrown with nlr_raise().
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001125 return MP_VM_RETURN_YIELD;
1126 }
1127 // If there's nowhere to throw exception into, then we assume that object
1128 // is just incapable to handle it, so any exception thrown into it
1129 // will be propagated up. This behavior is approved by test_pep380.py
1130 // test_delegation_of_close_to_non_generator(),
1131 // test_delegating_throw_to_non_generator()
1132 *ret_val = throw_value;
1133 return MP_VM_RETURN_EXCEPTION;
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001134 }
1135
1136 assert(0);
1137 return MP_VM_RETURN_NORMAL; // Should be unreachable
1138}
1139
Damien Georged17926d2014-03-30 13:35:08 +01001140mp_obj_t mp_make_raise_obj(mp_obj_t o) {
Damien Georgec5966122014-02-15 16:10:44 +00001141 DEBUG_printf("raise %p\n", o);
1142 if (mp_obj_is_exception_type(o)) {
1143 // o is an exception type (it is derived from BaseException (or is BaseException))
1144 // create and return a new exception instance by calling o
Damien George22a08652014-02-15 21:05:25 +00001145 // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1146 // could have const instances in ROM which we return here instead
Damien Georged17926d2014-03-30 13:35:08 +01001147 return mp_call_function_n_kw(o, 0, 0, NULL);
Damien Georgec5966122014-02-15 16:10:44 +00001148 } else if (mp_obj_is_exception_instance(o)) {
1149 // o is an instance of an exception, so use it as the exception
1150 return o;
1151 } else {
1152 // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1153 return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
Damience89a212013-10-15 22:25:17 +01001154 }
1155}
1156
Damien Georged17926d2014-03-30 13:35:08 +01001157mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
Damien George64131f32014-02-06 20:31:44 +00001158 DEBUG_printf("import name %s\n", qstr_str(name));
1159
Damiendb4c3612013-12-10 17:27:24 +00001160 // build args array
Damiend99b0522013-12-21 18:17:45 +00001161 mp_obj_t args[5];
Damien George5fa93b62014-01-22 14:35:10 +00001162 args[0] = MP_OBJ_NEW_QSTR(name);
Damiend99b0522013-12-21 18:17:45 +00001163 args[1] = mp_const_none; // TODO should be globals
1164 args[2] = mp_const_none; // TODO should be locals
Damiendb4c3612013-12-10 17:27:24 +00001165 args[3] = fromlist;
1166 args[4] = level; // must be 0; we don't yet support other values
1167
1168 // TODO lookup __import__ and call that instead of going straight to builtin implementation
Damiend99b0522013-12-21 18:17:45 +00001169 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001170}
1171
Damien Georged17926d2014-03-30 13:35:08 +01001172mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
Damien George64131f32014-02-06 20:31:44 +00001173 DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1174
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001175 mp_obj_t dest[2];
1176
1177 mp_load_method_maybe(module, name, dest);
1178
1179 if (dest[1] != MP_OBJ_NULL) {
1180 // Hopefully we can't import bound method from an object
1181import_error:
Paul Sokolovsky42453dc2014-04-12 03:00:40 +03001182 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %s", qstr_str(name)));
Damiendb4c3612013-12-10 17:27:24 +00001183 }
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001184
1185 if (dest[0] != MP_OBJ_NULL) {
1186 return dest[0];
1187 }
1188
1189 // See if it's a package, then can try FS import
Paul Sokolovskye5a37592014-10-25 21:04:13 +03001190 if (!mp_obj_is_package(module)) {
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001191 goto import_error;
1192 }
1193
1194 mp_load_method_maybe(module, MP_QSTR___name__, dest);
Damien Georged182b982014-08-30 14:19:41 +01001195 mp_uint_t pkg_name_len;
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001196 const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1197
stijn01d6be42014-05-05 12:18:27 +02001198 const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1199 char *dot_name = alloca(dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001200 memcpy(dot_name, pkg_name, pkg_name_len);
1201 dot_name[pkg_name_len] = '.';
1202 memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
stijn01d6be42014-05-05 12:18:27 +02001203 qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001204
1205 mp_obj_t args[5];
1206 args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
1207 args[1] = mp_const_none; // TODO should be globals
1208 args[2] = mp_const_none; // TODO should be locals
1209 args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
Paul Sokolovsky69f18672014-04-12 02:47:46 +03001210 args[4] = MP_OBJ_NEW_SMALL_INT(0);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001211
1212 // TODO lookup __import__ and call that instead of going straight to builtin implementation
1213 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001214}
1215
Damien Georged17926d2014-03-30 13:35:08 +01001216void mp_import_all(mp_obj_t module) {
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001217 DEBUG_printf("import all %p\n", module);
1218
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001219 // TODO: Support __all__
Damien George8b0535e2014-04-05 21:53:54 +01001220 mp_map_t *map = mp_obj_dict_get_map(mp_obj_module_get_globals(module));
Damien Georgeb063b9b2014-12-21 16:24:09 +00001221 for (mp_uint_t i = 0; i < map->alloc; i++) {
Damien George8b0535e2014-04-05 21:53:54 +01001222 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001223 qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
1224 if (*qstr_str(name) != '_') {
1225 mp_store_name(name, map->table[i].value);
1226 }
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001227 }
1228 }
1229}
1230
Damien Georgec4d08682014-10-05 20:13:34 +01001231// this is implemented in this file so it can optimise access to locals/globals
1232mp_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) {
1233 // parse the string
1234 mp_parse_error_kind_t parse_error_kind;
1235 mp_parse_node_t pn = mp_parse(lex, parse_input_kind, &parse_error_kind);
1236
1237 if (pn == MP_PARSE_NODE_NULL) {
1238 // parse error; raise exception
1239 mp_obj_t exc = mp_parse_make_exception(lex, parse_error_kind);
1240 mp_lexer_free(lex);
1241 nlr_raise(exc);
1242 }
1243
Damien Georgea4c52c52014-12-05 19:35:18 +00001244 qstr source_name = lex->source_name;
Damien Georgec4d08682014-10-05 20:13:34 +01001245 mp_lexer_free(lex);
1246
1247 // save context and set new context
1248 mp_obj_dict_t *old_globals = mp_globals_get();
1249 mp_obj_dict_t *old_locals = mp_locals_get();
1250 mp_globals_set(globals);
1251 mp_locals_set(locals);
1252
1253 // compile the string
1254 mp_obj_t module_fun = mp_compile(pn, source_name, MP_EMIT_OPT_NONE, false);
1255
1256 // check if there was a compile error
1257 if (mp_obj_is_exception_instance(module_fun)) {
1258 mp_globals_set(old_globals);
1259 mp_locals_set(old_locals);
1260 nlr_raise(module_fun);
1261 }
1262
Damien Georgec9fc6202014-10-25 21:59:14 +01001263 // for compile only
1264 if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
1265 mp_globals_set(old_globals);
1266 mp_locals_set(old_locals);
1267 return module_fun;
1268 }
1269
Damien Georgec4d08682014-10-05 20:13:34 +01001270 // complied successfully, execute it
1271 nlr_buf_t nlr;
1272 if (nlr_push(&nlr) == 0) {
1273 mp_obj_t ret = mp_call_function_0(module_fun);
1274 nlr_pop();
1275 mp_globals_set(old_globals);
1276 mp_locals_set(old_locals);
1277 return ret;
1278 } else {
1279 // exception; restore context and re-raise same exception
1280 mp_globals_set(old_globals);
1281 mp_locals_set(old_locals);
1282 nlr_raise(nlr.ret_val);
1283 }
1284}
1285
Damien Georgeb0261342014-09-23 18:10:17 +01001286void *m_malloc_fail(size_t num_bytes) {
1287 DEBUG_printf("memory allocation failed, allocating " UINT_FMT " bytes\n", num_bytes);
Damien George40914452014-10-09 16:44:43 +01001288 if (0) {
1289 // dummy
1290 #if MICROPY_ENABLE_GC
1291 } else if (gc_is_locked()) {
1292 nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001293 "memory allocation failed, heap is locked"));
Damien George40914452014-10-09 16:44:43 +01001294 #endif
Dave Hylands3556e452014-10-07 00:50:20 -07001295 } else {
Damien George40914452014-10-09 16:44:43 +01001296 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001297 "memory allocation failed, allocating " UINT_FMT " bytes", num_bytes));
1298 }
Damien George6902eed2014-04-04 10:52:59 +00001299}
1300
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001301NORETURN void mp_not_implemented(const char *msg) {
1302 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, msg));
1303}