blob: 4959617eff6b12275c90e3b73a923ea173dd30ce [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
Damien429d7192013-10-04 19:53:11 +010027#include <stdio.h>
28#include <string.h>
29#include <assert.h>
30
Damien Georgeb4b10fd2015-01-01 23:30:53 +000031#include "py/mpstate.h"
Damien George51dfcb42015-01-01 20:27:54 +000032#include "py/nlr.h"
Damien George51dfcb42015-01-01 20:27:54 +000033#include "py/parsenum.h"
34#include "py/compile.h"
Damien Georgec2a4e4e2015-05-11 12:25:19 +000035#include "py/objstr.h"
Damien George51dfcb42015-01-01 20:27:54 +000036#include "py/objtuple.h"
37#include "py/objlist.h"
38#include "py/objmodule.h"
39#include "py/objgenerator.h"
40#include "py/smallint.h"
41#include "py/runtime0.h"
42#include "py/runtime.h"
43#include "py/builtin.h"
44#include "py/stackctrl.h"
45#include "py/gc.h"
Damien660365e2013-12-17 18:27:24 +000046
Damien7f5dacf2013-10-10 11:24:39 +010047#if 0 // print debugging info
Damiena1ddfcc2013-10-10 23:25:50 +010048#define DEBUG_PRINT (1)
Paul Sokolovsky44739e22014-02-16 18:11:42 +020049#define DEBUG_printf DEBUG_printf
Damien George41eb6082014-02-26 22:40:35 +000050#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
Damien7f5dacf2013-10-10 11:24:39 +010051#else // don't print debugging info
Damien George41eb6082014-02-26 22:40:35 +000052#define DEBUG_printf(...) (void)0
53#define DEBUG_OP_printf(...) (void)0
Damien7f5dacf2013-10-10 11:24:39 +010054#endif
Damien429d7192013-10-04 19:53:11 +010055
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030056const mp_obj_module_t mp_module___main__ = {
57 .base = { &mp_type_module },
58 .name = MP_QSTR___main__,
Damien Georgeb4b10fd2015-01-01 23:30:53 +000059 .globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main),
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030060};
61
Damien Georged17926d2014-03-30 13:35:08 +010062void mp_init(void) {
Damien George8dbbbbc2014-08-04 10:05:16 +010063 qstr_init();
Paul Sokolovskycaa73342014-07-01 02:13:42 +030064 mp_stack_ctrl_init();
Paul Sokolovsky8a96ebe2014-06-27 20:54:22 +030065
Damien George124df6f2014-10-25 18:19:55 +010066 // no pending exceptions to start with
Damien Georgeb4b10fd2015-01-01 23:30:53 +000067 MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
Damien George124df6f2014-10-25 18:19:55 +010068
Damien George8dbbbbc2014-08-04 10:05:16 +010069#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
70 mp_init_emergency_exception_buf();
71#endif
72
Damien George97f9a282014-05-12 23:07:34 +010073 // call port specific initialization if any
stijn72521a12014-05-03 11:28:29 +020074#ifdef MICROPY_PORT_INIT_FUNC
75 MICROPY_PORT_INIT_FUNC;
76#endif
77
Paul Sokolovskyd3439d02014-06-02 19:37:55 +030078 // optimization disabled by default
Damien Georgeb4b10fd2015-01-01 23:30:53 +000079 MP_STATE_VM(mp_optimise_value) = 0;
Damien George97f9a282014-05-12 23:07:34 +010080
Damien Georgecaac5422014-03-25 14:18:18 +000081 // init global module stuff
82 mp_module_init();
Damien George0d028742014-01-22 23:59:20 +000083
Damien George7efc5b32014-04-05 22:36:42 +010084 // initialise the __main__ module
Damien Georgeb4b10fd2015-01-01 23:30:53 +000085 mp_obj_dict_init(&MP_STATE_VM(dict_main), 1);
86 mp_obj_dict_store(&MP_STATE_VM(dict_main), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
Paul Sokolovskyc6813d92014-04-04 20:08:21 +030087
88 // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
Damien Georgeb4b10fd2015-01-01 23:30:53 +000089 MP_STATE_CTX(dict_locals) = MP_STATE_CTX(dict_globals) = &MP_STATE_VM(dict_main);
Damien George78d702c2014-12-09 16:19:48 +000090
91 #if MICROPY_CAN_OVERRIDE_BUILTINS
92 // start with no extensions to builtins
Damien Georgeb4b10fd2015-01-01 23:30:53 +000093 MP_STATE_VM(mp_module_builtins_override_dict) = NULL;
Damien George78d702c2014-12-09 16:19:48 +000094 #endif
Damien429d7192013-10-04 19:53:11 +010095}
96
Damien Georged17926d2014-03-30 13:35:08 +010097void mp_deinit(void) {
Damien George7efc5b32014-04-05 22:36:42 +010098 //mp_obj_dict_free(&dict_main);
Damien George2326d522014-03-27 23:26:35 +000099 mp_module_deinit();
stijn5ed284a2014-05-08 10:56:33 +0200100
101 // call port specific deinitialization if any
102#ifdef MICROPY_PORT_INIT_FUNC
103 MICROPY_PORT_DEINIT_FUNC;
104#endif
Damien429d7192013-10-04 19:53:11 +0100105}
106
Damien George50912e72015-01-20 11:55:10 +0000107mp_obj_t mp_load_const_str(qstr qst) {
108 DEBUG_OP_printf("load '%s'\n", qstr_str(qst));
109 return MP_OBJ_NEW_QSTR(qst);
Damien429d7192013-10-04 19:53:11 +0100110}
111
Damien George50912e72015-01-20 11:55:10 +0000112mp_obj_t mp_load_const_bytes(qstr qst) {
113 DEBUG_OP_printf("load b'%s'\n", qstr_str(qst));
Damien George39dc1452014-10-03 19:52:22 +0100114 mp_uint_t len;
Damien George50912e72015-01-20 11:55:10 +0000115 const byte *data = qstr_data(qst, &len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200116 return mp_obj_new_bytes(data, len);
117}
118
Damien George50912e72015-01-20 11:55:10 +0000119mp_obj_t mp_load_name(qstr qst) {
Damien429d7192013-10-04 19:53:11 +0100120 // logic: search locals, globals, builtins
Damien George50912e72015-01-20 11:55:10 +0000121 DEBUG_OP_printf("load name %s\n", qstr_str(qst));
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300122 // If we're at the outer scope (locals == globals), dispatch to load_global right away
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000123 if (MP_STATE_CTX(dict_locals) != MP_STATE_CTX(dict_globals)) {
Damien George50912e72015-01-20 11:55:10 +0000124 mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_locals)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Paul Sokolovskya0d32992014-04-05 04:51:26 +0300125 if (elem != NULL) {
126 return elem->value;
127 }
Damiena3977762013-10-09 23:10:10 +0100128 }
Damien George50912e72015-01-20 11:55:10 +0000129 return mp_load_global(qst);
Damiena3977762013-10-09 23:10:10 +0100130}
131
Damien George50912e72015-01-20 11:55:10 +0000132mp_obj_t mp_load_global(qstr qst) {
Damiena3977762013-10-09 23:10:10 +0100133 // logic: search globals, builtins
Damien George50912e72015-01-20 11:55:10 +0000134 DEBUG_OP_printf("load global %s\n", qstr_str(qst));
135 mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_globals)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100136 if (elem == NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000137 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000138 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000139 // lookup in additional dynamic table of builtins first
Damien George50912e72015-01-20 11:55:10 +0000140 elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Damien George78d702c2014-12-09 16:19:48 +0000141 if (elem != NULL) {
142 return elem->value;
143 }
144 }
145 #endif
Damien George50912e72015-01-20 11:55:10 +0000146 elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
Damien429d7192013-10-04 19:53:11 +0100147 if (elem == NULL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000148 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
149 nlr_raise(mp_obj_new_exception_msg(&mp_type_NameError,
150 "name not defined"));
151 } else {
152 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
Damien George044c4732015-04-11 13:03:37 +0100153 "name '%q' is not defined", qst));
Damien George1e9a92f2014-11-06 17:36:16 +0000154 }
Damien429d7192013-10-04 19:53:11 +0100155 }
156 }
157 return elem->value;
158}
159
Damien Georged17926d2014-03-30 13:35:08 +0100160mp_obj_t mp_load_build_class(void) {
Damien429d7192013-10-04 19:53:11 +0100161 DEBUG_OP_printf("load_build_class\n");
Damien George78d702c2014-12-09 16:19:48 +0000162 #if MICROPY_CAN_OVERRIDE_BUILTINS
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000163 if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
Damien George78d702c2014-12-09 16:19:48 +0000164 // lookup in additional dynamic table of builtins first
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000165 mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(MP_QSTR___build_class__), MP_MAP_LOOKUP);
Damien George78d702c2014-12-09 16:19:48 +0000166 if (elem != NULL) {
167 return elem->value;
168 }
169 }
170 #endif
Damien George7efc5b32014-04-05 22:36:42 +0100171 return (mp_obj_t)&mp_builtin___build_class___obj;
Damien429d7192013-10-04 19:53:11 +0100172}
173
Damien George50912e72015-01-20 11:55:10 +0000174void mp_store_name(qstr qst, mp_obj_t obj) {
175 DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qst), obj);
176 mp_obj_dict_store(MP_STATE_CTX(dict_locals), MP_OBJ_NEW_QSTR(qst), obj);
Damiena3977762013-10-09 23:10:10 +0100177}
178
Damien George50912e72015-01-20 11:55:10 +0000179void mp_delete_name(qstr qst) {
180 DEBUG_OP_printf("delete name %s\n", qstr_str(qst));
181 // TODO convert KeyError to NameError if qst not found
182 mp_obj_dict_delete(MP_STATE_CTX(dict_locals), MP_OBJ_NEW_QSTR(qst));
Paul Sokolovskyf9090342014-03-23 21:19:02 +0200183}
184
Damien George50912e72015-01-20 11:55:10 +0000185void mp_store_global(qstr qst, mp_obj_t obj) {
186 DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qst), obj);
187 mp_obj_dict_store(MP_STATE_CTX(dict_globals), MP_OBJ_NEW_QSTR(qst), obj);
Damien429d7192013-10-04 19:53:11 +0100188}
189
Damien George50912e72015-01-20 11:55:10 +0000190void mp_delete_global(qstr qst) {
191 DEBUG_OP_printf("delete global %s\n", qstr_str(qst));
192 // TODO convert KeyError to NameError if qst not found
193 mp_obj_dict_delete(MP_STATE_CTX(dict_globals), MP_OBJ_NEW_QSTR(qst));
Damien George1d24ea52014-04-08 21:11:49 +0100194}
195
Damien George4abff752014-08-30 14:59:21 +0100196mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100197 DEBUG_OP_printf("unary " UINT_FMT " %p\n", op, arg);
Damien George9aa2a522014-02-01 23:04:09 +0000198
Damiend99b0522013-12-21 18:17:45 +0000199 if (MP_OBJ_IS_SMALL_INT(arg)) {
Damien George40f3c022014-07-03 13:25:24 +0100200 mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
Damien7410e442013-11-02 19:47:57 +0000201 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100202 case MP_UNARY_OP_BOOL:
Damien George9d68e9c2014-03-12 15:38:15 +0000203 return MP_BOOL(val != 0);
Damien Georgec2a4e4e2015-05-11 12:25:19 +0000204 case MP_UNARY_OP_HASH:
205 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100206 case MP_UNARY_OP_POSITIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000207 return arg;
Damien Georged17926d2014-03-30 13:35:08 +0100208 case MP_UNARY_OP_NEGATIVE:
Damien George9d68e9c2014-03-12 15:38:15 +0000209 // check for overflow
210 if (val == MP_SMALL_INT_MIN) {
211 return mp_obj_new_int(-val);
212 } else {
213 return MP_OBJ_NEW_SMALL_INT(-val);
214 }
Damien Georged17926d2014-03-30 13:35:08 +0100215 case MP_UNARY_OP_INVERT:
Damien George9d68e9c2014-03-12 15:38:15 +0000216 return MP_OBJ_NEW_SMALL_INT(~val);
217 default:
218 assert(0);
219 return arg;
Damien7410e442013-11-02 19:47:57 +0000220 }
Damien Georgec2a4e4e2015-05-11 12:25:19 +0000221 } else if (op == MP_UNARY_OP_HASH && MP_OBJ_IS_STR_OR_BYTES(arg)) {
222 // fast path for hashing str/bytes
223 GET_STR_HASH(arg, h);
224 return MP_OBJ_NEW_SMALL_INT(h);
Damien George1e708fe2014-01-23 18:27:51 +0000225 } else {
226 mp_obj_type_t *type = mp_obj_get_type(arg);
227 if (type->unary_op != NULL) {
228 mp_obj_t result = type->unary_op(op, arg);
Damien George6ac5dce2014-05-21 19:42:43 +0100229 if (result != MP_OBJ_NULL) {
Damiend99b0522013-12-21 18:17:45 +0000230 return result;
231 }
Damien7410e442013-11-02 19:47:57 +0000232 }
Damien George1e9a92f2014-11-06 17:36:16 +0000233 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
234 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
235 "unsupported type for operator"));
236 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000237 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
Damien George044c4732015-04-11 13:03:37 +0100238 "unsupported type for %q: '%s'",
239 mp_unary_op_method_name[op], mp_obj_get_type_str(arg)));
Damien George1e9a92f2014-11-06 17:36:16 +0000240 }
Damien7410e442013-11-02 19:47:57 +0000241 }
Damien429d7192013-10-04 19:53:11 +0100242}
243
Damien George4abff752014-08-30 14:59:21 +0100244mp_obj_t mp_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100245 DEBUG_OP_printf("binary " UINT_FMT " %p %p\n", op, lhs, rhs);
Damien George14f945c2014-01-03 14:09:31 +0000246
247 // TODO correctly distinguish inplace operators for mutable objects
248 // lookup logic that CPython uses for +=:
249 // check for implemented +=
250 // then check for implemented +
251 // then check for implemented seq.inplace_concat
252 // then check for implemented seq.concat
253 // then fail
254 // note that list does not implement + or +=, so that inplace_concat is reached first for +=
255
Damien George9aa2a522014-02-01 23:04:09 +0000256 // deal with is
Damien Georged17926d2014-03-30 13:35:08 +0100257 if (op == MP_BINARY_OP_IS) {
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200258 return MP_BOOL(lhs == rhs);
259 }
Paul Sokolovsky8bc96472014-01-15 00:31:28 +0200260
Damien Georgebcbeea02014-01-11 10:47:22 +0000261 // deal with == and != for all types
Damien Georged17926d2014-03-30 13:35:08 +0100262 if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000263 if (mp_obj_equal(lhs, rhs)) {
Damien Georged17926d2014-03-30 13:35:08 +0100264 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000265 return mp_const_true;
266 } else {
267 return mp_const_false;
268 }
269 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100270 if (op == MP_BINARY_OP_EQUAL) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000271 return mp_const_false;
272 } else {
273 return mp_const_true;
274 }
275 }
276 }
277
278 // deal with exception_match for all types
Damien Georged17926d2014-03-30 13:35:08 +0100279 if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
Damien Georgec5966122014-02-15 16:10:44 +0000280 // rhs must be issubclass(rhs, BaseException)
281 if (mp_obj_is_exception_type(rhs)) {
Damien George4bcd04b2014-09-24 14:05:40 +0100282 if (mp_obj_exception_match(lhs, rhs)) {
Damien Georgebcbeea02014-01-11 10:47:22 +0000283 return mp_const_true;
284 } else {
285 return mp_const_false;
286 }
Damien George4bcd04b2014-09-24 14:05:40 +0100287 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
288 mp_obj_tuple_t *tuple = rhs;
289 for (mp_uint_t i = 0; i < tuple->len; i++) {
290 rhs = tuple->items[i];
291 if (!mp_obj_is_exception_type(rhs)) {
292 goto unsupported_op;
293 }
294 if (mp_obj_exception_match(lhs, rhs)) {
295 return mp_const_true;
296 }
297 }
298 return mp_const_false;
Damien Georgebcbeea02014-01-11 10:47:22 +0000299 }
Damien George4bcd04b2014-09-24 14:05:40 +0100300 goto unsupported_op;
Damien Georgebcbeea02014-01-11 10:47:22 +0000301 }
302
Damien George1a9951d2014-01-06 22:13:00 +0000303 if (MP_OBJ_IS_SMALL_INT(lhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100304 mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
Damien George1a9951d2014-01-06 22:13:00 +0000305 if (MP_OBJ_IS_SMALL_INT(rhs)) {
Damien George40f3c022014-07-03 13:25:24 +0100306 mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
Damien George9d68e9c2014-03-12 15:38:15 +0000307 // This is a binary operation: lhs_val op rhs_val
308 // We need to be careful to handle overflow; see CERT INT32-C
309 // Operations that can overflow:
Damien George40f3c022014-07-03 13:25:24 +0100310 // + result always fits in mp_int_t, then handled by SMALL_INT check
311 // - result always fits in mp_int_t, then handled by SMALL_INT check
Damien George9d68e9c2014-03-12 15:38:15 +0000312 // * checked explicitly
Damien George40f3c022014-07-03 13:25:24 +0100313 // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
314 // % 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 +0000315 // << checked explicitly
Damien George1a9951d2014-01-06 22:13:00 +0000316 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100317 case MP_BINARY_OP_OR:
318 case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
319 case MP_BINARY_OP_XOR:
320 case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
321 case MP_BINARY_OP_AND:
322 case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
323 case MP_BINARY_OP_LSHIFT:
324 case MP_BINARY_OP_INPLACE_LSHIFT: {
Damien George9d68e9c2014-03-12 15:38:15 +0000325 if (rhs_val < 0) {
326 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100327 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George963a5a32015-01-16 17:47:07 +0000328 } else if (rhs_val >= (mp_int_t)BITS_PER_WORD || lhs_val > (MP_SMALL_INT_MAX >> rhs_val) || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
Damien George9d68e9c2014-03-12 15:38:15 +0000329 // left-shift will overflow, so use higher precision integer
330 lhs = mp_obj_new_int_from_ll(lhs_val);
331 goto generic_binary_op;
332 } else {
333 // use standard precision
334 lhs_val <<= rhs_val;
335 }
336 break;
337 }
Damien Georged17926d2014-03-30 13:35:08 +0100338 case MP_BINARY_OP_RSHIFT:
339 case MP_BINARY_OP_INPLACE_RSHIFT:
Damien George9d68e9c2014-03-12 15:38:15 +0000340 if (rhs_val < 0) {
341 // negative shift not allowed
Damien Georgeea13f402014-04-05 18:32:08 +0100342 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
Damien George9d68e9c2014-03-12 15:38:15 +0000343 } else {
344 // standard precision is enough for right-shift
Damien George963a5a32015-01-16 17:47:07 +0000345 if (rhs_val >= (mp_int_t)BITS_PER_WORD) {
Paul Sokolovsky039887a2014-11-02 02:39:41 +0200346 // Shifting to big amounts is underfined behavior
347 // in C and is CPU-dependent; propagate sign bit.
348 rhs_val = BITS_PER_WORD - 1;
349 }
Damien George9d68e9c2014-03-12 15:38:15 +0000350 lhs_val >>= rhs_val;
351 }
352 break;
Damien Georged17926d2014-03-30 13:35:08 +0100353 case MP_BINARY_OP_ADD:
354 case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
355 case MP_BINARY_OP_SUBTRACT:
356 case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
357 case MP_BINARY_OP_MULTIPLY:
358 case MP_BINARY_OP_INPLACE_MULTIPLY: {
Damien George9d68e9c2014-03-12 15:38:15 +0000359
Damien George40f3c022014-07-03 13:25:24 +0100360 // If long long type exists and is larger than mp_int_t, then
Damien George9d68e9c2014-03-12 15:38:15 +0000361 // we can use the following code to perform overflow-checked multiplication.
Damien Georgeecf5b772014-04-04 11:13:51 +0000362 // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
Damien George9d68e9c2014-03-12 15:38:15 +0000363 #if 0
364 // compute result using long long precision
365 long long res = (long long)lhs_val * (long long)rhs_val;
366 if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
367 // result overflowed SMALL_INT, so return higher precision integer
368 return mp_obj_new_int_from_ll(res);
369 } else {
370 // use standard precision
Damien George40f3c022014-07-03 13:25:24 +0100371 lhs_val = (mp_int_t)res;
Damien George9d68e9c2014-03-12 15:38:15 +0000372 }
373 #endif
374
Damien Georgeecf5b772014-04-04 11:13:51 +0000375 if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
376 // use higher precision
377 lhs = mp_obj_new_int_from_ll(lhs_val);
378 goto generic_binary_op;
379 } else {
380 // use standard precision
381 return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
382 }
Damien George9d68e9c2014-03-12 15:38:15 +0000383 break;
384 }
Damien Georged17926d2014-03-30 13:35:08 +0100385 case MP_BINARY_OP_FLOOR_DIVIDE:
386 case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300387 if (rhs_val == 0) {
388 goto zero_division;
389 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000390 lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
Rachel Dowdall56402792014-03-22 20:19:24 +0000391 break;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300392
Damien Georgefb510b32014-06-01 13:32:54 +0100393 #if MICROPY_PY_BUILTINS_FLOAT
Damien Georged17926d2014-03-30 13:35:08 +0100394 case MP_BINARY_OP_TRUE_DIVIDE:
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300395 case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
396 if (rhs_val == 0) {
Damien George70f33cd2014-04-02 17:06:05 +0100397 goto zero_division;
Paul Sokolovsky6ded55a2014-03-31 02:20:00 +0300398 }
399 return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000400 #endif
Damiena3dcd9e2013-12-17 21:35:38 +0000401
Damien Georged17926d2014-03-30 13:35:08 +0100402 case MP_BINARY_OP_MODULO:
Damien Georgeecf5b772014-04-04 11:13:51 +0000403 case MP_BINARY_OP_INPLACE_MODULO: {
404 lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
Rachel Dowdallcde86312014-03-22 17:29:27 +0000405 break;
406 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000407
Damien Georged17926d2014-03-30 13:35:08 +0100408 case MP_BINARY_OP_POWER:
409 case MP_BINARY_OP_INPLACE_POWER:
Damien George9d68e9c2014-03-12 15:38:15 +0000410 if (rhs_val < 0) {
Damien Georgefb510b32014-06-01 13:32:54 +0100411 #if MICROPY_PY_BUILTINS_FLOAT
Damien George9d68e9c2014-03-12 15:38:15 +0000412 lhs = mp_obj_new_float(lhs_val);
413 goto generic_binary_op;
414 #else
Damien Georgeea13f402014-04-05 18:32:08 +0100415 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative power with no float support"));
Damien George9d68e9c2014-03-12 15:38:15 +0000416 #endif
417 } else {
Damien George40f3c022014-07-03 13:25:24 +0100418 mp_int_t ans = 1;
Damien George9d68e9c2014-03-12 15:38:15 +0000419 while (rhs_val > 0) {
420 if (rhs_val & 1) {
Damien Georgeecf5b772014-04-04 11:13:51 +0000421 if (mp_small_int_mul_overflow(ans, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100422 goto power_overflow;
423 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000424 ans *= lhs_val;
Damien George9d68e9c2014-03-12 15:38:15 +0000425 }
Damien George5bf565e2014-04-04 00:16:32 +0100426 if (rhs_val == 1) {
427 break;
428 }
Damien George9d68e9c2014-03-12 15:38:15 +0000429 rhs_val /= 2;
Damien Georgeecf5b772014-04-04 11:13:51 +0000430 if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
Damien George5bf565e2014-04-04 00:16:32 +0100431 goto power_overflow;
432 }
Damien Georgeecf5b772014-04-04 11:13:51 +0000433 lhs_val *= lhs_val;
Damien George1a9951d2014-01-06 22:13:00 +0000434 }
Damien George9d68e9c2014-03-12 15:38:15 +0000435 lhs_val = ans;
Damiena3dcd9e2013-12-17 21:35:38 +0000436 }
Damien George1a9951d2014-01-06 22:13:00 +0000437 break;
Damien George5bf565e2014-04-04 00:16:32 +0100438
439 power_overflow:
440 // use higher precision
441 lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
442 goto generic_binary_op;
443
Damien Georgec5029bc2015-06-13 22:00:10 +0100444 case MP_BINARY_OP_DIVMOD: {
445 if (rhs_val == 0) {
446 goto zero_division;
447 }
448 // to reduce stack usage we don't pass a temp array of the 2 items
449 mp_obj_tuple_t *tuple = mp_obj_new_tuple(2, NULL);
450 tuple->items[0] = MP_OBJ_NEW_SMALL_INT(mp_small_int_floor_divide(lhs_val, rhs_val));
451 tuple->items[1] = MP_OBJ_NEW_SMALL_INT(mp_small_int_modulo(lhs_val, rhs_val));
452 return tuple;
453 }
454
Damien Georged17926d2014-03-30 13:35:08 +0100455 case MP_BINARY_OP_LESS: return MP_BOOL(lhs_val < rhs_val); break;
456 case MP_BINARY_OP_MORE: return MP_BOOL(lhs_val > rhs_val); break;
457 case MP_BINARY_OP_LESS_EQUAL: return MP_BOOL(lhs_val <= rhs_val); break;
458 case MP_BINARY_OP_MORE_EQUAL: return MP_BOOL(lhs_val >= rhs_val); break;
Damiena3dcd9e2013-12-17 21:35:38 +0000459
Damien George8bcb9862014-04-17 16:26:50 +0100460 default:
461 goto unsupported_op;
Damien George1a9951d2014-01-06 22:13:00 +0000462 }
Paul Sokolovsky757ac812014-01-12 17:06:25 +0200463 // TODO: We just should make mp_obj_new_int() inline and use that
Damien Georged1e355e2014-05-28 14:51:12 +0100464 if (MP_SMALL_INT_FITS(lhs_val)) {
Damien George1a9951d2014-01-06 22:13:00 +0000465 return MP_OBJ_NEW_SMALL_INT(lhs_val);
Damien George9d68e9c2014-03-12 15:38:15 +0000466 } else {
467 return mp_obj_new_int(lhs_val);
Damien George1a9951d2014-01-06 22:13:00 +0000468 }
Damien Georgefb510b32014-06-01 13:32:54 +0100469#if MICROPY_PY_BUILTINS_FLOAT
Damien George0c36da02014-03-08 15:24:39 +0000470 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_float)) {
Damien Georgeae491052014-04-10 20:08:11 +0100471 mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
472 if (res == MP_OBJ_NULL) {
473 goto unsupported_op;
474 } else {
475 return res;
476 }
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300477#if MICROPY_PY_BUILTINS_COMPLEX
Damien George0c36da02014-03-08 15:24:39 +0000478 } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
Damien Georgeae491052014-04-10 20:08:11 +0100479 mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
480 if (res == MP_OBJ_NULL) {
481 goto unsupported_op;
482 } else {
483 return res;
484 }
Damien George3f759b72014-01-31 00:42:12 +0000485#endif
Paul Sokolovsky3b6f7b92014-06-20 01:48:35 +0300486#endif
Damien429d7192013-10-04 19:53:11 +0100487 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000488 }
John R. Lentonb8698fc2014-01-11 00:58:59 +0000489
Damien George9aa2a522014-02-01 23:04:09 +0000490 /* deal with `in`
John R. Lentonc1bef212014-01-11 12:39:33 +0000491 *
492 * NOTE `a in b` is `b.__contains__(a)`, hence why the generic dispatch
Damien George48697f12014-02-01 23:32:29 +0000493 * needs to go below with swapped arguments
John R. Lentonc1bef212014-01-11 12:39:33 +0000494 */
Damien Georged17926d2014-03-30 13:35:08 +0100495 if (op == MP_BINARY_OP_IN) {
Damien George5fa93b62014-01-22 14:35:10 +0000496 mp_obj_type_t *type = mp_obj_get_type(rhs);
497 if (type->binary_op != NULL) {
498 mp_obj_t res = type->binary_op(op, rhs, lhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100499 if (res != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000500 return res;
501 }
502 }
503 if (type->getiter != NULL) {
504 /* second attempt, walk the iterator */
Damien Georged17926d2014-03-30 13:35:08 +0100505 mp_obj_t iter = mp_getiter(rhs);
Damien George3aa09f52014-10-23 12:06:53 +0100506 mp_obj_t next;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100507 while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
Damien George5fa93b62014-01-22 14:35:10 +0000508 if (mp_obj_equal(next, lhs)) {
Damien George9aa2a522014-02-01 23:04:09 +0000509 return mp_const_true;
John R. Lentonb8698fc2014-01-11 00:58:59 +0000510 }
Damien7410e442013-11-02 19:47:57 +0000511 }
Damien George9aa2a522014-02-01 23:04:09 +0000512 return mp_const_false;
Damien7410e442013-11-02 19:47:57 +0000513 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000514
Damien George1e9a92f2014-11-06 17:36:16 +0000515 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
516 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
517 "object not iterable"));
518 } else {
519 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
520 "'%s' object is not iterable", mp_obj_get_type_str(rhs)));
521 }
John R. Lentonc1bef212014-01-11 12:39:33 +0000522 }
523
Damien George5fa93b62014-01-22 14:35:10 +0000524 // generic binary_op supplied by type
Damien George9d68e9c2014-03-12 15:38:15 +0000525 mp_obj_type_t *type;
526generic_binary_op:
527 type = mp_obj_get_type(lhs);
Damien George5fa93b62014-01-22 14:35:10 +0000528 if (type->binary_op != NULL) {
529 mp_obj_t result = type->binary_op(op, lhs, rhs);
Damien George6ac5dce2014-05-21 19:42:43 +0100530 if (result != MP_OBJ_NULL) {
Damien George5fa93b62014-01-22 14:35:10 +0000531 return result;
John R. Lentonc1bef212014-01-11 12:39:33 +0000532 }
Damien429d7192013-10-04 19:53:11 +0100533 }
Damiend99b0522013-12-21 18:17:45 +0000534
Damien George5fa93b62014-01-22 14:35:10 +0000535 // TODO implement dispatch for reverse binary ops
536
Damien Georgeae491052014-04-10 20:08:11 +0100537unsupported_op:
Damien George1e9a92f2014-11-06 17:36:16 +0000538 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
539 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
540 "unsupported type for operator"));
541 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000542 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
Damien George044c4732015-04-11 13:03:37 +0100543 "unsupported types for %q: '%s', '%s'",
544 mp_binary_op_method_name[op], mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs)));
Damien George1e9a92f2014-11-06 17:36:16 +0000545 }
Damien George70f33cd2014-04-02 17:06:05 +0100546
547zero_division:
Damien Georgeea13f402014-04-05 18:32:08 +0100548 nlr_raise(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero"));
Damien429d7192013-10-04 19:53:11 +0100549}
550
Damien Georged17926d2014-03-30 13:35:08 +0100551mp_obj_t mp_call_function_0(mp_obj_t fun) {
552 return mp_call_function_n_kw(fun, 0, 0, NULL);
Damieneb19efb2013-10-10 22:06:54 +0100553}
554
Damien Georged17926d2014-03-30 13:35:08 +0100555mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
556 return mp_call_function_n_kw(fun, 1, 0, &arg);
Damieneb19efb2013-10-10 22:06:54 +0100557}
558
Damien Georged17926d2014-03-30 13:35:08 +0100559mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
Damiend99b0522013-12-21 18:17:45 +0000560 mp_obj_t args[2];
Damien George20006db2014-01-18 14:10:48 +0000561 args[0] = arg1;
562 args[1] = arg2;
Damien Georged17926d2014-03-30 13:35:08 +0100563 return mp_call_function_n_kw(fun, 2, 0, args);
Damieneb19efb2013-10-10 22:06:54 +0100564}
565
Damien George20006db2014-01-18 14:10:48 +0000566// args contains, eg: arg0 arg1 key0 value0 key1 value1
Damien George4abff752014-08-30 14:59:21 +0100567mp_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 +0000568 // TODO improve this: fun object can specify its type and we parse here the arguments,
569 // passing to the function arrays of fixed and keyword arguments
Damieneb19efb2013-10-10 22:06:54 +0100570
Damien Georgeeaaebf32014-09-23 10:59:05 +0100571 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 +0000572
Damien George8b56beb2014-01-31 23:49:49 +0000573 // get the type
574 mp_obj_type_t *type = mp_obj_get_type(fun_in);
575
576 // do the call
577 if (type->call != NULL) {
Damien George3f522622014-06-03 13:40:16 +0100578 return type->call(fun_in, n_args, n_kw, args);
John R. Lenton9c83ec02014-01-07 23:06:46 +0000579 }
Paul Sokolovsky755565d2014-04-25 21:15:16 +0300580
Damien George1e9a92f2014-11-06 17:36:16 +0000581 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
582 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
583 "object not callable"));
584 } else {
585 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
586 "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
587 }
Damien86c7fc72013-11-26 15:16:41 +0000588}
589
Damien George20006db2014-01-18 14:10:48 +0000590// 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)
591// if n_args==0 and n_kw==0 then there are only fun and self/NULL
Damien George4abff752014-08-30 14:59:21 +0100592mp_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 +0100593 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 +0000594 int adjust = (args[1] == NULL) ? 0 : 1;
Damien Georged17926d2014-03-30 13:35:08 +0100595 return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
Damien86c7fc72013-11-26 15:16:41 +0000596}
597
Damien George12a5e172015-04-01 23:31:30 +0100598// This function only needs to be exposed externally when in stackless mode.
599#if !MICROPY_STACKLESS
600STATIC
601#endif
602void mp_call_prepare_args_n_kw_var(bool have_self, mp_uint_t n_args_n_kw, const mp_obj_t *args, mp_call_args_t *out_args) {
Damien George230fec72014-03-30 21:21:24 +0100603 mp_obj_t fun = *args++;
604 mp_obj_t self = MP_OBJ_NULL;
605 if (have_self) {
606 self = *args++; // may be MP_OBJ_NULL
607 }
608 uint n_args = n_args_n_kw & 0xff;
609 uint n_kw = (n_args_n_kw >> 8) & 0xff;
Paul Sokolovskye104acd2015-03-03 21:37:37 +0200610 mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // may be MP_OBJ_NULL
611 mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // may be MP_OBJ_NULL
Damien George230fec72014-03-30 21:21:24 +0100612
613 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);
614
615 // We need to create the following array of objects:
616 // args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
617 // TODO: optimize one day to avoid constructing new arg array? Will be hard.
618
619 // The new args array
620 mp_obj_t *args2;
621 uint args2_alloc;
622 uint args2_len = 0;
623
624 // Try to get a hint for the size of the kw_dict
625 uint kw_dict_len = 0;
626 if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
627 kw_dict_len = mp_obj_dict_len(kw_dict);
628 }
629
630 // Extract the pos_seq sequence to the new args array.
631 // Note that it can be arbitrary iterator.
632 if (pos_seq == MP_OBJ_NULL) {
633 // no sequence
634
635 // allocate memory for the new array of args
636 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
637 args2 = m_new(mp_obj_t, args2_alloc);
638
639 // copy the self
640 if (self != MP_OBJ_NULL) {
641 args2[args2_len++] = self;
642 }
643
644 // copy the fixed pos args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300645 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100646 args2_len += n_args;
647
648 } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
649 // optimise the case of a tuple and list
650
651 // get the items
Damien George9c4cbe22014-08-30 14:04:14 +0100652 mp_uint_t len;
Damien George230fec72014-03-30 21:21:24 +0100653 mp_obj_t *items;
654 mp_obj_get_array(pos_seq, &len, &items);
655
656 // allocate memory for the new array of args
657 args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
658 args2 = m_new(mp_obj_t, args2_alloc);
659
660 // copy the self
661 if (self != MP_OBJ_NULL) {
662 args2[args2_len++] = self;
663 }
664
665 // copy the fixed and variable position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300666 mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100667 args2_len += n_args + len;
668
669 } else {
670 // generic iterator
671
672 // allocate memory for the new array of args
673 args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
674 args2 = m_new(mp_obj_t, args2_alloc);
675
676 // copy the self
677 if (self != MP_OBJ_NULL) {
678 args2[args2_len++] = self;
679 }
680
681 // copy the fixed position args
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300682 mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100683
684 // extract the variable position args from the iterator
685 mp_obj_t iterable = mp_getiter(pos_seq);
686 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100687 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100688 if (args2_len >= args2_alloc) {
689 args2 = m_renew(mp_obj_t, args2, args2_alloc, args2_alloc * 2);
690 args2_alloc *= 2;
691 }
692 args2[args2_len++] = item;
693 }
694 }
695
696 // The size of the args2 array now is the number of positional args.
697 uint pos_args_len = args2_len;
698
699 // Copy the fixed kw args.
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300700 mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
Damien George230fec72014-03-30 21:21:24 +0100701 args2_len += 2 * n_kw;
702
703 // Extract (key,value) pairs from kw_dict dictionary and append to args2.
704 // Note that it can be arbitrary iterator.
705 if (kw_dict == MP_OBJ_NULL) {
706 // pass
707 } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
708 // dictionary
709 mp_map_t *map = mp_obj_dict_get_map(kw_dict);
710 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 +0000711 for (mp_uint_t i = 0; i < map->alloc; i++) {
712 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Damien George230fec72014-03-30 21:21:24 +0100713 args2[args2_len++] = map->table[i].key;
714 args2[args2_len++] = map->table[i].value;
715 }
716 }
717 } else {
718 // generic mapping
719 // TODO is calling 'items' on the mapping the correct thing to do here?
720 mp_obj_t dest[2];
721 mp_load_method(kw_dict, MP_QSTR_items, dest);
722 mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest));
723 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100724 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George230fec72014-03-30 21:21:24 +0100725 if (args2_len + 1 >= args2_alloc) {
726 uint new_alloc = args2_alloc * 2;
727 if (new_alloc < 4) {
728 new_alloc = 4;
729 }
730 args2 = m_renew(mp_obj_t, args2, args2_alloc, new_alloc);
731 args2_alloc = new_alloc;
732 }
733 mp_obj_t *items;
734 mp_obj_get_array_fixed_n(item, 2, &items);
735 args2[args2_len++] = items[0];
736 args2[args2_len++] = items[1];
737 }
738 }
739
Paul Sokolovskye6c6fe32015-03-28 01:14:45 +0200740 out_args->fun = fun;
741 out_args->args = args2;
742 out_args->n_args = pos_args_len;
743 out_args->n_kw = (args2_len - pos_args_len) / 2;
744 out_args->n_alloc = args2_alloc;
745}
746
747mp_obj_t mp_call_method_n_kw_var(bool have_self, mp_uint_t n_args_n_kw, const mp_obj_t *args) {
Damien George12a5e172015-04-01 23:31:30 +0100748 mp_call_args_t out_args;
Paul Sokolovskye6c6fe32015-03-28 01:14:45 +0200749 mp_call_prepare_args_n_kw_var(have_self, n_args_n_kw, args, &out_args);
750
751 mp_obj_t res = mp_call_function_n_kw(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args);
752 m_del(mp_obj_t, out_args.args, out_args.n_alloc);
Damien George230fec72014-03-30 21:21:24 +0100753
754 return res;
755}
756
Damien George932bf1c2014-01-18 23:42:49 +0000757// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100758void mp_unpack_sequence(mp_obj_t seq_in, mp_uint_t num, mp_obj_t *items) {
Damien George9c4cbe22014-08-30 14:04:14 +0100759 mp_uint_t seq_len;
Damien George3e1a5c12014-03-29 13:43:38 +0000760 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 +0000761 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000762 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000763 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
764 } else {
765 mp_obj_list_get(seq_in, &seq_len, &seq_items);
Damien86c7fc72013-11-26 15:16:41 +0000766 }
Damiend99b0522013-12-21 18:17:45 +0000767 if (seq_len < num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200768 goto too_short;
Damiend99b0522013-12-21 18:17:45 +0000769 } else if (seq_len > num) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200770 goto too_long;
Damiend99b0522013-12-21 18:17:45 +0000771 }
Damien George4abff752014-08-30 14:59:21 +0100772 for (mp_uint_t i = 0; i < num; i++) {
Damien George932bf1c2014-01-18 23:42:49 +0000773 items[i] = seq_items[num - 1 - i];
774 }
Damien86c7fc72013-11-26 15:16:41 +0000775 } else {
Damien Georged17926d2014-03-30 13:35:08 +0100776 mp_obj_t iterable = mp_getiter(seq_in);
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200777
778 for (seq_len = 0; seq_len < num; seq_len++) {
Damien Georged17926d2014-03-30 13:35:08 +0100779 mp_obj_t el = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100780 if (el == MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200781 goto too_short;
782 }
783 items[num - 1 - seq_len] = el;
784 }
Damien Georgeea8d06c2014-04-17 23:19:36 +0100785 if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200786 goto too_long;
787 }
Damien86c7fc72013-11-26 15:16:41 +0000788 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200789 return;
790
791too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000792 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
793 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
794 "wrong number of values to unpack"));
795 } else {
796 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
797 "need more than %d values to unpack", seq_len));
798 }
Paul Sokolovskyedbdf712014-02-02 00:54:06 +0200799too_long:
Damien George1e9a92f2014-11-06 17:36:16 +0000800 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
801 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
802 "wrong number of values to unpack"));
803 } else {
804 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
805 "too many values to unpack (expected %d)", num));
806 }
Damien86c7fc72013-11-26 15:16:41 +0000807}
808
Damien George495d7812014-04-08 17:51:47 +0100809// unpacked items are stored in reverse order into the array pointed to by items
Damien George4abff752014-08-30 14:59:21 +0100810void mp_unpack_ex(mp_obj_t seq_in, mp_uint_t num_in, mp_obj_t *items) {
811 mp_uint_t num_left = num_in & 0xff;
812 mp_uint_t num_right = (num_in >> 8) & 0xff;
Damien Georgeeaaebf32014-09-23 10:59:05 +0100813 DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
Damien George9c4cbe22014-08-30 14:04:14 +0100814 mp_uint_t seq_len;
Damien George495d7812014-04-08 17:51:47 +0100815 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
816 mp_obj_t *seq_items;
817 if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple)) {
818 mp_obj_tuple_get(seq_in, &seq_len, &seq_items);
819 } else {
820 if (num_left == 0 && num_right == 0) {
821 // *a, = b # sets a to b if b is a list
822 items[0] = seq_in;
823 return;
824 }
825 mp_obj_list_get(seq_in, &seq_len, &seq_items);
826 }
827 if (seq_len < num_left + num_right) {
828 goto too_short;
829 }
Damien George4abff752014-08-30 14:59:21 +0100830 for (mp_uint_t i = 0; i < num_right; i++) {
Damien George495d7812014-04-08 17:51:47 +0100831 items[i] = seq_items[seq_len - 1 - i];
832 }
833 items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
Damien George4abff752014-08-30 14:59:21 +0100834 for (mp_uint_t i = 0; i < num_left; i++) {
Damien George495d7812014-04-08 17:51:47 +0100835 items[num_right + 1 + i] = seq_items[num_left - 1 - i];
836 }
837 } else {
838 // Generic iterable; this gets a bit messy: we unpack known left length to the
839 // items destination array, then the rest to a dynamically created list. Once the
840 // iterable is exhausted, we take from this list for the right part of the items.
841 // TODO Improve to waste less memory in the dynamically created list.
842 mp_obj_t iterable = mp_getiter(seq_in);
843 mp_obj_t item;
844 for (seq_len = 0; seq_len < num_left; seq_len++) {
845 item = mp_iternext(iterable);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100846 if (item == MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100847 goto too_short;
848 }
849 items[num_left + num_right + 1 - 1 - seq_len] = item;
850 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100851 mp_obj_list_t *rest = mp_obj_new_list(0, NULL);
Damien Georgeea8d06c2014-04-17 23:19:36 +0100852 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George495d7812014-04-08 17:51:47 +0100853 mp_obj_list_append(rest, item);
854 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100855 if (rest->len < num_right) {
Damien George495d7812014-04-08 17:51:47 +0100856 goto too_short;
857 }
858 items[num_right] = rest;
Damien George4abff752014-08-30 14:59:21 +0100859 for (mp_uint_t i = 0; i < num_right; i++) {
Damien Georgeca6d75f2014-08-30 15:17:47 +0100860 items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
Damien George495d7812014-04-08 17:51:47 +0100861 }
Damien Georgeca6d75f2014-08-30 15:17:47 +0100862 mp_obj_list_set_len(rest, rest->len - num_right);
Damien George495d7812014-04-08 17:51:47 +0100863 }
864 return;
865
866too_short:
Damien George1e9a92f2014-11-06 17:36:16 +0000867 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
868 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
869 "wrong number of values to unpack"));
870 } else {
871 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
872 "need more than %d values to unpack", seq_len));
873 }
Damien George495d7812014-04-08 17:51:47 +0100874}
875
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300876mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
Damien George062478e2014-01-09 20:57:50 +0000877 DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300878 // use load_method
Damien George062478e2014-01-09 20:57:50 +0000879 mp_obj_t dest[2];
Paul Sokolovsky36dd19a2014-04-06 02:12:03 +0300880 mp_load_method(base, attr, dest);
881 if (dest[1] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +0000882 // load_method returned just a normal attribute
Damien George20006db2014-01-18 14:10:48 +0000883 return dest[0];
Damien George062478e2014-01-09 20:57:50 +0000884 } else {
885 // load_method returned a method, so build a bound method object
886 return mp_obj_new_bound_meth(dest[0], dest[1]);
Damiend99b0522013-12-21 18:17:45 +0000887 }
Damiend99b0522013-12-21 18:17:45 +0000888}
889
Damien George06593fb2015-06-19 12:49:10 +0000890#if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
891
892// The following "checked fun" type is local to the mp_convert_member_lookup
893// function, and serves to check that the first argument to a builtin function
894// has the correct type.
895
896typedef struct _mp_obj_checked_fun_t {
897 mp_obj_base_t base;
898 const mp_obj_type_t *type;
899 mp_obj_t fun;
900} mp_obj_checked_fun_t;
901
902STATIC mp_obj_t checked_fun_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
903 mp_obj_checked_fun_t *self = self_in;
904 if (n_args > 0) {
905 const mp_obj_type_t *arg0_type = mp_obj_get_type(args[0]);
906 if (arg0_type != self->type) {
907 if (MICROPY_ERROR_REPORTING != MICROPY_ERROR_REPORTING_DETAILED) {
908 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
909 "argument has wrong type"));
910 } else {
911 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
912 "argument should be a '%q' not a '%q'", self->type->name, arg0_type->name));
913 }
914 }
915 }
916 return mp_call_function_n_kw(self->fun, n_args, n_kw, args);
917}
918
919STATIC const mp_obj_type_t mp_type_checked_fun = {
920 { &mp_type_type },
921 .name = MP_QSTR_function,
922 .call = checked_fun_call,
923};
924
925STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) {
926 mp_obj_checked_fun_t *o = m_new_obj(mp_obj_checked_fun_t);
927 o->base.type = &mp_type_checked_fun;
928 o->type = type;
929 o->fun = fun;
930 return o;
931}
932
933#endif // MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
934
Damien George55b74d12015-03-21 14:21:54 +0000935// Given a member that was extracted from an instance, convert it correctly
936// and put the result in the dest[] array for a possible method call.
937// Conversion means dealing with static/class methods, callables, and values.
938// see http://docs.python.org/3/howto/descriptor.html
939void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) {
940 if (MP_OBJ_IS_TYPE(member, &mp_type_staticmethod)) {
941 // return just the function
942 dest[0] = ((mp_obj_static_class_method_t*)member)->fun;
943 } else if (MP_OBJ_IS_TYPE(member, &mp_type_classmethod)) {
944 // return a bound method, with self being the type of this object
945 dest[0] = ((mp_obj_static_class_method_t*)member)->fun;
946 dest[1] = (mp_obj_t)type;
947 } else if (MP_OBJ_IS_TYPE(member, &mp_type_type)) {
948 // Don't try to bind types (even though they're callable)
949 dest[0] = member;
950 } else if (mp_obj_is_callable(member)) {
Damien George06593fb2015-06-19 12:49:10 +0000951 #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
952 if (self == MP_OBJ_NULL && mp_obj_get_type(member) == &mp_type_fun_builtin) {
953 // we extracted a builtin method without a first argument, so we must
954 // wrap this function in a type checker
955 dest[0] = mp_obj_new_checked_fun(type, member);
956 } else
957 #endif
958 {
959 // return a bound method, with self being this object
960 dest[0] = member;
961 dest[1] = self;
962 }
Damien George55b74d12015-03-21 14:21:54 +0000963 } else {
964 // class member is a value, so just return that value
965 dest[0] = member;
966 }
967}
968
Damien George7c9c6672014-01-25 00:17:36 +0000969// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
970// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
971// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +0200972void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) {
Damien George062478e2014-01-09 20:57:50 +0000973 // clear output to indicate no attribute/method found yet
974 dest[0] = MP_OBJ_NULL;
975 dest[1] = MP_OBJ_NULL;
976
977 // get the type
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +0200978 mp_obj_type_t *type = mp_obj_get_type(obj);
Damien George062478e2014-01-09 20:57:50 +0000979
Damien Georgee44d26a2014-03-31 22:57:56 +0100980 // look for built-in names
981 if (0) {
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300982#if MICROPY_CPYTHON_COMPAT
Damien Georgee44d26a2014-03-31 22:57:56 +0100983 } else if (attr == MP_QSTR___class__) {
984 // a.__class__ is equivalent to type(a)
985 dest[0] = type;
Paul Sokolovsky6ce78c42014-03-31 20:30:08 +0300986#endif
Damien Georgee44d26a2014-03-31 22:57:56 +0100987
988 } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
989 dest[0] = (mp_obj_t)&mp_builtin_next_obj;
Paul Sokolovsky07b8dc62015-03-21 00:58:07 +0200990 dest[1] = obj;
Damien Georgee44d26a2014-03-31 22:57:56 +0100991
Damien Georgeb1bbe962015-04-01 14:10:50 +0000992 } else if (type->attr != NULL) {
Damien Georgee44d26a2014-03-31 22:57:56 +0100993 // this type can do its own load, so call it
Damien Georgeb1bbe962015-04-01 14:10:50 +0000994 type->attr(obj, attr, dest);
Damien Georgee44d26a2014-03-31 22:57:56 +0100995
996 } else if (type->locals_dict != NULL) {
997 // generic method lookup
998 // this is a lookup in the object (ie not class or type)
999 assert(MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)); // Micro Python restriction, for now
1000 mp_map_t *locals_map = mp_obj_dict_get_map(type->locals_dict);
1001 mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
1002 if (elem != NULL) {
Damien George55b74d12015-03-21 14:21:54 +00001003 mp_convert_member_lookup(obj, type, elem->value, dest);
Damiend57eba52013-11-02 23:58:14 +00001004 }
Damiena3977762013-10-09 23:10:10 +01001005 }
Damien George7c9c6672014-01-25 00:17:36 +00001006}
Damiena3977762013-10-09 23:10:10 +01001007
Damien Georged17926d2014-03-30 13:35:08 +01001008void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
Damien George7c9c6672014-01-25 00:17:36 +00001009 DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
1010
Damien Georged17926d2014-03-30 13:35:08 +01001011 mp_load_method_maybe(base, attr, dest);
Damien George7c9c6672014-01-25 00:17:36 +00001012
1013 if (dest[0] == MP_OBJ_NULL) {
Damien George062478e2014-01-09 20:57:50 +00001014 // no attribute/method called attr
Damien George1e9a92f2014-11-06 17:36:16 +00001015 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1016 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
1017 "no such attribute"));
Damien George062478e2014-01-09 20:57:50 +00001018 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001019 // following CPython, we give a more detailed error message for type objects
1020 if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
1021 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001022 "type object '%q' has no attribute '%q'",
1023 ((mp_obj_type_t*)base)->name, attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001024 } else {
1025 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001026 "'%s' object has no attribute '%q'",
1027 mp_obj_get_type_str(base), attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001028 }
Damien George062478e2014-01-09 20:57:50 +00001029 }
1030 }
Damiena3977762013-10-09 23:10:10 +01001031}
1032
Damien Georged17926d2014-03-30 13:35:08 +01001033void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
Damien5ac1b2e2013-10-18 19:58:12 +01001034 DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
Damien George062478e2014-01-09 20:57:50 +00001035 mp_obj_type_t *type = mp_obj_get_type(base);
Damien Georgeb1bbe962015-04-01 14:10:50 +00001036 if (type->attr != NULL) {
1037 mp_obj_t dest[2] = {MP_OBJ_SENTINEL, value};
1038 type->attr(base, attr, dest);
1039 if (dest[0] == MP_OBJ_NULL) {
1040 // success
Damien George062478e2014-01-09 20:57:50 +00001041 return;
1042 }
Damiena3977762013-10-09 23:10:10 +01001043 }
Damien George1e9a92f2014-11-06 17:36:16 +00001044 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1045 nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError,
1046 "no such attribute"));
1047 } else {
1048 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
Damien George044c4732015-04-11 13:03:37 +01001049 "'%s' object has no attribute '%q'",
1050 mp_obj_get_type_str(base), attr));
Damien George1e9a92f2014-11-06 17:36:16 +00001051 }
Damiena3977762013-10-09 23:10:10 +01001052}
1053
Damien Georged17926d2014-03-30 13:35:08 +01001054mp_obj_t mp_getiter(mp_obj_t o_in) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001055 assert(o_in);
Damien Georgef6532bb2015-02-15 01:10:13 +00001056
1057 // check for native getiter (corresponds to __iter__)
Damien George5fa93b62014-01-22 14:35:10 +00001058 mp_obj_type_t *type = mp_obj_get_type(o_in);
1059 if (type->getiter != NULL) {
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001060 mp_obj_t iter = type->getiter(o_in);
Damien Georgef6532bb2015-02-15 01:10:13 +00001061 if (iter != MP_OBJ_NULL) {
1062 return iter;
Paul Sokolovskyc48d6f72014-05-11 20:32:39 +03001063 }
Damien Georgef6532bb2015-02-15 01:10:13 +00001064 }
1065
1066 // check for __getitem__
1067 mp_obj_t dest[2];
1068 mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
1069 if (dest[0] != MP_OBJ_NULL) {
1070 // __getitem__ exists, create and return an iterator
1071 return mp_obj_new_getitem_iter(dest);
1072 }
1073
1074 // object not iterable
1075 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1076 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1077 "object not iterable"));
Damience89a212013-10-15 22:25:17 +01001078 } else {
Damien Georgef6532bb2015-02-15 01:10:13 +00001079 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1080 "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
Damience89a212013-10-15 22:25:17 +01001081 }
1082}
1083
Damien Georgeea8d06c2014-04-17 23:19:36 +01001084// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
Damien George66eaf842014-03-26 19:27:58 +00001085// may also raise StopIteration()
Damien Georged17926d2014-03-30 13:35:08 +01001086mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001087 mp_obj_type_t *type = mp_obj_get_type(o_in);
1088 if (type->iternext != NULL) {
1089 return type->iternext(o_in);
Damience89a212013-10-15 22:25:17 +01001090 } else {
Damien George9e6e9352014-03-26 18:37:06 +00001091 // check for __next__ method
1092 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001093 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001094 if (dest[0] != MP_OBJ_NULL) {
1095 // __next__ exists, call it and return its result
Damien Georged17926d2014-03-30 13:35:08 +01001096 return mp_call_method_n_kw(0, 0, dest);
Damien George9e6e9352014-03-26 18:37:06 +00001097 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001098 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1099 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1100 "object not an iterator"));
1101 } else {
1102 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1103 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1104 }
Damien George9e6e9352014-03-26 18:37:06 +00001105 }
Damien Georgec5966122014-02-15 16:10:44 +00001106 }
1107}
1108
Damien Georgeea8d06c2014-04-17 23:19:36 +01001109// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
Damien George66eaf842014-03-26 19:27:58 +00001110// may raise other exceptions
Damien Georged17926d2014-03-30 13:35:08 +01001111mp_obj_t mp_iternext(mp_obj_t o_in) {
Damien George953c23b2015-06-03 22:19:41 +01001112 MP_STACK_CHECK(); // enumerate, filter, map and zip can recursively call mp_iternext
Damien George66eaf842014-03-26 19:27:58 +00001113 mp_obj_type_t *type = mp_obj_get_type(o_in);
1114 if (type->iternext != NULL) {
1115 return type->iternext(o_in);
1116 } else {
1117 // check for __next__ method
1118 mp_obj_t dest[2];
Damien Georged17926d2014-03-30 13:35:08 +01001119 mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
Damien George66eaf842014-03-26 19:27:58 +00001120 if (dest[0] != MP_OBJ_NULL) {
1121 // __next__ exists, call it and return its result
1122 nlr_buf_t nlr;
1123 if (nlr_push(&nlr) == 0) {
Damien Georged17926d2014-03-30 13:35:08 +01001124 mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
Damien George66eaf842014-03-26 19:27:58 +00001125 nlr_pop();
1126 return ret;
1127 } else {
1128 if (mp_obj_is_subclass_fast(mp_obj_get_type(nlr.ret_val), &mp_type_StopIteration)) {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001129 return MP_OBJ_STOP_ITERATION;
Damien George66eaf842014-03-26 19:27:58 +00001130 } else {
Damien Georgeea13f402014-04-05 18:32:08 +01001131 nlr_raise(nlr.ret_val);
Damien George66eaf842014-03-26 19:27:58 +00001132 }
1133 }
1134 } else {
Damien George1e9a92f2014-11-06 17:36:16 +00001135 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1136 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1137 "object not an iterator"));
1138 } else {
1139 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1140 "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
1141 }
Damien George66eaf842014-03-26 19:27:58 +00001142 }
1143 }
1144}
1145
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001146// TODO: Unclear what to do with StopIterarion exception here.
1147mp_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 +03001148 assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001149 mp_obj_type_t *type = mp_obj_get_type(self_in);
1150
1151 if (type == &mp_type_gen_instance) {
1152 return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
1153 }
1154
1155 if (type->iternext != NULL && send_value == mp_const_none) {
1156 mp_obj_t ret = type->iternext(self_in);
Paul Sokolovsky4ed7b7f2015-05-10 00:41:34 +03001157 if (ret != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001158 *ret_val = ret;
1159 return MP_VM_RETURN_YIELD;
1160 } else {
1161 // Emulate raise StopIteration()
1162 // Special case, handled in vm.c
1163 *ret_val = MP_OBJ_NULL;
1164 return MP_VM_RETURN_NORMAL;
1165 }
1166 }
1167
1168 mp_obj_t dest[3]; // Reserve slot for send() arg
1169
1170 if (send_value == mp_const_none) {
1171 mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
1172 if (dest[0] != MP_OBJ_NULL) {
1173 *ret_val = mp_call_method_n_kw(0, 0, dest);
1174 return MP_VM_RETURN_YIELD;
1175 }
1176 }
1177
1178 if (send_value != MP_OBJ_NULL) {
1179 mp_load_method(self_in, MP_QSTR_send, dest);
1180 dest[2] = send_value;
1181 *ret_val = mp_call_method_n_kw(1, 0, dest);
1182 return MP_VM_RETURN_YIELD;
1183 }
1184
1185 if (throw_value != MP_OBJ_NULL) {
1186 if (mp_obj_is_subclass_fast(mp_obj_get_type(throw_value), &mp_type_GeneratorExit)) {
1187 mp_load_method_maybe(self_in, MP_QSTR_close, dest);
1188 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovsky4a60cac2015-05-10 02:39:45 +03001189 // TODO: Exceptions raised in close() are not propagated,
1190 // printed to sys.stderr
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001191 *ret_val = mp_call_method_n_kw(0, 0, dest);
1192 // We assume one can't "yield" from close()
1193 return MP_VM_RETURN_NORMAL;
1194 }
1195 }
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001196 mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
1197 if (dest[0] != MP_OBJ_NULL) {
1198 *ret_val = mp_call_method_n_kw(1, 0, &throw_value);
1199 // If .throw() method returned, we assume it's value to yield
Damien Georgeea13f402014-04-05 18:32:08 +01001200 // - any exception would be thrown with nlr_raise().
Paul Sokolovskya2109d92014-03-31 04:14:30 +03001201 return MP_VM_RETURN_YIELD;
1202 }
1203 // If there's nowhere to throw exception into, then we assume that object
1204 // is just incapable to handle it, so any exception thrown into it
1205 // will be propagated up. This behavior is approved by test_pep380.py
1206 // test_delegation_of_close_to_non_generator(),
1207 // test_delegating_throw_to_non_generator()
1208 *ret_val = throw_value;
1209 return MP_VM_RETURN_EXCEPTION;
Paul Sokolovskyf39d3b92014-03-30 23:14:55 +03001210 }
1211
1212 assert(0);
1213 return MP_VM_RETURN_NORMAL; // Should be unreachable
1214}
1215
Damien Georged17926d2014-03-30 13:35:08 +01001216mp_obj_t mp_make_raise_obj(mp_obj_t o) {
Damien Georgec5966122014-02-15 16:10:44 +00001217 DEBUG_printf("raise %p\n", o);
1218 if (mp_obj_is_exception_type(o)) {
1219 // o is an exception type (it is derived from BaseException (or is BaseException))
1220 // create and return a new exception instance by calling o
Damien George22a08652014-02-15 21:05:25 +00001221 // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
1222 // could have const instances in ROM which we return here instead
Damien Georged17926d2014-03-30 13:35:08 +01001223 return mp_call_function_n_kw(o, 0, 0, NULL);
Damien Georgec5966122014-02-15 16:10:44 +00001224 } else if (mp_obj_is_exception_instance(o)) {
1225 // o is an instance of an exception, so use it as the exception
1226 return o;
1227 } else {
1228 // o cannot be used as an exception, so return a type error (which will be raised by the caller)
1229 return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
Damience89a212013-10-15 22:25:17 +01001230 }
1231}
1232
Damien Georged17926d2014-03-30 13:35:08 +01001233mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
Damien George64131f32014-02-06 20:31:44 +00001234 DEBUG_printf("import name %s\n", qstr_str(name));
1235
Damiendb4c3612013-12-10 17:27:24 +00001236 // build args array
Damiend99b0522013-12-21 18:17:45 +00001237 mp_obj_t args[5];
Damien George5fa93b62014-01-22 14:35:10 +00001238 args[0] = MP_OBJ_NEW_QSTR(name);
Damiend99b0522013-12-21 18:17:45 +00001239 args[1] = mp_const_none; // TODO should be globals
1240 args[2] = mp_const_none; // TODO should be locals
Damiendb4c3612013-12-10 17:27:24 +00001241 args[3] = fromlist;
1242 args[4] = level; // must be 0; we don't yet support other values
1243
1244 // TODO lookup __import__ and call that instead of going straight to builtin implementation
Damiend99b0522013-12-21 18:17:45 +00001245 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001246}
1247
Damien Georged17926d2014-03-30 13:35:08 +01001248mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
Damien George64131f32014-02-06 20:31:44 +00001249 DEBUG_printf("import from %p %s\n", module, qstr_str(name));
1250
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001251 mp_obj_t dest[2];
1252
1253 mp_load_method_maybe(module, name, dest);
1254
1255 if (dest[1] != MP_OBJ_NULL) {
1256 // Hopefully we can't import bound method from an object
1257import_error:
Damien George044c4732015-04-11 13:03:37 +01001258 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %q", name));
Damiendb4c3612013-12-10 17:27:24 +00001259 }
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001260
1261 if (dest[0] != MP_OBJ_NULL) {
1262 return dest[0];
1263 }
1264
1265 // See if it's a package, then can try FS import
Paul Sokolovskye5a37592014-10-25 21:04:13 +03001266 if (!mp_obj_is_package(module)) {
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001267 goto import_error;
1268 }
1269
1270 mp_load_method_maybe(module, MP_QSTR___name__, dest);
Damien Georged182b982014-08-30 14:19:41 +01001271 mp_uint_t pkg_name_len;
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001272 const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
1273
stijn01d6be42014-05-05 12:18:27 +02001274 const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
1275 char *dot_name = alloca(dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001276 memcpy(dot_name, pkg_name, pkg_name_len);
1277 dot_name[pkg_name_len] = '.';
1278 memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
stijn01d6be42014-05-05 12:18:27 +02001279 qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001280
1281 mp_obj_t args[5];
1282 args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
1283 args[1] = mp_const_none; // TODO should be globals
1284 args[2] = mp_const_none; // TODO should be locals
1285 args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
Paul Sokolovsky69f18672014-04-12 02:47:46 +03001286 args[4] = MP_OBJ_NEW_SMALL_INT(0);
Paul Sokolovskyaf620ab2014-04-12 00:15:19 +03001287
1288 // TODO lookup __import__ and call that instead of going straight to builtin implementation
1289 return mp_builtin___import__(5, args);
Damiendb4c3612013-12-10 17:27:24 +00001290}
1291
Damien Georged17926d2014-03-30 13:35:08 +01001292void mp_import_all(mp_obj_t module) {
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001293 DEBUG_printf("import all %p\n", module);
1294
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001295 // TODO: Support __all__
Damien George8b0535e2014-04-05 21:53:54 +01001296 mp_map_t *map = mp_obj_dict_get_map(mp_obj_module_get_globals(module));
Damien Georgeb063b9b2014-12-21 16:24:09 +00001297 for (mp_uint_t i = 0; i < map->alloc; i++) {
Damien George8b0535e2014-04-05 21:53:54 +01001298 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Paul Sokolovsky599bbc12014-04-18 04:11:19 +03001299 qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
1300 if (*qstr_str(name) != '_') {
1301 mp_store_name(name, map->table[i].value);
1302 }
Paul Sokolovskyda1ce932014-02-14 00:22:06 +02001303 }
1304 }
1305}
1306
Damien Georgec4d08682014-10-05 20:13:34 +01001307// this is implemented in this file so it can optimise access to locals/globals
1308mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_input_kind, mp_obj_dict_t *globals, mp_obj_dict_t *locals) {
Damien George0bfc7632015-02-07 18:33:58 +00001309 // save context
1310 mp_obj_dict_t *volatile old_globals = mp_globals_get();
1311 mp_obj_dict_t *volatile old_locals = mp_locals_get();
Damien Georgec4d08682014-10-05 20:13:34 +01001312
Damien George0bfc7632015-02-07 18:33:58 +00001313 // set new context
Damien Georgec4d08682014-10-05 20:13:34 +01001314 mp_globals_set(globals);
1315 mp_locals_set(locals);
1316
Damien Georgec4d08682014-10-05 20:13:34 +01001317 nlr_buf_t nlr;
1318 if (nlr_push(&nlr) == 0) {
Damien George0bfc7632015-02-07 18:33:58 +00001319 qstr source_name = lex->source_name;
1320 mp_parse_node_t pn = mp_parse(lex, parse_input_kind);
1321 mp_obj_t module_fun = mp_compile(pn, source_name, MP_EMIT_OPT_NONE, false);
1322
1323 mp_obj_t ret;
1324 if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
1325 // for compile only, return value is the module function
1326 ret = module_fun;
1327 } else {
1328 // execute module function and get return value
1329 ret = mp_call_function_0(module_fun);
1330 }
1331
1332 // finish nlr block, restore context and return value
Damien Georgec4d08682014-10-05 20:13:34 +01001333 nlr_pop();
1334 mp_globals_set(old_globals);
1335 mp_locals_set(old_locals);
1336 return ret;
1337 } else {
1338 // exception; restore context and re-raise same exception
1339 mp_globals_set(old_globals);
1340 mp_locals_set(old_locals);
1341 nlr_raise(nlr.ret_val);
1342 }
1343}
1344
Damien Georgeb0261342014-09-23 18:10:17 +01001345void *m_malloc_fail(size_t num_bytes) {
1346 DEBUG_printf("memory allocation failed, allocating " UINT_FMT " bytes\n", num_bytes);
Damien George40914452014-10-09 16:44:43 +01001347 if (0) {
1348 // dummy
1349 #if MICROPY_ENABLE_GC
1350 } else if (gc_is_locked()) {
1351 nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001352 "memory allocation failed, heap is locked"));
Damien George40914452014-10-09 16:44:43 +01001353 #endif
Dave Hylands3556e452014-10-07 00:50:20 -07001354 } else {
Damien George40914452014-10-09 16:44:43 +01001355 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
Dave Hylands3556e452014-10-07 00:50:20 -07001356 "memory allocation failed, allocating " UINT_FMT " bytes", num_bytes));
1357 }
Damien George6902eed2014-04-04 10:52:59 +00001358}
1359
Paul Sokolovsky7e4a2b02014-06-07 23:22:41 +03001360NORETURN void mp_not_implemented(const char *msg) {
1361 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, msg));
1362}