blob: 505c8e31af6b2b4cbf43042bdbbd84ddc105272c [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
Damien Georgec4d08682014-10-05 20:13:34 +010027#include <stdint.h>
Damien429d7192013-10-04 19:53:11 +010028#include <stdio.h>
29#include <string.h>
30#include <assert.h>
31
Paul Sokolovskyf54bcbf2014-05-02 17:47:01 +030032#include "mpconfig.h"
Damience89a212013-10-15 22:25:17 +010033#include "nlr.h"
Damien429d7192013-10-04 19:53:11 +010034#include "misc.h"
Damien George55baff42014-01-21 21:40:13 +000035#include "qstr.h"
Damien660365e2013-12-17 18:27:24 +000036#include "obj.h"
Damien George230fec72014-03-30 21:21:24 +010037#include "objtuple.h"
Damien Georgeca6d75f2014-08-30 15:17:47 +010038#include "objlist.h"
Damien Georgecaac5422014-03-25 14:18:18 +000039#include "objmodule.h"
Damien George20773972014-02-22 18:12:43 +000040#include "parsenum.h"
Damiend99b0522013-12-21 18:17:45 +000041#include "runtime0.h"
42#include "runtime.h"
Damien George2326d522014-03-27 23:26:35 +000043#include "emitglue.h"
Damien660365e2013-12-17 18:27:24 +000044#include "builtin.h"
Damien George5fa93b62014-01-22 14:35:10 +000045#include "bc.h"
Damien Georgeecf5b772014-04-04 11:13:51 +000046#include "smallint.h"
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +030047#include "objgenerator.h"
Paul Sokolovskyd3439d02014-06-02 19:37:55 +030048#include "lexer.h"
Damien Georgec4d08682014-10-05 20:13:34 +010049#include "parse.h"
50#include "parsehelper.h"
51#include "compile.h"
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030052#include "stackctrl.h"
Dave Hylands3556e452014-10-07 00:50:20 -070053#include "gc.h"
Damien660365e2013-12-17 18:27:24 +000054
Damien7f5dacf2013-10-10 11:24:39 +010055#if 0 // print debugging info
Damiena1ddfcc2013-10-10 23:25:50 +010056#define DEBUG_PRINT (1)
Paul Sokolovsky44739e22014-02-16 18:11:42 +020057#define DEBUG_printf DEBUG_printf
Damien George41eb6082014-02-26 22:40:35 +000058#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
Damien7f5dacf2013-10-10 11:24:39 +010059#else // don't print debugging info
Damien George41eb6082014-02-26 22:40:35 +000060#define DEBUG_printf(...) (void)0
61#define DEBUG_OP_printf(...) (void)0
Damien7f5dacf2013-10-10 11:24:39 +010062#endif
Damien429d7192013-10-04 19:53:11 +010063
Damien George124df6f2014-10-25 18:19:55 +010064// pending exception object (MP_OBJ_NULL if not pending)
65mp_obj_t mp_pending_exception;
66
Damieneb19efb2013-10-10 22:06:54 +010067// locals and globals need to be pointers because they can be the same in outer module scope
Damien George7efc5b32014-04-05 22:36:42 +010068STATIC mp_obj_dict_t *dict_locals;
69STATIC mp_obj_dict_t *dict_globals;
Damienbd254452013-10-16 20:39:12 +010070
Damien George7efc5b32014-04-05 22:36:42 +010071// dictionary for the __main__ module
Damien George8b0535e2014-04-05 21:53:54 +010072STATIC mp_obj_dict_t dict_main;
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030073
74const mp_obj_module_t mp_module___main__ = {
75 .base = { &mp_type_module },
76 .name = MP_QSTR___main__,
Damien George8b0535e2014-04-05 21:53:54 +010077 .globals = (mp_obj_dict_t*)&dict_main,
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030078};
79
Damien George78d702c2014-12-09 16:19:48 +000080#if MICROPY_CAN_OVERRIDE_BUILTINS
81mp_obj_dict_t *mp_module_builtins_override_dict;
82#endif
83
Damien Georged17926d2014-03-30 13:35:08 +010084void mp_init(void) {
Damien George8dbbbbc2014-08-04 10:05:16 +010085 qstr_init();
Paul Sokolovskycaa73342014-07-01 02:13:42 +030086 mp_stack_ctrl_init();
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030087
Damien George124df6f2014-10-25 18:19:55 +010088 // no pending exceptions to start with
89 mp_pending_exception = MP_OBJ_NULL;
90
Damien George8dbbbbc2014-08-04 10:05:16 +010091#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
92 mp_init_emergency_exception_buf();
93#endif
94
Damien George97f9a282014-05-12 23:07:34 +010095 // call port specific initialization if any
stijn72521a12014-05-03 11:28:29 +020096#ifdef MICROPY_PORT_INIT_FUNC
97 MICROPY_PORT_INIT_FUNC;
98#endif
99
Paul Sokolovskyd3439d02014-06-02 19:37:55 +0300100 // optimization disabled by default
101 mp_optimise_value = 0;
Damien George97f9a282014-05-12 23:07:34 +0100102
Damien Georgecaac5422014-03-25 14:18:18 +0000103 // init global module stuff
104 mp_module_init();
Damien George0d028742014-01-22 23:59:20 +0000105
Damien George7efc5b32014-04-05 22:36:42 +0100106 // initialise the __main__ module
Damien George8b0535e2014-04-05 21:53:54 +0100107 mp_obj_dict_init(&dict_main, 1);
Damien George8b0535e2014-04-05 21:53:54 +0100108 mp_obj_dict_store(&dict_main, MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
Paul Sokolovskyc6813d92014-04-04 20:08:21 +0300109
110 // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
Damien George7efc5b32014-04-05 22:36:42 +0100111 dict_locals = dict_globals = &dict_main;
Damien George78d702c2014-12-09 16:19:48 +0000112
113 #if MICROPY_CAN_OVERRIDE_BUILTINS
114 // start with no extensions to builtins
115 mp_module_builtins_override_dict = NULL;
116 #endif
Damien429d7192013-10-04 19:53:11 +0100117}
118
Damien Georged17926d2014-03-30 13:35:08 +0100119void mp_deinit(void) {
Damien George7efc5b32014-04-05 22:36:42 +0100120 //mp_obj_dict_free(&dict_main);
Damien George2326d522014-03-27 23:26:35 +0000121 mp_module_deinit();
stijn5ed284a2014-05-08 10:56:33 +0200122
123 // call port specific deinitialization if any
124#ifdef MICROPY_PORT_INIT_FUNC
125 MICROPY_PORT_DEINIT_FUNC;
126#endif
Damien429d7192013-10-04 19:53:11 +0100127}
128
Damien George503d6112014-05-28 14:07:21 +0100129mp_obj_t mp_load_const_int(qstr qstr) {
130 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100131 mp_uint_t len;
Damien George503d6112014-05-28 14:07:21 +0100132 const byte* data = qstr_data(qstr, &len);
133 return mp_parse_num_integer((const char*)data, len, 0);
134}
135
Damien Georged17926d2014-03-30 13:35:08 +0100136mp_obj_t mp_load_const_dec(qstr qstr) {
Damien7410e442013-11-02 19:47:57 +0000137 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100138 mp_uint_t len;
Damien George20773972014-02-22 18:12:43 +0000139 const byte* data = qstr_data(qstr, &len);
Damien George6e48f7f2014-03-21 11:45:46 +0000140 return mp_parse_num_decimal((const char*)data, len, true, false);
Damien7410e442013-11-02 19:47:57 +0000141}
142
Damien Georged17926d2014-03-30 13:35:08 +0100143mp_obj_t mp_load_const_str(qstr qstr) {
Damien429d7192013-10-04 19:53:11 +0100144 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George5fa93b62014-01-22 14:35:10 +0000145 return MP_OBJ_NEW_QSTR(qstr);
Damien429d7192013-10-04 19:53:11 +0100146}
147
Damien Georged17926d2014-03-30 13:35:08 +0100148mp_obj_t mp_load_const_bytes(qstr qstr) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200149 DEBUG_OP_printf("load b'%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100150 mp_uint_t len;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200151 const byte *data = qstr_data(qstr, &len);
152 return mp_obj_new_bytes(data, len);
153}
154
Damien Georged17926d2014-03-30 13:35:08 +0100155mp_obj_t mp_load_name(qstr qstr) {
Damien429d7192013-10-04 19:53:11 +0100156 // logic: search locals, globals, builtins
Damien George7efc5b32014-04-05 22:36:42 +0100157 DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300158 // If we're at the outer scope (locals == globals), dispatch to load_global right away
Damien George7efc5b32014-04-05 22:36:42 +0100159 if (dict_locals != dict_globals) {
160 mp_map_elem_t *elem = mp_map_lookup(&dict_locals->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300161 if (elem != NULL) {
162 return elem->value;
163 }
Damiena3977762013-10-09 23:10:10 +0100164 }
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300165 return mp_load_global(qstr);
Damiena3977762013-10-09 23:10:10 +0100166}
167
Damien Georged17926d2014-03-30 13:35:08 +0100168mp_obj_t mp_load_global(qstr qstr) {
Damiena3977762013-10-09 23:10:10 +0100169 // logic: search globals, builtins
170 DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
Damien George7efc5b32014-04-05 22:36:42 +0100171 mp_map_elem_t *elem = mp_map_lookup(&dict_globals->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100172 if (elem == NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000173 #if MICROPY_CAN_OVERRIDE_BUILTINS
174 if (mp_module_builtins_override_dict != NULL) {
175 // lookup in additional dynamic table of builtins first
176 elem = mp_map_lookup(&mp_module_builtins_override_dict->map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
177 if (elem != NULL) {
178 return elem->value;
179 }
180 }
181 #endif
182 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 +0100183 if (elem == NULL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000184 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
185 nlr_raise(mp_obj_new_exception_msg(&mp_type_NameError,
186 "name not defined"));
187 } else {
188 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
189 "name '%s' is not defined", qstr_str(qstr)));
190 }
Damien429d7192013-10-04 19:53:11 +0100191 }
192 }
193 return elem->value;
194}
195
Damien Georged17926d2014-03-30 13:35:08 +0100196mp_obj_t mp_load_build_class(void) {
Damien429d7192013-10-04 19:53:11 +0100197 DEBUG_OP_printf("load_build_class\n");
Damien George78d702c2014-12-09 16:19:48 +0000198 #if MICROPY_CAN_OVERRIDE_BUILTINS
199 if (mp_module_builtins_override_dict != NULL) {
200 // lookup in additional dynamic table of builtins first
201 mp_map_elem_t *elem = mp_map_lookup(&mp_module_builtins_override_dict->map, MP_OBJ_NEW_QSTR(MP_QSTR___build_class__), MP_MAP_LOOKUP);
202 if (elem != NULL) {
203 return elem->value;
204 }
205 }
206 #endif
Damien George7efc5b32014-04-05 22:36:42 +0100207 return (mp_obj_t)&mp_builtin___build_class___obj;
Damien429d7192013-10-04 19:53:11 +0100208}
209
Damien Georged17926d2014-03-30 13:35:08 +0100210void mp_store_name(qstr qstr, mp_obj_t obj) {
Damiena3977762013-10-09 23:10:10 +0100211 DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
Damien George7efc5b32014-04-05 22:36:42 +0100212 mp_obj_dict_store(dict_locals, MP_OBJ_NEW_QSTR(qstr), obj);
Damiena3977762013-10-09 23:10:10 +0100213}
214
Damien Georged17926d2014-03-30 13:35:08 +0100215void mp_delete_name(qstr qstr) {
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200216 DEBUG_OP_printf("delete name %s\n", qstr_str(qstr));
Damien George1d24ea52014-04-08 21:11:49 +0100217 // TODO convert KeyError to NameError if qstr not found
218 mp_obj_dict_delete(dict_locals, MP_OBJ_NEW_QSTR(qstr));
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200219}
220
Damien Georged17926d2014-03-30 13:35:08 +0100221void mp_store_global(qstr qstr, mp_obj_t obj) {
Damiena3977762013-10-09 23:10:10 +0100222 DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qstr), obj);
Damien George7efc5b32014-04-05 22:36:42 +0100223 mp_obj_dict_store(dict_globals, MP_OBJ_NEW_QSTR(qstr), obj);
Damien429d7192013-10-04 19:53:11 +0100224}
225
Damien George1d24ea52014-04-08 21:11:49 +0100226void mp_delete_global(qstr qstr) {
227 DEBUG_OP_printf("delete global %s\n", qstr_str(qstr));
228 // TODO convert KeyError to NameError if qstr not found
229 mp_obj_dict_delete(dict_globals, MP_OBJ_NEW_QSTR(qstr));
230}
231
Damien George4abff752014-08-30 14:59:21 +0100232mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100233 DEBUG_OP_printf("unary " UINT_FMT " %p\n", op, arg);
Damien George9aa2a522014-02-01 23:04:09 +0000234
Damiend99b0522013-12-21 18:17:45 +0000235 if (MP_OBJ_IS_SMALL_INT(arg)) {
Damien George40f3c022014-07-03 13:25:24 +0100236 mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
Damien7410e442013-11-02 19:47:57 +0000237 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100238 case MP_UNARY_OP_BOOL:
Damien George9d68e9c2014-03-12 15:38:15 +0000239 return MP_BOOL(val != 0);
Damien Georged17926d2014-03-30 13:35:08 +0100240 case MP_UNARY_OP_POSITIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000241 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100242 case MP_UNARY_OP_NEGATIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000243 // check for overflow
244 if (val == MP_SMALL_INT_MIN) {
245 return mp_obj_new_int(-val);
246 } else {
247 return MP_OBJ_NEW_SMALL_INT(-val);
248 }
Damien Georged17926d2014-03-30 13:35:08 +0100249 case MP_UNARY_OP_INVERT:
Damien George9d68e9c2014-03-12 15:38:15 +0000250 return MP_OBJ_NEW_SMALL_INT(~val);
251 default:
252 assert(0);
253 return arg;
Damien7410e442013-11-02 19:47:57 +0000254 }
Damien George1e708fe2014-01-23 18:27:51 +0000255 } else {
256 mp_obj_type_t *type = mp_obj_get_type(arg);
257 if (type->unary_op != NULL) {
258 mp_obj_t result = type->unary_op(op, arg);
Damien George6ac5dce2014-05-21 19:42:43 +0100259 if (result != MP_OBJ_NULL) {
Damiend99b0522013-12-21 18:17:45 +0000260 return result;
261 }
Damien7410e442013-11-02 19:47:57 +0000262 }
Damien George1e9a92f2014-11-06 17:36:16 +0000263 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
264 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
265 "unsupported type for operator"));
266 } else {
267 // TODO specify in error message what the operator is
268 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
269 "bad operand type for unary operator: '%s'",
270 mp_obj_get_type_str(arg)));
271 }
Damien7410e442013-11-02 19:47:57 +0000272 }
Damien429d7192013-10-04 19:53:11 +0100273}
274
Damien George4abff752014-08-30 14:59:21 +0100275mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100276 DEBUG_OP_printf("binary " UINT_FMT " %p %p\n", op, lhs, rhs);
Damien George14f945c2014-01-03 14:09:31 +0000277
278 // TODO correctly distinguish inplace operators for mutable objects
279 // lookup logic that CPython uses for +=:
280 // check for implemented +=
281 // then check for implemented +
282 // then check for implemented seq.inplace_concat
283 // then check for implemented seq.concat
284 // then fail
285 // note that list does not implement + or +=, so that inplace_concat is reached first for +=
286
Damien George9aa2a522014-02-01 23:04:09 +0000287 // deal with is
Damien Georged17926d2014-03-30 13:35:08 +0100288 if (op == MP_BINARY_OP_IS) {
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200289 return MP_BOOL(lhs == rhs);
290 }
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200291
Damien Georgebcbeea02014-01-11 10:47:22 +0000292 // deal with == and != for all types
Damien Georged17926d2014-03-30 13:35:08 +0100293 if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000294 if (mp_obj_equal(lhs, rhs)) {
Damien Georged17926d2014-03-30 13:35:08 +0100295 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000296 return mp_const_true;
297 } else {
298 return mp_const_false;
299 }
300 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100301 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000302 return mp_const_false;
303 } else {
304 return mp_const_true;
305 }
306 }
307 }
308
309 // deal with exception_match for all types
Damien Georged17926d2014-03-30 13:35:08 +0100310 if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
Damien Georgec5966122014-02-15 16:10:44 +0000311 // rhs must be issubclass(rhs, BaseException)
312 if (mp_obj_is_exception_type(rhs)) {
Damien George4bcd04b2014-09-24 14:05:40 +0100313 if (mp_obj_exception_match(lhs, rhs)) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000314 return mp_const_true;
315 } else {
316 return mp_const_false;
317 }
Damien George4bcd04b2014-09-24 14:05:40 +0100318 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
319 mp_obj_tuple_t *tuple = rhs;
320 for (mp_uint_t i = 0; i < tuple->len; i++) {
321 rhs = tuple->items[i];
322 if (!mp_obj_is_exception_type(rhs)) {
323 goto unsupported_op;
324 }
325 if (mp_obj_exception_match(lhs, rhs)) {
326 return mp_const_true;
327 }
328 }
329 return mp_const_false;
Damien Georgebcbeea02014-01-11 10:47:22 +0000330 }
Damien George4bcd04b2014-09-24 14:05:40 +0100331 goto unsupported_op;
Damien Georgebcbeea02014-01-11 10:47:22 +0000332 }
333
Damien George1a9951d2014-01-06 22:13:00 +0000334 if (MP_OBJ_IS_SMALL_INT(lhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100335 mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
Damien George1a9951d2014-01-06 22:13:00 +0000336 if (MP_OBJ_IS_SMALL_INT(rhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100337 mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
Damien George9d68e9c2014-03-12 15:38:15 +0000338 // This is a binary operation: lhs_val op rhs_val
339 // We need to be careful to handle overflow; see CERT INT32-C
340 // Operations that can overflow:
Damien George40f3c022014-07-03 13:25:24 +0100341 // + result always fits in mp_int_t, then handled by SMALL_INT check
342 // - result always fits in mp_int_t, then handled by SMALL_INT check
Damien George9d68e9c2014-03-12 15:38:15 +0000343 // * checked explicitly
Damien George40f3c022014-07-03 13:25:24 +0100344 // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
345 // % 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 +0000346 // << checked explicitly
Damien George1a9951d2014-01-06 22:13:00 +0000347 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100348 case MP_BINARY_OP_OR:
349 case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
350 case MP_BINARY_OP_XOR:
351 case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
352 case MP_BINARY_OP_AND:
353 case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
354 case MP_BINARY_OP_LSHIFT:
355 case MP_BINARY_OP_INPLACE_LSHIFT: {
Damien George9d68e9c2014-03-12 15:38:15 +0000356 if (rhs_val < 0) {
357 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100358 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000359 } else if (rhs_val >= BITS_PER_WORD || lhs_val > (MP_SMALL_INT_MAX >> rhs_val) || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
360 // left-shift will overflow, so use higher precision integer
361 lhs = mp_obj_new_int_from_ll(lhs_val);
362 goto generic_binary_op;
363 } else {
364 // use standard precision
365 lhs_val <<= rhs_val;
366 }
367 break;
368 }
Damien Georged17926d2014-03-30 13:35:08 +0100369 case MP_BINARY_OP_RSHIFT:
370 case MP_BINARY_OP_INPLACE_RSHIFT:
Damien George9d68e9c2014-03-12 15:38:15 +0000371 if (rhs_val < 0) {
372 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100373 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000374 } else {
375 // standard precision is enough for right-shift
Paul Sokolovsky039887a2014-11-02 02:39:41 +0200376 if (rhs_val >= BITS_PER_WORD) {
377 // Shifting to big amounts is underfined behavior
378 // in C and is CPU-dependent; propagate sign bit.
379 rhs_val = BITS_PER_WORD - 1;
380 }
Damien George9d68e9c2014-03-12 15:38:15 +0000381 lhs_val >>= rhs_val;
382 }
383 break;
Damien Georged17926d2014-03-30 13:35:08 +0100384 case MP_BINARY_OP_ADD:
385 case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
386 case MP_BINARY_OP_SUBTRACT:
387 case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
388 case MP_BINARY_OP_MULTIPLY:
389 case MP_BINARY_OP_INPLACE_MULTIPLY: {
Damien George9d68e9c2014-03-12 15:38:15 +0000390
Damien George40f3c022014-07-03 13:25:24 +0100391 // If long long type exists and is larger than mp_int_t, then
Damien George9d68e9c2014-03-12 15:38:15 +0000392 // we can use the following code to perform overflow-checked multiplication.
Damien Georgeecf5b772014-04-04 11:13:51 +0000393 // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
Damien George9d68e9c2014-03-12 15:38:15 +0000394 #if 0
395 // compute result using long long precision
396 long long res = (long long)lhs_val * (long long)rhs_val;
397 if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
398 // result overflowed SMALL_INT, so return higher precision integer
399 return mp_obj_new_int_from_ll(res);
400 } else {
401 // use standard precision
Damien George40f3c022014-07-03 13:25:24 +0100402 lhs_val = (mp_int_t)res;
Damien George9d68e9c2014-03-12 15:38:15 +0000403 }
404 #endif
405
Damien Georgeecf5b772014-04-04 11:13:51 +0000406 if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
407 // use higher precision
408 lhs = mp_obj_new_int_from_ll(lhs_val);
409 goto generic_binary_op;
410 } else {
411 // use standard precision
412 return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
413 }
Damien George9d68e9c2014-03-12 15:38:15 +0000414 break;
415 }
Damien Georged17926d2014-03-30 13:35:08 +0100416 case MP_BINARY_OP_FLOOR_DIVIDE:
417 case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300418 if (rhs_val == 0) {
419 goto zero_division;
420 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000421 lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
Rachel Dowdall56402792014-03-22 20:19:24 +0000422 break;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300423
Damien Georgefb510b32014-06-01 13:32:54 +0100424 #if MICROPY_PY_BUILTINS_FLOAT
Damien Georged17926d2014-03-30 13:35:08 +0100425 case MP_BINARY_OP_TRUE_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300426 case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
427 if (rhs_val == 0) {
Damien George70f33cd2014-04-02 17:06:05 +0100428 goto zero_division;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300429 }
430 return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000431 #endif
Damiena3dcd9e2013-12-17 21:35:38 +0000432
Damien Georged17926d2014-03-30 13:35:08 +0100433 case MP_BINARY_OP_MODULO:
Damien Georgeecf5b772014-04-04 11:13:51 +0000434 case MP_BINARY_OP_INPLACE_MODULO: {
435 lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
Rachel Dowdallcde86312014-03-22 17:29:27 +0000436 break;
437 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000438
Damien Georged17926d2014-03-30 13:35:08 +0100439 case MP_BINARY_OP_POWER:
440 case MP_BINARY_OP_INPLACE_POWER:
Damien George9d68e9c2014-03-12 15:38:15 +0000441 if (rhs_val < 0) {
Damien Georgefb510b32014-06-01 13:32:54 +0100442 #if MICROPY_PY_BUILTINS_FLOAT
Damien George9d68e9c2014-03-12 15:38:15 +0000443 lhs = mp_obj_new_float(lhs_val);
444 goto generic_binary_op;
445 #else
Damien Georgeea13f402014-04-05 18:32:08 +0100446 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative power with no float support"));
Damien George9d68e9c2014-03-12 15:38:15 +0000447 #endif
448 } else {
Damien George40f3c022014-07-03 13:25:24 +0100449 mp_int_t ans = 1;
Damien George9d68e9c2014-03-12 15:38:15 +0000450 while (rhs_val > 0) {
451 if (rhs_val & 1) {
Damien Georgeecf5b772014-04-04 11:13:51 +0000452 if (mp_small_int_mul_overflow(ans, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100453 goto power_overflow;
454 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000455 ans *= lhs_val;
Damien George9d68e9c2014-03-12 15:38:15 +0000456 }
Damien George5bf565e2014-04-04 00:16:32 +0100457 if (rhs_val == 1) {
458 break;
459 }
Damien George9d68e9c2014-03-12 15:38:15 +0000460 rhs_val /= 2;
Damien Georgeecf5b772014-04-04 11:13:51 +0000461 if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100462 goto power_overflow;
463 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000464 lhs_val *= lhs_val;
Damien George1a9951d2014-01-06 22:13:00 +0000465 }
Damien George9d68e9c2014-03-12 15:38:15 +0000466 lhs_val = ans;
Damiena3dcd9e2013-12-17 21:35:38 +0000467 }
Damien George1a9951d2014-01-06 22:13:00 +0000468 break;
Damien George5bf565e2014-04-04 00:16:32 +0100469
470 power_overflow:
471 // use higher precision
472 lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
473 goto generic_binary_op;
474
Damien Georged17926d2014-03-30 13:35:08 +0100475 case MP_BINARY_OP_LESS: return MP_BOOL(lhs_val < rhs_val); break;
476 case MP_BINARY_OP_MORE: return MP_BOOL(lhs_val > rhs_val); break;
477 case MP_BINARY_OP_LESS_EQUAL: return MP_BOOL(lhs_val <= rhs_val); break;
478 case MP_BINARY_OP_MORE_EQUAL: return MP_BOOL(lhs_val >= rhs_val); break;
Damiena3dcd9e2013-12-17 21:35:38 +0000479
Damien George8bcb9862014-04-17 16:26:50 +0100480 default:
481 goto unsupported_op;
Damien George1a9951d2014-01-06 22:13:00 +0000482 }
Paul Sokolovsky757ac812014-01-12 17:06:25 +0200483 // TODO: We just should make mp_obj_new_int() inline and use that
Damien Georged1e355e2014-05-28 14:51:12 +0100484 if (MP_SMALL_INT_FITS(lhs_val)) {
Damien George1a9951d2014-01-06 22:13:00 +0000485 return MP_OBJ_NEW_SMALL_INT(lhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000486 } else {
487 return mp_obj_new_int(lhs_val);
Damien George1a9951d2014-01-06 22:13:00 +0000488 }
Damien Georgefb510b32014-06-01 13:32:54 +0100489#if MICROPY_PY_BUILTINS_FLOAT
Damien George0c36da02014-03-08 15:24:39 +0000490 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_float)) {
Damien Georgeae491052014-04-10 20:08:11 +0100491 mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
492 if (res == MP_OBJ_NULL) {
493 goto unsupported_op;
494 } else {
495 return res;
496 }
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300497#if MICROPY_PY_BUILTINS_COMPLEX
Damien George0c36da02014-03-08 15:24:39 +0000498 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
Damien Georgeae491052014-04-10 20:08:11 +0100499 mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
500 if (res == MP_OBJ_NULL) {
501 goto unsupported_op;
502 } else {
503 return res;
504 }
Damien George3f759b72014-01-31 00:42:12 +0000505#endif
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300506#endif
Damien429d7192013-10-04 19:53:11 +0100507 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000508 }
John R. Lentonb8698fc2014-01-11 00:58:59 +0000509
Damien George9aa2a522014-02-01 23:04:09 +0000510 /* deal with `in`
John R. Lentonc1bef212014-01-11 12:39:33 +0000511 *
512 * NOTE `a in b` is `b.__contains__(a)`, hence why the generic dispatch
Damien George48697f12014-02-01 23:32:29 +0000513 * needs to go below with swapped arguments
John R. Lentonc1bef212014-01-11 12:39:33 +0000514 */
Damien Georged17926d2014-03-30 13:35:08 +0100515 if (op == MP_BINARY_OP_IN) {
Damien George5fa93b62014-01-22 14:35:10 +0000516 mp_obj_type_t *type = mp_obj_get_type(rhs);
517 if (type->binary_op != NULL) {
518 mp_obj_t res = type->binary_op(op, rhs, lhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100519 if (res != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000520 return res;
521 }
522 }
523 if (type->getiter != NULL) {
524 /* second attempt, walk the iterator */
Damien Georged17926d2014-03-30 13:35:08 +0100525 mp_obj_t iter = mp_getiter(rhs);
Damien George3aa09f52014-10-23 12:06:53 +0100526 mp_obj_t next;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100527 while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
Damien George5fa93b62014-01-22 14:35:10 +0000528 if (mp_obj_equal(next, lhs)) {
Damien George9aa2a522014-02-01 23:04:09 +0000529 return mp_const_true;
John R. Lentonb8698fc2014-01-11 00:58:59 +0000530 }
Damien7410e442013-11-02 19:47:57 +0000531 }
Damien George9aa2a522014-02-01 23:04:09 +0000532 return mp_const_false;
Damien7410e442013-11-02 19:47:57 +0000533 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000534
Damien George1e9a92f2014-11-06 17:36:16 +0000535 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
536 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
537 "object not iterable"));
538 } else {
539 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
540 "'%s' object is not iterable", mp_obj_get_type_str(rhs)));
541 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000542 }
543
Damien George5fa93b62014-01-22 14:35:10 +0000544 // generic binary_op supplied by type
Damien George9d68e9c2014-03-12 15:38:15 +0000545 mp_obj_type_t *type;
546generic_binary_op:
547 type = mp_obj_get_type(lhs);
Damien George5fa93b62014-01-22 14:35:10 +0000548 if (type->binary_op != NULL) {
549 mp_obj_t result = type->binary_op(op, lhs, rhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100550 if (result != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000551 return result;
John R. Lentonc1bef212014-01-11 12:39:33 +0000552 }
Damien429d7192013-10-04 19:53:11 +0100553 }
Damiend99b0522013-12-21 18:17:45 +0000554
Damien George5fa93b62014-01-22 14:35:10 +0000555 // TODO implement dispatch for reverse binary ops
556
Damien Georgeae491052014-04-10 20:08:11 +0100557unsupported_op:
Damien George1e9a92f2014-11-06 17:36:16 +0000558 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
559 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
560 "unsupported type for operator"));
561 } else {
562 // TODO specify in error message what the operator is
563 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
564 "unsupported operand types for binary operator: '%s', '%s'",
565 mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs)));
566 }
Damien George70f33cd2014-04-02 17:06:05 +0100567
568zero_division:
Damien Georgeea13f402014-04-05 18:32:08 +0100569 nlr_raise(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero"));
Damien429d7192013-10-04 19:53:11 +0100570}
571
Damien Georged17926d2014-03-30 13:35:08 +0100572mp_obj_t mp_call_function_0(mp_obj_t fun) {
573 return mp_call_function_n_kw(fun, 0, 0, NULL);
Damieneb19efb2013-10-10 22:06:54 +0100574}
575
Damien Georged17926d2014-03-30 13:35:08 +0100576mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
577 return mp_call_function_n_kw(fun, 1, 0, &arg);
Damieneb19efb2013-10-10 22:06:54 +0100578}
579
Damien Georged17926d2014-03-30 13:35:08 +0100580mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
Damiend99b0522013-12-21 18:17:45 +0000581 mp_obj_t args[2];
Damien George20006db2014-01-18 14:10:48 +0000582 args[0] = arg1;
583 args[1] = arg2;
Damien Georged17926d2014-03-30 13:35:08 +0100584 return mp_call_function_n_kw(fun, 2, 0, args);
Damieneb19efb2013-10-10 22:06:54 +0100585}
586
Damien George20006db2014-01-18 14:10:48 +0000587// args contains, eg: arg0 arg1 key0 value0 key1 value1
Damien George4abff752014-08-30 14:59:21 +0100588mp_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 +0000589 // TODO improve this: fun object can specify its type and we parse here the arguments,
590 // passing to the function arrays of fixed and keyword arguments
Damieneb19efb2013-10-10 22:06:54 +0100591
Damien Georgeeaaebf32014-09-23 10:59:05 +0100592 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 +0000593
Damien George8b56beb2014-01-31 23:49:49 +0000594 // get the type
595 mp_obj_type_t *type = mp_obj_get_type(fun_in);
596
597 // do the call
598 if (type->call != NULL) {
Damien George3f522622014-06-03 13:40:16 +0100599 return type->call(fun_in, n_args, n_kw, args);
John R. Lenton9c83ec02014-01-07 23:06:46 +0000600 }
Paul Sokolovsky755565d2014-04-25 21:15:16 +0300601
Damien George1e9a92f2014-11-06 17:36:16 +0000602 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
603 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
604 "object not callable"));
605 } else {
606 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
607 "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
608 }
Damien86c7fc72013-11-26 15:16:41 +0000609}
610
Damien George20006db2014-01-18 14:10:48 +0000611// 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)
612// if n_args==0 and n_kw==0 then there are only fun and self/NULL
Damien George4abff752014-08-30 14:59:21 +0100613mp_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 +0100614 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 +0000615 int adjust = (args[1] == NULL) ? 0 : 1;
Damien Georged17926d2014-03-30 13:35:08 +0100616 return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
Damien86c7fc72013-11-26 15:16:41 +0000617}
618
Damien George4abff752014-08-30 14:59:21 +0100619mp_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 +0100620 mp_obj_t fun = *args++;
621 mp_obj_t self = MP_OBJ_NULL;
622 if (have_self) {
623 self = *args++; // may be MP_OBJ_NULL
624 }
625 uint n_args = n_args_n_kw & 0xff;
626 uint n_kw = (n_args_n_kw >> 8) & 0xff;
Damien George523b5752014-03-31 11:59:23 +0100627 mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // map be MP_OBJ_NULL
628 mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // map be MP_OBJ_NULL
Damien George230fec72014-03-30 21:21:24 +0100629
630 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);
631
632 // We need to create the following array of objects:
633 // args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
634 // TODO: optimize one day to avoid constructing new arg array? Will be hard.
635
636 // The new args array
637 mp_obj_t *args2;
638 uint args2_alloc;
639 uint args2_len = 0;
640
641 // Try to get a hint for the size of the kw_dict
642 uint kw_dict_len = 0;
643 if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
644 kw_dict_len = mp_obj_dict_len(kw_dict);
645 }
646
647 // Extract the pos_seq sequence to the new args array.
648 // Note that it can be arbitrary iterator.
649 if (pos_seq == MP_OBJ_NULL) {
650 // no sequence
651
652 // allocate memory for the new array of args
653 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
654 args2 = m_new(mp_obj_t, args2_alloc);
655
656 // copy the self
657 if (self != MP_OBJ_NULL) {
658 args2[args2_len++] = self;
659 }
660
661 // copy the fixed pos args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300662 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100663 args2_len += n_args;
664
665 } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
666 // optimise the case of a tuple and list
667
668 // get the items
Damien George9c4cbe22014-08-30 14:04:14 +0100669 mp_uint_t len;
Damien George230fec72014-03-30 21:21:24 +0100670 mp_obj_t *items;
671 mp_obj_get_array(pos_seq, &len, &items);
672
673 // allocate memory for the new array of args
674 args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
675 args2 = m_new(mp_obj_t, args2_alloc);
676
677 // copy the self
678 if (self != MP_OBJ_NULL) {
679 args2[args2_len++] = self;
680 }
681
682 // copy the fixed and variable position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300683 mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100684 args2_len += n_args + len;
685
686 } else {
687 // generic iterator
688
689 // allocate memory for the new array of args
690 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
691 args2 = m_new(mp_obj_t, args2_alloc);
692
693 // copy the self
694 if (self != MP_OBJ_NULL) {
695 args2[args2_len++] = self;
696 }
697
698 // copy the fixed position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300699 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100700
701 // extract the variable position args from the iterator
702 mp_obj_t iterable = mp_getiter(pos_seq);
703 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100704 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100705 if (args2_len >= args2_alloc) {
706 args2 = m_renew(mp_obj_t, args2, args2_alloc, args2_alloc * 2);
707 args2_alloc *= 2;
708 }
709 args2[args2_len++] = item;
710 }
711 }
712
713 // The size of the args2 array now is the number of positional args.
714 uint pos_args_len = args2_len;
715
716 // Copy the fixed kw args.
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300717 mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100718 args2_len += 2 * n_kw;
719
720 // Extract (key,value) pairs from kw_dict dictionary and append to args2.
721 // Note that it can be arbitrary iterator.
722 if (kw_dict == MP_OBJ_NULL) {
723 // pass
724 } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
725 // dictionary
726 mp_map_t *map = mp_obj_dict_get_map(kw_dict);
727 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 +0000728 for (mp_uint_t i = 0; i < map->alloc; i++) {
729 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Damien George230fec72014-03-30 21:21:24 +0100730 args2[args2_len++] = map->table[i].key;
731 args2[args2_len++] = map->table[i].value;
732 }
733 }
734 } else {
735 // generic mapping
736 // TODO is calling 'items' on the mapping the correct thing to do here?
737 mp_obj_t dest[2];
738 mp_load_method(kw_dict, MP_QSTR_items, dest);
739 mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest));
740 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100741 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100742 if (args2_len + 1 >= args2_alloc) {
743 uint new_alloc = args2_alloc * 2;
744 if (new_alloc < 4) {
745 new_alloc = 4;
746 }
747 args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
748 args2_alloc = new_alloc;
749 }
750 mp_obj_t *items;
751 mp_obj_get_array_fixed_n(item, 2, &items);
752 args2[args2_len++] = items[0];
753 args2[args2_len++] = items[1];
754 }
755 }
756
757 mp_obj_t res = mp_call_function_n_kw(fun, pos_args_len, (args2_len - pos_args_len) / 2, args2);
758 m_del(mp_obj_t, args2, args2_alloc);
759
760 return res;
761}
762
Damien George932bf1c2014-01-18 23:42:49 +0000763// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100764void mp_unpack_sequence(mp_obj_t seq_in, mp_uint_t num, mp_obj_t *items) {
Damien George9c4cbe22014-08-30 14:04:14 +0100765 mp_uint_t seq_len;
Damien George3e1a5c12014-03-29 13:43:38 +0000766 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 +0000767 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000768 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000769 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
770 } else {
771 mp_obj_list_get(seq_in, &seq_len, &seq_items);
Damien86c7fc72013-11-26 15:16:41 +0000772 }
Damiend99b0522013-12-21 18:17:45 +0000773 if (seq_len < num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200774 goto too_short;
Damiend99b0522013-12-21 18:17:45 +0000775 } else if (seq_len > num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200776 goto too_long;
Damiend99b0522013-12-21 18:17:45 +0000777 }
Damien George4abff752014-08-30 14:59:21 +0100778 for (mp_uint_t i = 0; i < num; i++) {
Damien George932bf1c2014-01-18 23:42:49 +0000779 items[i] = seq_items[num - 1 - i];
780 }
Damien86c7fc72013-11-26 15:16:41 +0000781 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100782 mp_obj_t iterable = mp_getiter(seq_in);
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200783
784 for (seq_len = 0; seq_len < num; seq_len++) {
Damien Georged17926d2014-03-30 13:35:08 +0100785 mp_obj_t el = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100786 if (el == MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200787 goto too_short;
788 }
789 items[num - 1 - seq_len] = el;
790 }
Damien Georgeea8d06c2014-04-17 23:19:36 +0100791 if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200792 goto too_long;
793 }
Damien86c7fc72013-11-26 15:16:41 +0000794 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200795 return;
796
797too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000798 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
799 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
800 "wrong number of values to unpack"));
801 } else {
802 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
803 "need more than %d values to unpack", seq_len));
804 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200805too_long:
Damien George1e9a92f2014-11-06 17:36:16 +0000806 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
807 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
808 "wrong number of values to unpack"));
809 } else {
810 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
811 "too many values to unpack (expected %d)", num));
812 }
Damien86c7fc72013-11-26 15:16:41 +0000813}
814
Damien George495d7812014-04-08 17:51:47 +0100815// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100816void mp_unpack_ex(mp_obj_t seq_in, mp_uint_t num_in, mp_obj_t *items) {
817 mp_uint_t num_left = num_in & 0xff;
818 mp_uint_t num_right = (num_in >> 8) & 0xff;
Damien Georgeeaaebf32014-09-23 10:59:05 +0100819 DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
Damien George9c4cbe22014-08-30 14:04:14 +0100820 mp_uint_t seq_len;
Damien George495d7812014-04-08 17:51:47 +0100821 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
822 mp_obj_t *seq_items;
823 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
824 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
825 } else {
826 if (num_left == 0 && num_right == 0) {
827 // *a, = b # sets a to b if b is a list
828 items[0] = seq_in;
829 return;
830 }
831 mp_obj_list_get(seq_in, &seq_len, &seq_items);
832 }
833 if (seq_len < num_left + num_right) {
834 goto too_short;
835 }
Damien George4abff752014-08-30 14:59:21 +0100836 for (mp_uint_t i = 0; i < num_right; i++) {
Damien George495d7812014-04-08 17:51:47 +0100837 items[i] = seq_items[seq_len - 1 - i];
838 }
839 items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
Damien George4abff752014-08-30 14:59:21 +0100840 for (mp_uint_t i = 0; i < num_left; i++) {
Damien George495d7812014-04-08 17:51:47 +0100841 items[num_right + 1 + i] = seq_items[num_left - 1 - i];
842 }
843 } else {
844 // Generic iterable; this gets a bit messy: we unpack known left length to the
845 // items destination array, then the rest to a dynamically created list. Once the
846 // iterable is exhausted, we take from this list for the right part of the items.
847 // TODO Improve to waste less memory in the dynamically created list.
848 mp_obj_t iterable = mp_getiter(seq_in);
849 mp_obj_t item;
850 for (seq_len = 0; seq_len < num_left; seq_len++) {
851 item = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100852 if (item == MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100853 goto too_short;
854 }
855 items[num_left + num_right + 1 - 1 - seq_len] = item;
856 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100857 mp_obj_list_t *rest = mp_obj_new_list(0, NULL);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100858 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100859 mp_obj_list_append(rest, item);
860 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100861 if (rest->len < num_right) {
Damien George495d7812014-04-08 17:51:47 +0100862 goto too_short;
863 }
864 items[num_right] = rest;
Damien George4abff752014-08-30 14:59:21 +0100865 for (mp_uint_t i = 0; i < num_right; i++) {
Damien Georgeca6d75f2014-08-30 15:17:47 +0100866 items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
Damien George495d7812014-04-08 17:51:47 +0100867 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100868 mp_obj_list_set_len(rest, rest->len - num_right);
Damien George495d7812014-04-08 17:51:47 +0100869 }
870 return;
871
872too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000873 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
874 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
875 "wrong number of values to unpack"));
876 } else {
877 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
878 "need more than %d values to unpack", seq_len));
879 }
Damien George495d7812014-04-08 17:51:47 +0100880}
881
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300882mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
Damien George062478e2014-01-09 20:57:50 +0000883 DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300884 // use load_method
Damien George062478e2014-01-09 20:57:50 +0000885 mp_obj_t dest[2];
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300886 mp_load_method(base, attr, dest);
887 if (dest[1] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000888 // load_method returned just a normal attribute
Damien George20006db2014-01-18 14:10:48 +0000889 return dest[0];
Damien George062478e2014-01-09 20:57:50 +0000890 } else {
891 // load_method returned a method, so build a bound method object
892 return mp_obj_new_bound_meth(dest[0], dest[1]);
Damiend99b0522013-12-21 18:17:45 +0000893 }
Damiend99b0522013-12-21 18:17:45 +0000894}
895
Damien George7c9c6672014-01-25 00:17:36 +0000896// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
897// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
898// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
Damien Georgee44d26a2014-03-31 22:57:56 +0100899void mp_load_method_maybe(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George062478e2014-01-09 20:57:50 +0000900 // clear output to indicate no attribute/method found yet
901 dest[0] = MP_OBJ_NULL;
902 dest[1] = MP_OBJ_NULL;
903
904 // get the type
905 mp_obj_type_t *type = mp_obj_get_type(base);
906
Damien Georgee44d26a2014-03-31 22:57:56 +0100907 // look for built-in names
908 if (0) {
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300909#if MICROPY_CPYTHON_COMPAT
Damien Georgee44d26a2014-03-31 22:57:56 +0100910 } else if (attr == MP_QSTR___class__) {
911 // a.__class__ is equivalent to type(a)
912 dest[0] = type;
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300913#endif
Damien Georgee44d26a2014-03-31 22:57:56 +0100914
915 } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
916 dest[0] = (mp_obj_t)&mp_builtin_next_obj;
917 dest[1] = base;
918
919 } else if (type->load_attr != NULL) {
920 // this type can do its own load, so call it
921 type->load_attr(base, attr, dest);
922
923 } else if (type->locals_dict != NULL) {
924 // generic method lookup
925 // this is a lookup in the object (ie not class or type)
926 assert(MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)); // Micro Python restriction, for now
927 mp_map_t *locals_map = mp_obj_dict_get_map(type->locals_dict);
928 mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
929 if (elem != NULL) {
930 // check if the methods are functions, static or class methods
Chris Angelicodaf973a2014-06-06 03:51:03 +1000931 // see http://docs.python.org/3/howto/descriptor.html
Damien Georgee44d26a2014-03-31 22:57:56 +0100932 if (MP_OBJ_IS_TYPE(elem->value, &mp_type_staticmethod)) {
933 // return just the function
934 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
935 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_classmethod)) {
936 // return a bound method, with self being the type of this object
937 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
938 dest[1] = mp_obj_get_type(base);
Paul Sokolovsky9511f602014-05-11 03:12:36 +0300939 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_type)) {
940 // Don't try to bind types
941 dest[0] = elem->value;
Damien Georgee44d26a2014-03-31 22:57:56 +0100942 } else if (mp_obj_is_callable(elem->value)) {
943 // return a bound method, with self being this object
944 dest[0] = elem->value;
945 dest[1] = base;
946 } else {
947 // class member is a value, so just return that value
948 dest[0] = elem->value;
Damiend57eba52013-11-02 23:58:14 +0000949 }
950 }
Damiena3977762013-10-09 23:10:10 +0100951 }
Damien George7c9c6672014-01-25 00:17:36 +0000952}
Damiena3977762013-10-09 23:10:10 +0100953
Damien Georged17926d2014-03-30 13:35:08 +0100954void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George7c9c6672014-01-25 00:17:36 +0000955 DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
956
Damien Georged17926d2014-03-30 13:35:08 +0100957 mp_load_method_maybe(base, attr, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000958
959 if (dest[0] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000960 // no attribute/method called attr
Damien George1e9a92f2014-11-06 17:36:16 +0000961 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
962 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
963 "no such attribute"));
Damien George062478e2014-01-09 20:57:50 +0000964 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000965 // following CPython, we give a more detailed error message for type objects
966 if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
967 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
968 "type object '%s' has no attribute '%s'",
969 qstr_str(((mp_obj_type_t*)base)->name), qstr_str(attr)));
970 } else {
971 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
972 "'%s' object has no attribute '%s'",
973 mp_obj_get_type_str(base), qstr_str(attr)));
974 }
Damien George062478e2014-01-09 20:57:50 +0000975 }
976 }
Damiena3977762013-10-09 23:10:10 +0100977}
978
Damien Georged17926d2014-03-30 13:35:08 +0100979void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien5ac1b2e2013-10-18 19:58:12 +0100980 DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
Damien George062478e2014-01-09 20:57:50 +0000981 mp_obj_type_t *type = mp_obj_get_type(base);
982 if (type->store_attr != NULL) {
983 if (type->store_attr(base, attr, value)) {
984 return;
985 }
Damiena3977762013-10-09 23:10:10 +0100986 }
Damien George1e9a92f2014-11-06 17:36:16 +0000987 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
988 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
989 "no such attribute"));
990 } else {
991 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
992 "'%s' object has no attribute '%s'",
993 mp_obj_get_type_str(base), qstr_str(attr)));
994 }
Damiena3977762013-10-09 23:10:10 +0100995}
996
Damien Georged17926d2014-03-30 13:35:08 +0100997mp_obj_t mp_getiter(mp_obj_t o_in) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300998 assert(o_in);
Damien George5fa93b62014-01-22 14:35:10 +0000999 mp_obj_type_t *type = mp_obj_get_type(o_in);
1000 if (type->getiter != NULL) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001001 mp_obj_t iter = type->getiter(o_in);
1002 if (iter == MP_OBJ_NULL) {
1003 goto not_iterable;
1004 }
1005 return iter;
Damience89a212013-10-15 22:25:17 +01001006 } else {
Damien George9e6e9352014-03-26 18:37:06 +00001007 // check for __iter__ method
Damien George7c9c6672014-01-25 00:17:36 +00001008 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001009 mp_load_method_maybe(o_in, MP_QSTR___iter__, dest);
Damien George7c9c6672014-01-25 00:17:36 +00001010 if (dest[0] != MP_OBJ_NULL) {
Damien George9e6e9352014-03-26 18:37:06 +00001011 // __iter__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +01001012 return mp_call_method_n_kw(0, 0, dest);
Damien George7c9c6672014-01-25 00:17:36 +00001013 } else {
Damien Georged17926d2014-03-30 13:35:08 +01001014 mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001015 if (dest[0] != MP_OBJ_NULL) {
1016 // __getitem__ exists, create an iterator
1017 return mp_obj_new_getitem_iter(dest);
1018 } else {
1019 // object not iterable
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001020not_iterable:
Damien George1e9a92f2014-11-06 17:36:16 +00001021 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1022 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1023 "object not iterable"));
1024 } else {
1025 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1026 "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
1027 }
Damien George9e6e9352014-03-26 18:37:06 +00001028 }
Damien George7c9c6672014-01-25 00:17:36 +00001029 }
Damience89a212013-10-15 22:25:17 +01001030 }
1031}
1032
Damien Georgeea8d06c2014-04-17 23:19:36 +01001033// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
Damien George66eaf842014-03-26 19:27:58 +00001034// may also raise StopIteration()
Damien Georged17926d2014-03-30 13:35:08 +01001035mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001036 mp_obj_type_t *type = mp_obj_get_type(o_in);
1037 if (type->iternext != NULL) {
1038 return type->iternext(o_in);
Damience89a212013-10-15 22:25:17 +01001039 } else {
Damien George9e6e9352014-03-26 18:37:06 +00001040 // 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 George9e6e9352014-03-26 18:37:06 +00001043 if (dest[0] != MP_OBJ_NULL) {
1044 // __next__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +01001045 return mp_call_method_n_kw(0, 0, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001046 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001047 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1048 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1049 "object not an iterator"));
1050 } else {
1051 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1052 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1053 }
Damien George9e6e9352014-03-26 18:37:06 +00001054 }
Damien Georgec5966122014-02-15 16:10:44 +00001055 }
1056}
1057
Damien Georgeea8d06c2014-04-17 23:19:36 +01001058// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
Damien George66eaf842014-03-26 19:27:58 +00001059// may raise other exceptions
Damien Georged17926d2014-03-30 13:35:08 +01001060mp_obj_t mp_iternext(mp_obj_t o_in) {
Damien George66eaf842014-03-26 19:27:58 +00001061 mp_obj_type_t *type = mp_obj_get_type(o_in);
1062 if (type->iternext != NULL) {
1063 return type->iternext(o_in);
1064 } else {
1065 // check for __next__ method
1066 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001067 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George66eaf842014-03-26 19:27:58 +00001068 if (dest[0] != MP_OBJ_NULL) {
1069 // __next__ exists, call it and return its result
1070 nlr_buf_t nlr;
1071 if (nlr_push(&nlr) == 0) {
Damien Georged17926d2014-03-30 13:35:08 +01001072 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
Damien George66eaf842014-03-26 19:27:58 +00001073 nlr_pop();
1074 return ret;
1075 } else {
1076 if (mp_obj_is_subclass_fast(mp_obj_get_type(nlr.ret_val), &mp_type_StopIteration)) {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001077 return MP_OBJ_STOP_ITERATION;
Damien George66eaf842014-03-26 19:27:58 +00001078 } else {
Damien Georgeea13f402014-04-05 18:32:08 +01001079 nlr_raise(nlr.ret_val);
Damien George66eaf842014-03-26 19:27:58 +00001080 }
1081 }
1082 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001083 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1084 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1085 "object not an iterator"));
1086 } else {
1087 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1088 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1089 }
Damien George66eaf842014-03-26 19:27:58 +00001090 }
1091 }
1092}
1093
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001094// TODO: Unclear what to do with StopIterarion exception here.
1095mp_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 +03001096 assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001097 mp_obj_type_t *type = mp_obj_get_type(self_in);
1098
1099 if (type == &mp_type_gen_instance) {
1100 return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
1101 }
1102
1103 if (type->iternext != NULL && send_value == mp_const_none) {
1104 mp_obj_t ret = type->iternext(self_in);
1105 if (ret != MP_OBJ_NULL) {
1106 *ret_val = ret;
1107 return MP_VM_RETURN_YIELD;
1108 } else {
1109 // Emulate raise StopIteration()
1110 // Special case, handled in vm.c
1111 *ret_val = MP_OBJ_NULL;
1112 return MP_VM_RETURN_NORMAL;
1113 }
1114 }
1115
1116 mp_obj_t dest[3]; // Reserve slot for send() arg
1117
1118 if (send_value == mp_const_none) {
1119 mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1120 if (dest[0] != MP_OBJ_NULL) {
1121 *ret_val = mp_call_method_n_kw(0, 0, dest);
1122 return MP_VM_RETURN_YIELD;
1123 }
1124 }
1125
1126 if (send_value != MP_OBJ_NULL) {
1127 mp_load_method(self_in, MP_QSTR_send, dest);
1128 dest[2] = send_value;
1129 *ret_val = mp_call_method_n_kw(1, 0, dest);
1130 return MP_VM_RETURN_YIELD;
1131 }
1132
1133 if (throw_value != MP_OBJ_NULL) {
1134 if (mp_obj_is_subclass_fast(mp_obj_get_type(throw_value), &mp_type_GeneratorExit)) {
1135 mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1136 if (dest[0] != MP_OBJ_NULL) {
1137 *ret_val = mp_call_method_n_kw(0, 0, dest);
1138 // We assume one can't "yield" from close()
1139 return MP_VM_RETURN_NORMAL;
1140 }
1141 }
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001142 mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1143 if (dest[0] != MP_OBJ_NULL) {
1144 *ret_val = mp_call_method_n_kw(1, 0, &throw_value);
1145 // If .throw() method returned, we assume it's value to yield
Damien Georgeea13f402014-04-05 18:32:08 +01001146 // - any exception would be thrown with nlr_raise().
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001147 return MP_VM_RETURN_YIELD;
1148 }
1149 // If there's nowhere to throw exception into, then we assume that object
1150 // is just incapable to handle it, so any exception thrown into it
1151 // will be propagated up. This behavior is approved by test_pep380.py
1152 // test_delegation_of_close_to_non_generator(),
1153 // test_delegating_throw_to_non_generator()
1154 *ret_val = throw_value;
1155 return MP_VM_RETURN_EXCEPTION;
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001156 }
1157
1158 assert(0);
1159 return MP_VM_RETURN_NORMAL; // Should be unreachable
1160}
1161
Damien Georged17926d2014-03-30 13:35:08 +01001162mp_obj_t mp_make_raise_obj(mp_obj_t o) {
Damien Georgec5966122014-02-15 16:10:44 +00001163 DEBUG_printf("raise %p\n", o);
1164 if (mp_obj_is_exception_type(o)) {
1165 // o is an exception type (it is derived from BaseException (or is BaseException))
1166 // create and return a new exception instance by calling o
Damien George22a08652014-02-15 21:05:25 +00001167 // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1168 // could have const instances in ROM which we return here instead
Damien Georged17926d2014-03-30 13:35:08 +01001169 return mp_call_function_n_kw(o, 0, 0, NULL);
Damien Georgec5966122014-02-15 16:10:44 +00001170 } else if (mp_obj_is_exception_instance(o)) {
1171 // o is an instance of an exception, so use it as the exception
1172 return o;
1173 } else {
1174 // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1175 return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
Damience89a212013-10-15 22:25:17 +01001176 }
1177}
1178
Damien Georged17926d2014-03-30 13:35:08 +01001179mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
Damien George64131f32014-02-06 20:31:44 +00001180 DEBUG_printf("import name %s\n", qstr_str(name));
1181
Damiendb4c3612013-12-10 17:27:24 +00001182 // build args array
Damiend99b0522013-12-21 18:17:45 +00001183 mp_obj_t args[5];
Damien George5fa93b62014-01-22 14:35:10 +00001184 args[0] = MP_OBJ_NEW_QSTR(name);
Damiend99b0522013-12-21 18:17:45 +00001185 args[1] = mp_const_none; // TODO should be globals
1186 args[2] = mp_const_none; // TODO should be locals
Damiendb4c3612013-12-10 17:27:24 +00001187 args[3] = fromlist;
1188 args[4] = level; // must be 0; we don't yet support other values
1189
1190 // TODO lookup __import__ and call that instead of going straight to builtin implementation
Damiend99b0522013-12-21 18:17:45 +00001191 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001192}
1193
Damien Georged17926d2014-03-30 13:35:08 +01001194mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
Damien George64131f32014-02-06 20:31:44 +00001195 DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1196
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001197 mp_obj_t dest[2];
1198
1199 mp_load_method_maybe(module, name, dest);
1200
1201 if (dest[1] != MP_OBJ_NULL) {
1202 // Hopefully we can't import bound method from an object
1203import_error:
Paul Sokolovsky42453dc2014-04-12 03:00:40 +03001204 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %s", qstr_str(name)));
Damiendb4c3612013-12-10 17:27:24 +00001205 }
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001206
1207 if (dest[0] != MP_OBJ_NULL) {
1208 return dest[0];
1209 }
1210
1211 // See if it's a package, then can try FS import
Paul Sokolovskye5a37592014-10-25 21:04:13 +03001212 if (!mp_obj_is_package(module)) {
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001213 goto import_error;
1214 }
1215
1216 mp_load_method_maybe(module, MP_QSTR___name__, dest);
Damien Georged182b982014-08-30 14:19:41 +01001217 mp_uint_t pkg_name_len;
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001218 const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1219
stijn01d6be42014-05-05 12:18:27 +02001220 const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1221 char *dot_name = alloca(dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001222 memcpy(dot_name, pkg_name, pkg_name_len);
1223 dot_name[pkg_name_len] = '.';
1224 memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
stijn01d6be42014-05-05 12:18:27 +02001225 qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001226
1227 mp_obj_t args[5];
1228 args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
1229 args[1] = mp_const_none; // TODO should be globals
1230 args[2] = mp_const_none; // TODO should be locals
1231 args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
Paul Sokolovsky69f18672014-04-12 02:47:46 +03001232 args[4] = MP_OBJ_NEW_SMALL_INT(0);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001233
1234 // TODO lookup __import__ and call that instead of going straight to builtin implementation
1235 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001236}
1237
Damien Georged17926d2014-03-30 13:35:08 +01001238void mp_import_all(mp_obj_t module) {
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001239 DEBUG_printf("import all %p\n", module);
1240
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001241 // TODO: Support __all__
Damien George8b0535e2014-04-05 21:53:54 +01001242 mp_map_t *map = mp_obj_dict_get_map(mp_obj_module_get_globals(module));
Damien Georgeb063b9b2014-12-21 16:24:09 +00001243 for (mp_uint_t i = 0; i < map->alloc; i++) {
Damien George8b0535e2014-04-05 21:53:54 +01001244 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001245 qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
1246 if (*qstr_str(name) != '_') {
1247 mp_store_name(name, map->table[i].value);
1248 }
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001249 }
1250 }
1251}
1252
Damien George7efc5b32014-04-05 22:36:42 +01001253mp_obj_dict_t *mp_locals_get(void) {
1254 return dict_locals;
Damien George66028ab2014-01-03 14:03:48 +00001255}
1256
Damien George7efc5b32014-04-05 22:36:42 +01001257void mp_locals_set(mp_obj_dict_t *d) {
1258 DEBUG_OP_printf("mp_locals_set(%p)\n", d);
1259 dict_locals = d;
Damien George66028ab2014-01-03 14:03:48 +00001260}
1261
Damien George7efc5b32014-04-05 22:36:42 +01001262mp_obj_dict_t *mp_globals_get(void) {
1263 return dict_globals;
Damien George66028ab2014-01-03 14:03:48 +00001264}
1265
Damien George7efc5b32014-04-05 22:36:42 +01001266void mp_globals_set(mp_obj_dict_t *d) {
1267 DEBUG_OP_printf("mp_globals_set(%p)\n", d);
1268 dict_globals = d;
Damien George66028ab2014-01-03 14:03:48 +00001269}
1270
Damien Georgec4d08682014-10-05 20:13:34 +01001271// this is implemented in this file so it can optimise access to locals/globals
1272mp_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) {
1273 // parse the string
1274 mp_parse_error_kind_t parse_error_kind;
1275 mp_parse_node_t pn = mp_parse(lex, parse_input_kind, &parse_error_kind);
1276
1277 if (pn == MP_PARSE_NODE_NULL) {
1278 // parse error; raise exception
1279 mp_obj_t exc = mp_parse_make_exception(lex, parse_error_kind);
1280 mp_lexer_free(lex);
1281 nlr_raise(exc);
1282 }
1283
Damien Georgea4c52c52014-12-05 19:35:18 +00001284 qstr source_name = lex->source_name;
Damien Georgec4d08682014-10-05 20:13:34 +01001285 mp_lexer_free(lex);
1286
1287 // save context and set new context
1288 mp_obj_dict_t *old_globals = mp_globals_get();
1289 mp_obj_dict_t *old_locals = mp_locals_get();
1290 mp_globals_set(globals);
1291 mp_locals_set(locals);
1292
1293 // compile the string
1294 mp_obj_t module_fun = mp_compile(pn, source_name, MP_EMIT_OPT_NONE, false);
1295
1296 // check if there was a compile error
1297 if (mp_obj_is_exception_instance(module_fun)) {
1298 mp_globals_set(old_globals);
1299 mp_locals_set(old_locals);
1300 nlr_raise(module_fun);
1301 }
1302
Damien Georgec9fc6202014-10-25 21:59:14 +01001303 // for compile only
1304 if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
1305 mp_globals_set(old_globals);
1306 mp_locals_set(old_locals);
1307 return module_fun;
1308 }
1309
Damien Georgec4d08682014-10-05 20:13:34 +01001310 // complied successfully, execute it
1311 nlr_buf_t nlr;
1312 if (nlr_push(&nlr) == 0) {
1313 mp_obj_t ret = mp_call_function_0(module_fun);
1314 nlr_pop();
1315 mp_globals_set(old_globals);
1316 mp_locals_set(old_locals);
1317 return ret;
1318 } else {
1319 // exception; restore context and re-raise same exception
1320 mp_globals_set(old_globals);
1321 mp_locals_set(old_locals);
1322 nlr_raise(nlr.ret_val);
1323 }
1324}
1325
Damien Georgeb0261342014-09-23 18:10:17 +01001326void *m_malloc_fail(size_t num_bytes) {
1327 DEBUG_printf("memory allocation failed, allocating " UINT_FMT " bytes\n", num_bytes);
Damien George40914452014-10-09 16:44:43 +01001328 if (0) {
1329 // dummy
1330 #if MICROPY_ENABLE_GC
1331 } else if (gc_is_locked()) {
1332 nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001333 "memory allocation failed, heap is locked"));
Damien George40914452014-10-09 16:44:43 +01001334 #endif
Dave Hylands3556e452014-10-07 00:50:20 -07001335 } else {
Damien George40914452014-10-09 16:44:43 +01001336 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001337 "memory allocation failed, allocating " UINT_FMT " bytes", num_bytes));
1338 }
Damien George6902eed2014-04-04 10:52:59 +00001339}
1340
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001341NORETURN void mp_not_implemented(const char *msg) {
1342 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, msg));
1343}