blob: 6efab0480c6cb6e7cc4be1421d85fe39c91a6827 [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 Georgecaac5422014-03-25 14:18:18 +000045#include "builtintables.h"
Damien George5fa93b62014-01-22 14:35:10 +000046#include "bc.h"
Damien Georgeecf5b772014-04-04 11:13:51 +000047#include "smallint.h"
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +030048#include "objgenerator.h"
Paul Sokolovskyd3439d02014-06-02 19:37:55 +030049#include "lexer.h"
Damien Georgec4d08682014-10-05 20:13:34 +010050#include "parse.h"
51#include "parsehelper.h"
52#include "compile.h"
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030053#include "stackctrl.h"
Dave Hylands3556e452014-10-07 00:50:20 -070054#include "gc.h"
Damien660365e2013-12-17 18:27:24 +000055
Damien7f5dacf2013-10-10 11:24:39 +010056#if 0 // print debugging info
Damiena1ddfcc2013-10-10 23:25:50 +010057#define DEBUG_PRINT (1)
Paul Sokolovsky44739e22014-02-16 18:11:42 +020058#define DEBUG_printf DEBUG_printf
Damien George41eb6082014-02-26 22:40:35 +000059#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
Damien7f5dacf2013-10-10 11:24:39 +010060#else // don't print debugging info
Damien George41eb6082014-02-26 22:40:35 +000061#define DEBUG_printf(...) (void)0
62#define DEBUG_OP_printf(...) (void)0
Damien7f5dacf2013-10-10 11:24:39 +010063#endif
Damien429d7192013-10-04 19:53:11 +010064
Damieneb19efb2013-10-10 22:06:54 +010065// locals and globals need to be pointers because they can be the same in outer module scope
Damien George7efc5b32014-04-05 22:36:42 +010066STATIC mp_obj_dict_t *dict_locals;
67STATIC mp_obj_dict_t *dict_globals;
Damienbd254452013-10-16 20:39:12 +010068
Damien George7efc5b32014-04-05 22:36:42 +010069// dictionary for the __main__ module
Damien George8b0535e2014-04-05 21:53:54 +010070STATIC mp_obj_dict_t dict_main;
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030071
72const mp_obj_module_t mp_module___main__ = {
73 .base = { &mp_type_module },
74 .name = MP_QSTR___main__,
Damien George8b0535e2014-04-05 21:53:54 +010075 .globals = (mp_obj_dict_t*)&dict_main,
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030076};
77
Damien Georged17926d2014-03-30 13:35:08 +010078void mp_init(void) {
Damien George8dbbbbc2014-08-04 10:05:16 +010079 qstr_init();
Paul Sokolovskycaa73342014-07-01 02:13:42 +030080 mp_stack_ctrl_init();
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030081
Damien George8dbbbbc2014-08-04 10:05:16 +010082#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
83 mp_init_emergency_exception_buf();
84#endif
85
Damien George97f9a282014-05-12 23:07:34 +010086 // call port specific initialization if any
stijn72521a12014-05-03 11:28:29 +020087#ifdef MICROPY_PORT_INIT_FUNC
88 MICROPY_PORT_INIT_FUNC;
89#endif
90
Paul Sokolovskyd3439d02014-06-02 19:37:55 +030091 // optimization disabled by default
92 mp_optimise_value = 0;
Damien George97f9a282014-05-12 23:07:34 +010093
Damien Georgecaac5422014-03-25 14:18:18 +000094 // init global module stuff
95 mp_module_init();
Damien George0d028742014-01-22 23:59:20 +000096
Damien George7efc5b32014-04-05 22:36:42 +010097 // initialise the __main__ module
Damien George8b0535e2014-04-05 21:53:54 +010098 mp_obj_dict_init(&dict_main, 1);
Damien George8b0535e2014-04-05 21:53:54 +010099 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 +0300100
101 // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
Damien George7efc5b32014-04-05 22:36:42 +0100102 dict_locals = dict_globals = &dict_main;
Damien429d7192013-10-04 19:53:11 +0100103}
104
Damien Georged17926d2014-03-30 13:35:08 +0100105void mp_deinit(void) {
Damien George7efc5b32014-04-05 22:36:42 +0100106 //mp_obj_dict_free(&dict_main);
Damien George2326d522014-03-27 23:26:35 +0000107 mp_module_deinit();
stijn5ed284a2014-05-08 10:56:33 +0200108
109 // call port specific deinitialization if any
110#ifdef MICROPY_PORT_INIT_FUNC
111 MICROPY_PORT_DEINIT_FUNC;
112#endif
Damien429d7192013-10-04 19:53:11 +0100113}
114
Damien George503d6112014-05-28 14:07:21 +0100115mp_obj_t mp_load_const_int(qstr qstr) {
116 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100117 mp_uint_t len;
Damien George503d6112014-05-28 14:07:21 +0100118 const byte* data = qstr_data(qstr, &len);
119 return mp_parse_num_integer((const char*)data, len, 0);
120}
121
Damien Georged17926d2014-03-30 13:35:08 +0100122mp_obj_t mp_load_const_dec(qstr qstr) {
Damien7410e442013-11-02 19:47:57 +0000123 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100124 mp_uint_t len;
Damien George20773972014-02-22 18:12:43 +0000125 const byte* data = qstr_data(qstr, &len);
Damien George6e48f7f2014-03-21 11:45:46 +0000126 return mp_parse_num_decimal((const char*)data, len, true, false);
Damien7410e442013-11-02 19:47:57 +0000127}
128
Damien Georged17926d2014-03-30 13:35:08 +0100129mp_obj_t mp_load_const_str(qstr qstr) {
Damien429d7192013-10-04 19:53:11 +0100130 DEBUG_OP_printf("load '%s'\n", qstr_str(qstr));
Damien George5fa93b62014-01-22 14:35:10 +0000131 return MP_OBJ_NEW_QSTR(qstr);
Damien429d7192013-10-04 19:53:11 +0100132}
133
Damien Georged17926d2014-03-30 13:35:08 +0100134mp_obj_t mp_load_const_bytes(qstr qstr) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200135 DEBUG_OP_printf("load b'%s'\n", qstr_str(qstr));
Damien George39dc1452014-10-03 19:52:22 +0100136 mp_uint_t len;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200137 const byte *data = qstr_data(qstr, &len);
138 return mp_obj_new_bytes(data, len);
139}
140
Damien Georged17926d2014-03-30 13:35:08 +0100141mp_obj_t mp_load_name(qstr qstr) {
Damien429d7192013-10-04 19:53:11 +0100142 // logic: search locals, globals, builtins
Damien George7efc5b32014-04-05 22:36:42 +0100143 DEBUG_OP_printf("load name %s\n", qstr_str(qstr));
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300144 // If we're at the outer scope (locals == globals), dispatch to load_global right away
Damien George7efc5b32014-04-05 22:36:42 +0100145 if (dict_locals != dict_globals) {
146 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 +0300147 if (elem != NULL) {
148 return elem->value;
149 }
Damiena3977762013-10-09 23:10:10 +0100150 }
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300151 return mp_load_global(qstr);
Damiena3977762013-10-09 23:10:10 +0100152}
153
Damien Georged17926d2014-03-30 13:35:08 +0100154mp_obj_t mp_load_global(qstr qstr) {
Damiena3977762013-10-09 23:10:10 +0100155 // logic: search globals, builtins
156 DEBUG_OP_printf("load global %s\n", qstr_str(qstr));
Damien George7efc5b32014-04-05 22:36:42 +0100157 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 +0100158 if (elem == NULL) {
Damien George7efc5b32014-04-05 22:36:42 +0100159 // TODO lookup in dynamic table of builtins first
160 elem = mp_map_lookup((mp_map_t*)&mp_builtin_object_dict_obj.map, MP_OBJ_NEW_QSTR(qstr), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100161 if (elem == NULL) {
Damien Georgeea13f402014-04-05 18:32:08 +0100162 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError, "name '%s' is not defined", qstr_str(qstr)));
Damien429d7192013-10-04 19:53:11 +0100163 }
164 }
165 return elem->value;
166}
167
Damien Georged17926d2014-03-30 13:35:08 +0100168mp_obj_t mp_load_build_class(void) {
Damien429d7192013-10-04 19:53:11 +0100169 DEBUG_OP_printf("load_build_class\n");
Damien George7efc5b32014-04-05 22:36:42 +0100170 // TODO lookup __build_class__ in dynamic table of builtins first
171 // ... else no user-defined __build_class__, return builtin one
172 return (mp_obj_t)&mp_builtin___build_class___obj;
Damien429d7192013-10-04 19:53:11 +0100173}
174
Damien Georged17926d2014-03-30 13:35:08 +0100175void mp_store_name(qstr qstr, mp_obj_t obj) {
Damiena3977762013-10-09 23:10:10 +0100176 DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qstr), obj);
Damien George7efc5b32014-04-05 22:36:42 +0100177 mp_obj_dict_store(dict_locals, MP_OBJ_NEW_QSTR(qstr), obj);
Damiena3977762013-10-09 23:10:10 +0100178}
179
Damien Georged17926d2014-03-30 13:35:08 +0100180void mp_delete_name(qstr qstr) {
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200181 DEBUG_OP_printf("delete name %s\n", qstr_str(qstr));
Damien George1d24ea52014-04-08 21:11:49 +0100182 // TODO convert KeyError to NameError if qstr not found
183 mp_obj_dict_delete(dict_locals, MP_OBJ_NEW_QSTR(qstr));
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200184}
185
Damien Georged17926d2014-03-30 13:35:08 +0100186void mp_store_global(qstr qstr, mp_obj_t obj) {
Damiena3977762013-10-09 23:10:10 +0100187 DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qstr), obj);
Damien George7efc5b32014-04-05 22:36:42 +0100188 mp_obj_dict_store(dict_globals, MP_OBJ_NEW_QSTR(qstr), obj);
Damien429d7192013-10-04 19:53:11 +0100189}
190
Damien George1d24ea52014-04-08 21:11:49 +0100191void mp_delete_global(qstr qstr) {
192 DEBUG_OP_printf("delete global %s\n", qstr_str(qstr));
193 // TODO convert KeyError to NameError if qstr not found
194 mp_obj_dict_delete(dict_globals, MP_OBJ_NEW_QSTR(qstr));
195}
196
Damien George4abff752014-08-30 14:59:21 +0100197mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100198 DEBUG_OP_printf("unary " UINT_FMT " %p\n", op, arg);
Damien George9aa2a522014-02-01 23:04:09 +0000199
Damiend99b0522013-12-21 18:17:45 +0000200 if (MP_OBJ_IS_SMALL_INT(arg)) {
Damien George40f3c022014-07-03 13:25:24 +0100201 mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
Damien7410e442013-11-02 19:47:57 +0000202 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100203 case MP_UNARY_OP_BOOL:
Damien George9d68e9c2014-03-12 15:38:15 +0000204 return MP_BOOL(val != 0);
Damien Georged17926d2014-03-30 13:35:08 +0100205 case MP_UNARY_OP_POSITIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000206 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100207 case MP_UNARY_OP_NEGATIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000208 // check for overflow
209 if (val == MP_SMALL_INT_MIN) {
210 return mp_obj_new_int(-val);
211 } else {
212 return MP_OBJ_NEW_SMALL_INT(-val);
213 }
Damien Georged17926d2014-03-30 13:35:08 +0100214 case MP_UNARY_OP_INVERT:
Damien George9d68e9c2014-03-12 15:38:15 +0000215 return MP_OBJ_NEW_SMALL_INT(~val);
216 default:
217 assert(0);
218 return arg;
Damien7410e442013-11-02 19:47:57 +0000219 }
Damien George1e708fe2014-01-23 18:27:51 +0000220 } else {
221 mp_obj_type_t *type = mp_obj_get_type(arg);
222 if (type->unary_op != NULL) {
223 mp_obj_t result = type->unary_op(op, arg);
Damien George6ac5dce2014-05-21 19:42:43 +0100224 if (result != MP_OBJ_NULL) {
Damiend99b0522013-12-21 18:17:45 +0000225 return result;
226 }
Damien7410e442013-11-02 19:47:57 +0000227 }
Damiend99b0522013-12-21 18:17:45 +0000228 // TODO specify in error message what the operator is
Damien Georgeea13f402014-04-05 18:32:08 +0100229 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "bad operand type for unary operator: '%s'", mp_obj_get_type_str(arg)));
Damien7410e442013-11-02 19:47:57 +0000230 }
Damien429d7192013-10-04 19:53:11 +0100231}
232
Damien George4abff752014-08-30 14:59:21 +0100233mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100234 DEBUG_OP_printf("binary " UINT_FMT " %p %p\n", op, lhs, rhs);
Damien George14f945c2014-01-03 14:09:31 +0000235
236 // TODO correctly distinguish inplace operators for mutable objects
237 // lookup logic that CPython uses for +=:
238 // check for implemented +=
239 // then check for implemented +
240 // then check for implemented seq.inplace_concat
241 // then check for implemented seq.concat
242 // then fail
243 // note that list does not implement + or +=, so that inplace_concat is reached first for +=
244
Damien George9aa2a522014-02-01 23:04:09 +0000245 // deal with is
Damien Georged17926d2014-03-30 13:35:08 +0100246 if (op == MP_BINARY_OP_IS) {
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200247 return MP_BOOL(lhs == rhs);
248 }
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200249
Damien Georgebcbeea02014-01-11 10:47:22 +0000250 // deal with == and != for all types
Damien Georged17926d2014-03-30 13:35:08 +0100251 if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000252 if (mp_obj_equal(lhs, rhs)) {
Damien Georged17926d2014-03-30 13:35:08 +0100253 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000254 return mp_const_true;
255 } else {
256 return mp_const_false;
257 }
258 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100259 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000260 return mp_const_false;
261 } else {
262 return mp_const_true;
263 }
264 }
265 }
266
267 // deal with exception_match for all types
Damien Georged17926d2014-03-30 13:35:08 +0100268 if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
Damien Georgec5966122014-02-15 16:10:44 +0000269 // rhs must be issubclass(rhs, BaseException)
270 if (mp_obj_is_exception_type(rhs)) {
Damien George4bcd04b2014-09-24 14:05:40 +0100271 if (mp_obj_exception_match(lhs, rhs)) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000272 return mp_const_true;
273 } else {
274 return mp_const_false;
275 }
Damien George4bcd04b2014-09-24 14:05:40 +0100276 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
277 mp_obj_tuple_t *tuple = rhs;
278 for (mp_uint_t i = 0; i < tuple->len; i++) {
279 rhs = tuple->items[i];
280 if (!mp_obj_is_exception_type(rhs)) {
281 goto unsupported_op;
282 }
283 if (mp_obj_exception_match(lhs, rhs)) {
284 return mp_const_true;
285 }
286 }
287 return mp_const_false;
Damien Georgebcbeea02014-01-11 10:47:22 +0000288 }
Damien George4bcd04b2014-09-24 14:05:40 +0100289 goto unsupported_op;
Damien Georgebcbeea02014-01-11 10:47:22 +0000290 }
291
Damien George1a9951d2014-01-06 22:13:00 +0000292 if (MP_OBJ_IS_SMALL_INT(lhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100293 mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
Damien George1a9951d2014-01-06 22:13:00 +0000294 if (MP_OBJ_IS_SMALL_INT(rhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100295 mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
Damien George9d68e9c2014-03-12 15:38:15 +0000296 // This is a binary operation: lhs_val op rhs_val
297 // We need to be careful to handle overflow; see CERT INT32-C
298 // Operations that can overflow:
Damien George40f3c022014-07-03 13:25:24 +0100299 // + result always fits in mp_int_t, then handled by SMALL_INT check
300 // - result always fits in mp_int_t, then handled by SMALL_INT check
Damien George9d68e9c2014-03-12 15:38:15 +0000301 // * checked explicitly
Damien George40f3c022014-07-03 13:25:24 +0100302 // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
303 // % 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 +0000304 // << checked explicitly
Damien George1a9951d2014-01-06 22:13:00 +0000305 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100306 case MP_BINARY_OP_OR:
307 case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
308 case MP_BINARY_OP_XOR:
309 case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
310 case MP_BINARY_OP_AND:
311 case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
312 case MP_BINARY_OP_LSHIFT:
313 case MP_BINARY_OP_INPLACE_LSHIFT: {
Damien George9d68e9c2014-03-12 15:38:15 +0000314 if (rhs_val < 0) {
315 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100316 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000317 } else if (rhs_val >= BITS_PER_WORD || lhs_val > (MP_SMALL_INT_MAX >> rhs_val) || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
318 // left-shift will overflow, so use higher precision integer
319 lhs = mp_obj_new_int_from_ll(lhs_val);
320 goto generic_binary_op;
321 } else {
322 // use standard precision
323 lhs_val <<= rhs_val;
324 }
325 break;
326 }
Damien Georged17926d2014-03-30 13:35:08 +0100327 case MP_BINARY_OP_RSHIFT:
328 case MP_BINARY_OP_INPLACE_RSHIFT:
Damien George9d68e9c2014-03-12 15:38:15 +0000329 if (rhs_val < 0) {
330 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100331 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000332 } else {
333 // standard precision is enough for right-shift
334 lhs_val >>= rhs_val;
335 }
336 break;
Damien Georged17926d2014-03-30 13:35:08 +0100337 case MP_BINARY_OP_ADD:
338 case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
339 case MP_BINARY_OP_SUBTRACT:
340 case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
341 case MP_BINARY_OP_MULTIPLY:
342 case MP_BINARY_OP_INPLACE_MULTIPLY: {
Damien George9d68e9c2014-03-12 15:38:15 +0000343
Damien George40f3c022014-07-03 13:25:24 +0100344 // If long long type exists and is larger than mp_int_t, then
Damien George9d68e9c2014-03-12 15:38:15 +0000345 // we can use the following code to perform overflow-checked multiplication.
Damien Georgeecf5b772014-04-04 11:13:51 +0000346 // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
Damien George9d68e9c2014-03-12 15:38:15 +0000347 #if 0
348 // compute result using long long precision
349 long long res = (long long)lhs_val * (long long)rhs_val;
350 if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
351 // result overflowed SMALL_INT, so return higher precision integer
352 return mp_obj_new_int_from_ll(res);
353 } else {
354 // use standard precision
Damien George40f3c022014-07-03 13:25:24 +0100355 lhs_val = (mp_int_t)res;
Damien George9d68e9c2014-03-12 15:38:15 +0000356 }
357 #endif
358
Damien Georgeecf5b772014-04-04 11:13:51 +0000359 if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
360 // use higher precision
361 lhs = mp_obj_new_int_from_ll(lhs_val);
362 goto generic_binary_op;
363 } else {
364 // use standard precision
365 return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
366 }
Damien George9d68e9c2014-03-12 15:38:15 +0000367 break;
368 }
Damien Georged17926d2014-03-30 13:35:08 +0100369 case MP_BINARY_OP_FLOOR_DIVIDE:
370 case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300371 if (rhs_val == 0) {
372 goto zero_division;
373 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000374 lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
Rachel Dowdall56402792014-03-22 20:19:24 +0000375 break;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300376
Damien Georgefb510b32014-06-01 13:32:54 +0100377 #if MICROPY_PY_BUILTINS_FLOAT
Damien Georged17926d2014-03-30 13:35:08 +0100378 case MP_BINARY_OP_TRUE_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300379 case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
380 if (rhs_val == 0) {
Damien George70f33cd2014-04-02 17:06:05 +0100381 goto zero_division;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300382 }
383 return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000384 #endif
Damiena3dcd9e2013-12-17 21:35:38 +0000385
Damien Georged17926d2014-03-30 13:35:08 +0100386 case MP_BINARY_OP_MODULO:
Damien Georgeecf5b772014-04-04 11:13:51 +0000387 case MP_BINARY_OP_INPLACE_MODULO: {
388 lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
Rachel Dowdallcde86312014-03-22 17:29:27 +0000389 break;
390 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000391
Damien Georged17926d2014-03-30 13:35:08 +0100392 case MP_BINARY_OP_POWER:
393 case MP_BINARY_OP_INPLACE_POWER:
Damien George9d68e9c2014-03-12 15:38:15 +0000394 if (rhs_val < 0) {
Damien Georgefb510b32014-06-01 13:32:54 +0100395 #if MICROPY_PY_BUILTINS_FLOAT
Damien George9d68e9c2014-03-12 15:38:15 +0000396 lhs = mp_obj_new_float(lhs_val);
397 goto generic_binary_op;
398 #else
Damien Georgeea13f402014-04-05 18:32:08 +0100399 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative power with no float support"));
Damien George9d68e9c2014-03-12 15:38:15 +0000400 #endif
401 } else {
Damien George40f3c022014-07-03 13:25:24 +0100402 mp_int_t ans = 1;
Damien George9d68e9c2014-03-12 15:38:15 +0000403 while (rhs_val > 0) {
404 if (rhs_val & 1) {
Damien Georgeecf5b772014-04-04 11:13:51 +0000405 if (mp_small_int_mul_overflow(ans, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100406 goto power_overflow;
407 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000408 ans *= lhs_val;
Damien George9d68e9c2014-03-12 15:38:15 +0000409 }
Damien George5bf565e2014-04-04 00:16:32 +0100410 if (rhs_val == 1) {
411 break;
412 }
Damien George9d68e9c2014-03-12 15:38:15 +0000413 rhs_val /= 2;
Damien Georgeecf5b772014-04-04 11:13:51 +0000414 if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100415 goto power_overflow;
416 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000417 lhs_val *= lhs_val;
Damien George1a9951d2014-01-06 22:13:00 +0000418 }
Damien George9d68e9c2014-03-12 15:38:15 +0000419 lhs_val = ans;
Damiena3dcd9e2013-12-17 21:35:38 +0000420 }
Damien George1a9951d2014-01-06 22:13:00 +0000421 break;
Damien George5bf565e2014-04-04 00:16:32 +0100422
423 power_overflow:
424 // use higher precision
425 lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
426 goto generic_binary_op;
427
Damien Georged17926d2014-03-30 13:35:08 +0100428 case MP_BINARY_OP_LESS: return MP_BOOL(lhs_val < rhs_val); break;
429 case MP_BINARY_OP_MORE: return MP_BOOL(lhs_val > rhs_val); break;
430 case MP_BINARY_OP_LESS_EQUAL: return MP_BOOL(lhs_val <= rhs_val); break;
431 case MP_BINARY_OP_MORE_EQUAL: return MP_BOOL(lhs_val >= rhs_val); break;
Damiena3dcd9e2013-12-17 21:35:38 +0000432
Damien George8bcb9862014-04-17 16:26:50 +0100433 default:
434 goto unsupported_op;
Damien George1a9951d2014-01-06 22:13:00 +0000435 }
Paul Sokolovsky757ac812014-01-12 17:06:25 +0200436 // TODO: We just should make mp_obj_new_int() inline and use that
Damien Georged1e355e2014-05-28 14:51:12 +0100437 if (MP_SMALL_INT_FITS(lhs_val)) {
Damien George1a9951d2014-01-06 22:13:00 +0000438 return MP_OBJ_NEW_SMALL_INT(lhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000439 } else {
440 return mp_obj_new_int(lhs_val);
Damien George1a9951d2014-01-06 22:13:00 +0000441 }
Damien Georgefb510b32014-06-01 13:32:54 +0100442#if MICROPY_PY_BUILTINS_FLOAT
Damien George0c36da02014-03-08 15:24:39 +0000443 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_float)) {
Damien Georgeae491052014-04-10 20:08:11 +0100444 mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
445 if (res == MP_OBJ_NULL) {
446 goto unsupported_op;
447 } else {
448 return res;
449 }
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300450#if MICROPY_PY_BUILTINS_COMPLEX
Damien George0c36da02014-03-08 15:24:39 +0000451 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
Damien Georgeae491052014-04-10 20:08:11 +0100452 mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
453 if (res == MP_OBJ_NULL) {
454 goto unsupported_op;
455 } else {
456 return res;
457 }
Damien George3f759b72014-01-31 00:42:12 +0000458#endif
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300459#endif
Damien429d7192013-10-04 19:53:11 +0100460 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000461 }
John R. Lentonb8698fc2014-01-11 00:58:59 +0000462
Damien George9aa2a522014-02-01 23:04:09 +0000463 /* deal with `in`
John R. Lentonc1bef212014-01-11 12:39:33 +0000464 *
465 * NOTE `a in b` is `b.__contains__(a)`, hence why the generic dispatch
Damien George48697f12014-02-01 23:32:29 +0000466 * needs to go below with swapped arguments
John R. Lentonc1bef212014-01-11 12:39:33 +0000467 */
Damien Georged17926d2014-03-30 13:35:08 +0100468 if (op == MP_BINARY_OP_IN) {
Damien George5fa93b62014-01-22 14:35:10 +0000469 mp_obj_type_t *type = mp_obj_get_type(rhs);
470 if (type->binary_op != NULL) {
471 mp_obj_t res = type->binary_op(op, rhs, lhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100472 if (res != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000473 return res;
474 }
475 }
476 if (type->getiter != NULL) {
477 /* second attempt, walk the iterator */
478 mp_obj_t next = NULL;
Damien Georged17926d2014-03-30 13:35:08 +0100479 mp_obj_t iter = mp_getiter(rhs);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100480 while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
Damien George5fa93b62014-01-22 14:35:10 +0000481 if (mp_obj_equal(next, lhs)) {
Damien George9aa2a522014-02-01 23:04:09 +0000482 return mp_const_true;
John R. Lentonb8698fc2014-01-11 00:58:59 +0000483 }
Damien7410e442013-11-02 19:47:57 +0000484 }
Damien George9aa2a522014-02-01 23:04:09 +0000485 return mp_const_false;
Damien7410e442013-11-02 19:47:57 +0000486 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000487
Damien Georgeea13f402014-04-05 18:32:08 +0100488 nlr_raise(mp_obj_new_exception_msg_varg(
Damien Georgec5966122014-02-15 16:10:44 +0000489 &mp_type_TypeError, "'%s' object is not iterable",
John R. Lentonc1bef212014-01-11 12:39:33 +0000490 mp_obj_get_type_str(rhs)));
491 return mp_const_none;
492 }
493
Damien George5fa93b62014-01-22 14:35:10 +0000494 // generic binary_op supplied by type
Damien George9d68e9c2014-03-12 15:38:15 +0000495 mp_obj_type_t *type;
496generic_binary_op:
497 type = mp_obj_get_type(lhs);
Damien George5fa93b62014-01-22 14:35:10 +0000498 if (type->binary_op != NULL) {
499 mp_obj_t result = type->binary_op(op, lhs, rhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100500 if (result != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000501 return result;
John R. Lentonc1bef212014-01-11 12:39:33 +0000502 }
Damien429d7192013-10-04 19:53:11 +0100503 }
Damiend99b0522013-12-21 18:17:45 +0000504
Damien George5fa93b62014-01-22 14:35:10 +0000505 // TODO implement dispatch for reverse binary ops
506
Damiend99b0522013-12-21 18:17:45 +0000507 // TODO specify in error message what the operator is
Damien Georgeae491052014-04-10 20:08:11 +0100508unsupported_op:
Damien Georgeea13f402014-04-05 18:32:08 +0100509 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
Paul Sokolovskybab5cfb2014-01-10 17:32:22 +0200510 "unsupported operand types for binary operator: '%s', '%s'",
511 mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs)));
John R. Lentonc1bef212014-01-11 12:39:33 +0000512 return mp_const_none;
Damien George70f33cd2014-04-02 17:06:05 +0100513
514zero_division:
Damien Georgeea13f402014-04-05 18:32:08 +0100515 nlr_raise(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero"));
Damien429d7192013-10-04 19:53:11 +0100516}
517
Damien Georged17926d2014-03-30 13:35:08 +0100518mp_obj_t mp_call_function_0(mp_obj_t fun) {
519 return mp_call_function_n_kw(fun, 0, 0, NULL);
Damieneb19efb2013-10-10 22:06:54 +0100520}
521
Damien Georged17926d2014-03-30 13:35:08 +0100522mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
523 return mp_call_function_n_kw(fun, 1, 0, &arg);
Damieneb19efb2013-10-10 22:06:54 +0100524}
525
Damien Georged17926d2014-03-30 13:35:08 +0100526mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
Damiend99b0522013-12-21 18:17:45 +0000527 mp_obj_t args[2];
Damien George20006db2014-01-18 14:10:48 +0000528 args[0] = arg1;
529 args[1] = arg2;
Damien Georged17926d2014-03-30 13:35:08 +0100530 return mp_call_function_n_kw(fun, 2, 0, args);
Damieneb19efb2013-10-10 22:06:54 +0100531}
532
Damien George20006db2014-01-18 14:10:48 +0000533// args contains, eg: arg0 arg1 key0 value0 key1 value1
Damien George4abff752014-08-30 14:59:21 +0100534mp_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 +0000535 // TODO improve this: fun object can specify its type and we parse here the arguments,
536 // passing to the function arrays of fixed and keyword arguments
Damieneb19efb2013-10-10 22:06:54 +0100537
Damien Georgeeaaebf32014-09-23 10:59:05 +0100538 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 +0000539
Damien George8b56beb2014-01-31 23:49:49 +0000540 // get the type
541 mp_obj_type_t *type = mp_obj_get_type(fun_in);
542
543 // do the call
544 if (type->call != NULL) {
Damien George3f522622014-06-03 13:40:16 +0100545 return type->call(fun_in, n_args, n_kw, args);
John R. Lenton9c83ec02014-01-07 23:06:46 +0000546 }
Paul Sokolovsky755565d2014-04-25 21:15:16 +0300547
548 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
Damien86c7fc72013-11-26 15:16:41 +0000549}
550
Damien George20006db2014-01-18 14:10:48 +0000551// 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)
552// if n_args==0 and n_kw==0 then there are only fun and self/NULL
Damien George4abff752014-08-30 14:59:21 +0100553mp_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 +0100554 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 +0000555 int adjust = (args[1] == NULL) ? 0 : 1;
Damien Georged17926d2014-03-30 13:35:08 +0100556 return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
Damien86c7fc72013-11-26 15:16:41 +0000557}
558
Damien George4abff752014-08-30 14:59:21 +0100559mp_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 +0100560 mp_obj_t fun = *args++;
561 mp_obj_t self = MP_OBJ_NULL;
562 if (have_self) {
563 self = *args++; // may be MP_OBJ_NULL
564 }
565 uint n_args = n_args_n_kw & 0xff;
566 uint n_kw = (n_args_n_kw >> 8) & 0xff;
Damien George523b5752014-03-31 11:59:23 +0100567 mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // map be MP_OBJ_NULL
568 mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // map be MP_OBJ_NULL
Damien George230fec72014-03-30 21:21:24 +0100569
570 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);
571
572 // We need to create the following array of objects:
573 // args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
574 // TODO: optimize one day to avoid constructing new arg array? Will be hard.
575
576 // The new args array
577 mp_obj_t *args2;
578 uint args2_alloc;
579 uint args2_len = 0;
580
581 // Try to get a hint for the size of the kw_dict
582 uint kw_dict_len = 0;
583 if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
584 kw_dict_len = mp_obj_dict_len(kw_dict);
585 }
586
587 // Extract the pos_seq sequence to the new args array.
588 // Note that it can be arbitrary iterator.
589 if (pos_seq == MP_OBJ_NULL) {
590 // no sequence
591
592 // allocate memory for the new array of args
593 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
594 args2 = m_new(mp_obj_t, args2_alloc);
595
596 // copy the self
597 if (self != MP_OBJ_NULL) {
598 args2[args2_len++] = self;
599 }
600
601 // copy the fixed pos args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300602 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100603 args2_len += n_args;
604
605 } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
606 // optimise the case of a tuple and list
607
608 // get the items
Damien George9c4cbe22014-08-30 14:04:14 +0100609 mp_uint_t len;
Damien George230fec72014-03-30 21:21:24 +0100610 mp_obj_t *items;
611 mp_obj_get_array(pos_seq, &len, &items);
612
613 // allocate memory for the new array of args
614 args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
615 args2 = m_new(mp_obj_t, args2_alloc);
616
617 // copy the self
618 if (self != MP_OBJ_NULL) {
619 args2[args2_len++] = self;
620 }
621
622 // copy the fixed and variable position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300623 mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100624 args2_len += n_args + len;
625
626 } else {
627 // generic iterator
628
629 // allocate memory for the new array of args
630 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
631 args2 = m_new(mp_obj_t, args2_alloc);
632
633 // copy the self
634 if (self != MP_OBJ_NULL) {
635 args2[args2_len++] = self;
636 }
637
638 // copy the fixed position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300639 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100640
641 // extract the variable position args from the iterator
642 mp_obj_t iterable = mp_getiter(pos_seq);
643 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100644 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100645 if (args2_len >= args2_alloc) {
646 args2 = m_renew(mp_obj_t, args2, args2_alloc, args2_alloc * 2);
647 args2_alloc *= 2;
648 }
649 args2[args2_len++] = item;
650 }
651 }
652
653 // The size of the args2 array now is the number of positional args.
654 uint pos_args_len = args2_len;
655
656 // Copy the fixed kw args.
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300657 mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100658 args2_len += 2 * n_kw;
659
660 // Extract (key,value) pairs from kw_dict dictionary and append to args2.
661 // Note that it can be arbitrary iterator.
662 if (kw_dict == MP_OBJ_NULL) {
663 // pass
664 } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
665 // dictionary
666 mp_map_t *map = mp_obj_dict_get_map(kw_dict);
667 assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above
668 for (uint i = 0; i < map->alloc; i++) {
669 if (map->table[i].key != MP_OBJ_NULL) {
670 args2[args2_len++] = map->table[i].key;
671 args2[args2_len++] = map->table[i].value;
672 }
673 }
674 } else {
675 // generic mapping
676 // TODO is calling 'items' on the mapping the correct thing to do here?
677 mp_obj_t dest[2];
678 mp_load_method(kw_dict, MP_QSTR_items, dest);
679 mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest));
680 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100681 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100682 if (args2_len + 1 >= args2_alloc) {
683 uint new_alloc = args2_alloc * 2;
684 if (new_alloc < 4) {
685 new_alloc = 4;
686 }
687 args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
688 args2_alloc = new_alloc;
689 }
690 mp_obj_t *items;
691 mp_obj_get_array_fixed_n(item, 2, &items);
692 args2[args2_len++] = items[0];
693 args2[args2_len++] = items[1];
694 }
695 }
696
697 mp_obj_t res = mp_call_function_n_kw(fun, pos_args_len, (args2_len - pos_args_len) / 2, args2);
698 m_del(mp_obj_t, args2, args2_alloc);
699
700 return res;
701}
702
Damien George932bf1c2014-01-18 23:42:49 +0000703// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100704void mp_unpack_sequence(mp_obj_t seq_in, mp_uint_t num, mp_obj_t *items) {
Damien George9c4cbe22014-08-30 14:04:14 +0100705 mp_uint_t seq_len;
Damien George3e1a5c12014-03-29 13:43:38 +0000706 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 +0000707 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000708 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000709 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
710 } else {
711 mp_obj_list_get(seq_in, &seq_len, &seq_items);
Damien86c7fc72013-11-26 15:16:41 +0000712 }
Damiend99b0522013-12-21 18:17:45 +0000713 if (seq_len < num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200714 goto too_short;
Damiend99b0522013-12-21 18:17:45 +0000715 } else if (seq_len > num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200716 goto too_long;
Damiend99b0522013-12-21 18:17:45 +0000717 }
Damien George4abff752014-08-30 14:59:21 +0100718 for (mp_uint_t i = 0; i < num; i++) {
Damien George932bf1c2014-01-18 23:42:49 +0000719 items[i] = seq_items[num - 1 - i];
720 }
Damien86c7fc72013-11-26 15:16:41 +0000721 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100722 mp_obj_t iterable = mp_getiter(seq_in);
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200723
724 for (seq_len = 0; seq_len < num; seq_len++) {
Damien Georged17926d2014-03-30 13:35:08 +0100725 mp_obj_t el = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100726 if (el == MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200727 goto too_short;
728 }
729 items[num - 1 - seq_len] = el;
730 }
Damien Georgeea8d06c2014-04-17 23:19:36 +0100731 if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200732 goto too_long;
733 }
Damien86c7fc72013-11-26 15:16:41 +0000734 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200735 return;
736
737too_short:
Damien Georgeea13f402014-04-05 18:32:08 +0100738 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "need more than %d values to unpack", seq_len));
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200739too_long:
Damien Georgeea13f402014-04-05 18:32:08 +0100740 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "too many values to unpack (expected %d)", num));
Damien86c7fc72013-11-26 15:16:41 +0000741}
742
Damien George495d7812014-04-08 17:51:47 +0100743// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100744void mp_unpack_ex(mp_obj_t seq_in, mp_uint_t num_in, mp_obj_t *items) {
745 mp_uint_t num_left = num_in & 0xff;
746 mp_uint_t num_right = (num_in >> 8) & 0xff;
Damien Georgeeaaebf32014-09-23 10:59:05 +0100747 DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
Damien George9c4cbe22014-08-30 14:04:14 +0100748 mp_uint_t seq_len;
Damien George495d7812014-04-08 17:51:47 +0100749 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
750 mp_obj_t *seq_items;
751 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
752 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
753 } else {
754 if (num_left == 0 && num_right == 0) {
755 // *a, = b # sets a to b if b is a list
756 items[0] = seq_in;
757 return;
758 }
759 mp_obj_list_get(seq_in, &seq_len, &seq_items);
760 }
761 if (seq_len < num_left + num_right) {
762 goto too_short;
763 }
Damien George4abff752014-08-30 14:59:21 +0100764 for (mp_uint_t i = 0; i < num_right; i++) {
Damien George495d7812014-04-08 17:51:47 +0100765 items[i] = seq_items[seq_len - 1 - i];
766 }
767 items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
Damien George4abff752014-08-30 14:59:21 +0100768 for (mp_uint_t i = 0; i < num_left; i++) {
Damien George495d7812014-04-08 17:51:47 +0100769 items[num_right + 1 + i] = seq_items[num_left - 1 - i];
770 }
771 } else {
772 // Generic iterable; this gets a bit messy: we unpack known left length to the
773 // items destination array, then the rest to a dynamically created list. Once the
774 // iterable is exhausted, we take from this list for the right part of the items.
775 // TODO Improve to waste less memory in the dynamically created list.
776 mp_obj_t iterable = mp_getiter(seq_in);
777 mp_obj_t item;
778 for (seq_len = 0; seq_len < num_left; seq_len++) {
779 item = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100780 if (item == MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100781 goto too_short;
782 }
783 items[num_left + num_right + 1 - 1 - seq_len] = item;
784 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100785 mp_obj_list_t *rest = mp_obj_new_list(0, NULL);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100786 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100787 mp_obj_list_append(rest, item);
788 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100789 if (rest->len < num_right) {
Damien George495d7812014-04-08 17:51:47 +0100790 goto too_short;
791 }
792 items[num_right] = rest;
Damien George4abff752014-08-30 14:59:21 +0100793 for (mp_uint_t i = 0; i < num_right; i++) {
Damien Georgeca6d75f2014-08-30 15:17:47 +0100794 items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
Damien George495d7812014-04-08 17:51:47 +0100795 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100796 mp_obj_list_set_len(rest, rest->len - num_right);
Damien George495d7812014-04-08 17:51:47 +0100797 }
798 return;
799
800too_short:
801 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "need more than %d values to unpack", seq_len));
802}
803
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300804mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
Damien George062478e2014-01-09 20:57:50 +0000805 DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300806 // use load_method
Damien George062478e2014-01-09 20:57:50 +0000807 mp_obj_t dest[2];
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300808 mp_load_method(base, attr, dest);
809 if (dest[1] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000810 // load_method returned just a normal attribute
Damien George20006db2014-01-18 14:10:48 +0000811 return dest[0];
Damien George062478e2014-01-09 20:57:50 +0000812 } else {
813 // load_method returned a method, so build a bound method object
814 return mp_obj_new_bound_meth(dest[0], dest[1]);
Damiend99b0522013-12-21 18:17:45 +0000815 }
Damiend99b0522013-12-21 18:17:45 +0000816}
817
Damien George7c9c6672014-01-25 00:17:36 +0000818// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
819// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
820// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
Damien Georgee44d26a2014-03-31 22:57:56 +0100821void mp_load_method_maybe(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George062478e2014-01-09 20:57:50 +0000822 // clear output to indicate no attribute/method found yet
823 dest[0] = MP_OBJ_NULL;
824 dest[1] = MP_OBJ_NULL;
825
826 // get the type
827 mp_obj_type_t *type = mp_obj_get_type(base);
828
Damien Georgee44d26a2014-03-31 22:57:56 +0100829 // look for built-in names
830 if (0) {
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300831#if MICROPY_CPYTHON_COMPAT
Damien Georgee44d26a2014-03-31 22:57:56 +0100832 } else if (attr == MP_QSTR___class__) {
833 // a.__class__ is equivalent to type(a)
834 dest[0] = type;
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300835#endif
Damien Georgee44d26a2014-03-31 22:57:56 +0100836
837 } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
838 dest[0] = (mp_obj_t)&mp_builtin_next_obj;
839 dest[1] = base;
840
841 } else if (type->load_attr != NULL) {
842 // this type can do its own load, so call it
843 type->load_attr(base, attr, dest);
844
845 } else if (type->locals_dict != NULL) {
846 // generic method lookup
847 // this is a lookup in the object (ie not class or type)
848 assert(MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)); // Micro Python restriction, for now
849 mp_map_t *locals_map = mp_obj_dict_get_map(type->locals_dict);
850 mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
851 if (elem != NULL) {
852 // check if the methods are functions, static or class methods
Chris Angelicodaf973a2014-06-06 03:51:03 +1000853 // see http://docs.python.org/3/howto/descriptor.html
Damien Georgee44d26a2014-03-31 22:57:56 +0100854 if (MP_OBJ_IS_TYPE(elem->value, &mp_type_staticmethod)) {
855 // return just the function
856 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
857 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_classmethod)) {
858 // return a bound method, with self being the type of this object
859 dest[0] = ((mp_obj_static_class_method_t*)elem->value)->fun;
860 dest[1] = mp_obj_get_type(base);
Paul Sokolovsky9511f602014-05-11 03:12:36 +0300861 } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_type)) {
862 // Don't try to bind types
863 dest[0] = elem->value;
Damien Georgee44d26a2014-03-31 22:57:56 +0100864 } else if (mp_obj_is_callable(elem->value)) {
865 // return a bound method, with self being this object
866 dest[0] = elem->value;
867 dest[1] = base;
868 } else {
869 // class member is a value, so just return that value
870 dest[0] = elem->value;
Damiend57eba52013-11-02 23:58:14 +0000871 }
872 }
Damiena3977762013-10-09 23:10:10 +0100873 }
Damien George7c9c6672014-01-25 00:17:36 +0000874}
Damiena3977762013-10-09 23:10:10 +0100875
Damien Georged17926d2014-03-30 13:35:08 +0100876void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George7c9c6672014-01-25 00:17:36 +0000877 DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
878
Damien Georged17926d2014-03-30 13:35:08 +0100879 mp_load_method_maybe(base, attr, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000880
881 if (dest[0] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000882 // no attribute/method called attr
883 // following CPython, we give a more detailed error message for type objects
Damien Georgec5966122014-02-15 16:10:44 +0000884 if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100885 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Paul Sokolovsky7f8b3132014-03-25 00:55:39 +0200886 "type object '%s' has no attribute '%s'", qstr_str(((mp_obj_type_t*)base)->name), qstr_str(attr)));
Damien George062478e2014-01-09 20:57:50 +0000887 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100888 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, "'%s' object has no attribute '%s'", mp_obj_get_type_str(base), qstr_str(attr)));
Damien George062478e2014-01-09 20:57:50 +0000889 }
890 }
Damiena3977762013-10-09 23:10:10 +0100891}
892
Damien Georged17926d2014-03-30 13:35:08 +0100893void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien5ac1b2e2013-10-18 19:58:12 +0100894 DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
Damien George062478e2014-01-09 20:57:50 +0000895 mp_obj_type_t *type = mp_obj_get_type(base);
896 if (type->store_attr != NULL) {
897 if (type->store_attr(base, attr, value)) {
898 return;
899 }
Damiena3977762013-10-09 23:10:10 +0100900 }
Damien Georgeea13f402014-04-05 18:32:08 +0100901 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, "'%s' object has no attribute '%s'", mp_obj_get_type_str(base), qstr_str(attr)));
Damiena3977762013-10-09 23:10:10 +0100902}
903
Damien Georged17926d2014-03-30 13:35:08 +0100904mp_obj_t mp_getiter(mp_obj_t o_in) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300905 assert(o_in);
Damien George5fa93b62014-01-22 14:35:10 +0000906 mp_obj_type_t *type = mp_obj_get_type(o_in);
907 if (type->getiter != NULL) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300908 mp_obj_t iter = type->getiter(o_in);
909 if (iter == MP_OBJ_NULL) {
910 goto not_iterable;
911 }
912 return iter;
Damience89a212013-10-15 22:25:17 +0100913 } else {
Damien George9e6e9352014-03-26 18:37:06 +0000914 // check for __iter__ method
Damien George7c9c6672014-01-25 00:17:36 +0000915 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +0100916 mp_load_method_maybe(o_in, MP_QSTR___iter__, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000917 if (dest[0] != MP_OBJ_NULL) {
Damien George9e6e9352014-03-26 18:37:06 +0000918 // __iter__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +0100919 return mp_call_method_n_kw(0, 0, dest);
Damien George7c9c6672014-01-25 00:17:36 +0000920 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100921 mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
Damien George9e6e9352014-03-26 18:37:06 +0000922 if (dest[0] != MP_OBJ_NULL) {
923 // __getitem__ exists, create an iterator
924 return mp_obj_new_getitem_iter(dest);
925 } else {
926 // object not iterable
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +0300927not_iterable:
Damien Georgeea13f402014-04-05 18:32:08 +0100928 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
Damien George9e6e9352014-03-26 18:37:06 +0000929 }
Damien George7c9c6672014-01-25 00:17:36 +0000930 }
Damience89a212013-10-15 22:25:17 +0100931 }
932}
933
Damien Georgeea8d06c2014-04-17 23:19:36 +0100934// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
Damien George66eaf842014-03-26 19:27:58 +0000935// may also raise StopIteration()
Damien Georged17926d2014-03-30 13:35:08 +0100936mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000937 mp_obj_type_t *type = mp_obj_get_type(o_in);
938 if (type->iternext != NULL) {
939 return type->iternext(o_in);
Damience89a212013-10-15 22:25:17 +0100940 } else {
Damien George9e6e9352014-03-26 18:37:06 +0000941 // check for __next__ method
942 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +0100943 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George9e6e9352014-03-26 18:37:06 +0000944 if (dest[0] != MP_OBJ_NULL) {
945 // __next__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +0100946 return mp_call_method_n_kw(0, 0, dest);
Damien George9e6e9352014-03-26 18:37:06 +0000947 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100948 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
Damien George9e6e9352014-03-26 18:37:06 +0000949 }
Damien Georgec5966122014-02-15 16:10:44 +0000950 }
951}
952
Damien Georgeea8d06c2014-04-17 23:19:36 +0100953// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
Damien George66eaf842014-03-26 19:27:58 +0000954// may raise other exceptions
Damien Georged17926d2014-03-30 13:35:08 +0100955mp_obj_t mp_iternext(mp_obj_t o_in) {
Damien George66eaf842014-03-26 19:27:58 +0000956 mp_obj_type_t *type = mp_obj_get_type(o_in);
957 if (type->iternext != NULL) {
958 return type->iternext(o_in);
959 } else {
960 // check for __next__ method
961 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +0100962 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George66eaf842014-03-26 19:27:58 +0000963 if (dest[0] != MP_OBJ_NULL) {
964 // __next__ exists, call it and return its result
965 nlr_buf_t nlr;
966 if (nlr_push(&nlr) == 0) {
Damien Georged17926d2014-03-30 13:35:08 +0100967 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
Damien George66eaf842014-03-26 19:27:58 +0000968 nlr_pop();
969 return ret;
970 } else {
971 if (mp_obj_is_subclass_fast(mp_obj_get_type(nlr.ret_val), &mp_type_StopIteration)) {
Damien Georgeea8d06c2014-04-17 23:19:36 +0100972 return MP_OBJ_STOP_ITERATION;
Damien George66eaf842014-03-26 19:27:58 +0000973 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100974 nlr_raise(nlr.ret_val);
Damien George66eaf842014-03-26 19:27:58 +0000975 }
976 }
977 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100978 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
Damien George66eaf842014-03-26 19:27:58 +0000979 }
980 }
981}
982
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +0300983// TODO: Unclear what to do with StopIterarion exception here.
984mp_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 +0300985 assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +0300986 mp_obj_type_t *type = mp_obj_get_type(self_in);
987
988 if (type == &mp_type_gen_instance) {
989 return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
990 }
991
992 if (type->iternext != NULL && send_value == mp_const_none) {
993 mp_obj_t ret = type->iternext(self_in);
994 if (ret != MP_OBJ_NULL) {
995 *ret_val = ret;
996 return MP_VM_RETURN_YIELD;
997 } else {
998 // Emulate raise StopIteration()
999 // Special case, handled in vm.c
1000 *ret_val = MP_OBJ_NULL;
1001 return MP_VM_RETURN_NORMAL;
1002 }
1003 }
1004
1005 mp_obj_t dest[3]; // Reserve slot for send() arg
1006
1007 if (send_value == mp_const_none) {
1008 mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1009 if (dest[0] != MP_OBJ_NULL) {
1010 *ret_val = mp_call_method_n_kw(0, 0, dest);
1011 return MP_VM_RETURN_YIELD;
1012 }
1013 }
1014
1015 if (send_value != MP_OBJ_NULL) {
1016 mp_load_method(self_in, MP_QSTR_send, dest);
1017 dest[2] = send_value;
1018 *ret_val = mp_call_method_n_kw(1, 0, dest);
1019 return MP_VM_RETURN_YIELD;
1020 }
1021
1022 if (throw_value != MP_OBJ_NULL) {
1023 if (mp_obj_is_subclass_fast(mp_obj_get_type(throw_value), &mp_type_GeneratorExit)) {
1024 mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1025 if (dest[0] != MP_OBJ_NULL) {
1026 *ret_val = mp_call_method_n_kw(0, 0, dest);
1027 // We assume one can't "yield" from close()
1028 return MP_VM_RETURN_NORMAL;
1029 }
1030 }
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001031 mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1032 if (dest[0] != MP_OBJ_NULL) {
1033 *ret_val = mp_call_method_n_kw(1, 0, &throw_value);
1034 // If .throw() method returned, we assume it's value to yield
Damien Georgeea13f402014-04-05 18:32:08 +01001035 // - any exception would be thrown with nlr_raise().
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001036 return MP_VM_RETURN_YIELD;
1037 }
1038 // If there's nowhere to throw exception into, then we assume that object
1039 // is just incapable to handle it, so any exception thrown into it
1040 // will be propagated up. This behavior is approved by test_pep380.py
1041 // test_delegation_of_close_to_non_generator(),
1042 // test_delegating_throw_to_non_generator()
1043 *ret_val = throw_value;
1044 return MP_VM_RETURN_EXCEPTION;
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001045 }
1046
1047 assert(0);
1048 return MP_VM_RETURN_NORMAL; // Should be unreachable
1049}
1050
Damien Georged17926d2014-03-30 13:35:08 +01001051mp_obj_t mp_make_raise_obj(mp_obj_t o) {
Damien Georgec5966122014-02-15 16:10:44 +00001052 DEBUG_printf("raise %p\n", o);
1053 if (mp_obj_is_exception_type(o)) {
1054 // o is an exception type (it is derived from BaseException (or is BaseException))
1055 // create and return a new exception instance by calling o
Damien George22a08652014-02-15 21:05:25 +00001056 // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1057 // could have const instances in ROM which we return here instead
Damien Georged17926d2014-03-30 13:35:08 +01001058 return mp_call_function_n_kw(o, 0, 0, NULL);
Damien Georgec5966122014-02-15 16:10:44 +00001059 } else if (mp_obj_is_exception_instance(o)) {
1060 // o is an instance of an exception, so use it as the exception
1061 return o;
1062 } else {
1063 // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1064 return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
Damience89a212013-10-15 22:25:17 +01001065 }
1066}
1067
Damien Georged17926d2014-03-30 13:35:08 +01001068mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
Damien George64131f32014-02-06 20:31:44 +00001069 DEBUG_printf("import name %s\n", qstr_str(name));
1070
Damiendb4c3612013-12-10 17:27:24 +00001071 // build args array
Damiend99b0522013-12-21 18:17:45 +00001072 mp_obj_t args[5];
Damien George5fa93b62014-01-22 14:35:10 +00001073 args[0] = MP_OBJ_NEW_QSTR(name);
Damiend99b0522013-12-21 18:17:45 +00001074 args[1] = mp_const_none; // TODO should be globals
1075 args[2] = mp_const_none; // TODO should be locals
Damiendb4c3612013-12-10 17:27:24 +00001076 args[3] = fromlist;
1077 args[4] = level; // must be 0; we don't yet support other values
1078
1079 // TODO lookup __import__ and call that instead of going straight to builtin implementation
Damiend99b0522013-12-21 18:17:45 +00001080 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001081}
1082
Damien Georged17926d2014-03-30 13:35:08 +01001083mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
Damien George64131f32014-02-06 20:31:44 +00001084 DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1085
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001086 mp_obj_t dest[2];
1087
1088 mp_load_method_maybe(module, name, dest);
1089
1090 if (dest[1] != MP_OBJ_NULL) {
1091 // Hopefully we can't import bound method from an object
1092import_error:
Paul Sokolovsky42453dc2014-04-12 03:00:40 +03001093 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %s", qstr_str(name)));
Damiendb4c3612013-12-10 17:27:24 +00001094 }
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001095
1096 if (dest[0] != MP_OBJ_NULL) {
1097 return dest[0];
1098 }
1099
1100 // See if it's a package, then can try FS import
1101 mp_load_method_maybe(module, MP_QSTR___path__, dest);
1102 if (dest[0] == MP_OBJ_NULL) {
1103 goto import_error;
1104 }
1105
1106 mp_load_method_maybe(module, MP_QSTR___name__, dest);
Damien Georged182b982014-08-30 14:19:41 +01001107 mp_uint_t pkg_name_len;
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001108 const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1109
stijn01d6be42014-05-05 12:18:27 +02001110 const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1111 char *dot_name = alloca(dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001112 memcpy(dot_name, pkg_name, pkg_name_len);
1113 dot_name[pkg_name_len] = '.';
1114 memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
stijn01d6be42014-05-05 12:18:27 +02001115 qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001116
1117 mp_obj_t args[5];
1118 args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
1119 args[1] = mp_const_none; // TODO should be globals
1120 args[2] = mp_const_none; // TODO should be locals
1121 args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
Paul Sokolovsky69f18672014-04-12 02:47:46 +03001122 args[4] = MP_OBJ_NEW_SMALL_INT(0);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001123
1124 // TODO lookup __import__ and call that instead of going straight to builtin implementation
1125 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001126}
1127
Damien Georged17926d2014-03-30 13:35:08 +01001128void mp_import_all(mp_obj_t module) {
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001129 DEBUG_printf("import all %p\n", module);
1130
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001131 // TODO: Support __all__
Damien George8b0535e2014-04-05 21:53:54 +01001132 mp_map_t *map = mp_obj_dict_get_map(mp_obj_module_get_globals(module));
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001133 for (uint i = 0; i < map->alloc; i++) {
Damien George8b0535e2014-04-05 21:53:54 +01001134 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001135 qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
1136 if (*qstr_str(name) != '_') {
1137 mp_store_name(name, map->table[i].value);
1138 }
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001139 }
1140 }
1141}
1142
Damien George7efc5b32014-04-05 22:36:42 +01001143mp_obj_dict_t *mp_locals_get(void) {
1144 return dict_locals;
Damien George66028ab2014-01-03 14:03:48 +00001145}
1146
Damien George7efc5b32014-04-05 22:36:42 +01001147void mp_locals_set(mp_obj_dict_t *d) {
1148 DEBUG_OP_printf("mp_locals_set(%p)\n", d);
1149 dict_locals = d;
Damien George66028ab2014-01-03 14:03:48 +00001150}
1151
Damien George7efc5b32014-04-05 22:36:42 +01001152mp_obj_dict_t *mp_globals_get(void) {
1153 return dict_globals;
Damien George66028ab2014-01-03 14:03:48 +00001154}
1155
Damien George7efc5b32014-04-05 22:36:42 +01001156void mp_globals_set(mp_obj_dict_t *d) {
1157 DEBUG_OP_printf("mp_globals_set(%p)\n", d);
1158 dict_globals = d;
Damien George66028ab2014-01-03 14:03:48 +00001159}
1160
Damien Georgec4d08682014-10-05 20:13:34 +01001161// this is implemented in this file so it can optimise access to locals/globals
1162mp_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) {
1163 // parse the string
1164 mp_parse_error_kind_t parse_error_kind;
1165 mp_parse_node_t pn = mp_parse(lex, parse_input_kind, &parse_error_kind);
1166
1167 if (pn == MP_PARSE_NODE_NULL) {
1168 // parse error; raise exception
1169 mp_obj_t exc = mp_parse_make_exception(lex, parse_error_kind);
1170 mp_lexer_free(lex);
1171 nlr_raise(exc);
1172 }
1173
1174 qstr source_name = mp_lexer_source_name(lex);
1175 mp_lexer_free(lex);
1176
1177 // save context and set new context
1178 mp_obj_dict_t *old_globals = mp_globals_get();
1179 mp_obj_dict_t *old_locals = mp_locals_get();
1180 mp_globals_set(globals);
1181 mp_locals_set(locals);
1182
1183 // compile the string
1184 mp_obj_t module_fun = mp_compile(pn, source_name, MP_EMIT_OPT_NONE, false);
1185
1186 // check if there was a compile error
1187 if (mp_obj_is_exception_instance(module_fun)) {
1188 mp_globals_set(old_globals);
1189 mp_locals_set(old_locals);
1190 nlr_raise(module_fun);
1191 }
1192
1193 // complied successfully, execute it
1194 nlr_buf_t nlr;
1195 if (nlr_push(&nlr) == 0) {
1196 mp_obj_t ret = mp_call_function_0(module_fun);
1197 nlr_pop();
1198 mp_globals_set(old_globals);
1199 mp_locals_set(old_locals);
1200 return ret;
1201 } else {
1202 // exception; restore context and re-raise same exception
1203 mp_globals_set(old_globals);
1204 mp_locals_set(old_locals);
1205 nlr_raise(nlr.ret_val);
1206 }
1207}
1208
Damien Georgeb0261342014-09-23 18:10:17 +01001209void *m_malloc_fail(size_t num_bytes) {
1210 DEBUG_printf("memory allocation failed, allocating " UINT_FMT " bytes\n", num_bytes);
Damien George40914452014-10-09 16:44:43 +01001211 if (0) {
1212 // dummy
1213 #if MICROPY_ENABLE_GC
1214 } else if (gc_is_locked()) {
1215 nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001216 "memory allocation failed, heap is locked"));
Damien George40914452014-10-09 16:44:43 +01001217 #endif
Dave Hylands3556e452014-10-07 00:50:20 -07001218 } else {
Damien George40914452014-10-09 16:44:43 +01001219 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001220 "memory allocation failed, allocating " UINT_FMT " bytes", num_bytes));
1221 }
Damien George6902eed2014-04-04 10:52:59 +00001222}
1223
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001224NORETURN void mp_not_implemented(const char *msg) {
1225 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, msg));
1226}