runtime.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. /*
  2. * This file is part of the MicroPython 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. #include <stdio.h>
  27. #include <string.h>
  28. #include <assert.h>
  29. #include "py/parsenum.h"
  30. #include "py/compile.h"
  31. #include "py/objstr.h"
  32. #include "py/objtuple.h"
  33. #include "py/objlist.h"
  34. #include "py/objmodule.h"
  35. #include "py/objgenerator.h"
  36. #include "py/smallint.h"
  37. #include "py/runtime.h"
  38. #include "py/builtin.h"
  39. #include "py/stackctrl.h"
  40. #include "py/gc.h"
  41. #if MICROPY_DEBUG_VERBOSE // print debugging info
  42. #define DEBUG_PRINT (1)
  43. #define DEBUG_printf DEBUG_printf
  44. #define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
  45. #else // don't print debugging info
  46. #define DEBUG_printf(...) (void)0
  47. #define DEBUG_OP_printf(...) (void)0
  48. #endif
  49. const mp_obj_module_t mp_module___main__ = {
  50. .base = { &mp_type_module },
  51. .globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main),
  52. };
  53. void mp_init(void) {
  54. qstr_init();
  55. // no pending exceptions to start with
  56. MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
  57. #if MICROPY_ENABLE_SCHEDULER
  58. MP_STATE_VM(sched_state) = MP_SCHED_IDLE;
  59. MP_STATE_VM(sched_sp) = 0;
  60. #endif
  61. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  62. mp_init_emergency_exception_buf();
  63. #endif
  64. #if MICROPY_KBD_EXCEPTION
  65. // initialise the exception object for raising KeyboardInterrupt
  66. MP_STATE_VM(mp_kbd_exception).base.type = &mp_type_KeyboardInterrupt;
  67. MP_STATE_VM(mp_kbd_exception).traceback_alloc = 0;
  68. MP_STATE_VM(mp_kbd_exception).traceback_len = 0;
  69. MP_STATE_VM(mp_kbd_exception).traceback_data = NULL;
  70. MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
  71. #endif
  72. // call port specific initialization if any
  73. #ifdef MICROPY_PORT_INIT_FUNC
  74. MICROPY_PORT_INIT_FUNC;
  75. #endif
  76. // optimization disabled by default
  77. MP_STATE_VM(mp_optimise_value) = 0;
  78. // init global module dict
  79. mp_obj_dict_init(&MP_STATE_VM(mp_loaded_modules_dict), 3);
  80. // initialise the __main__ module
  81. mp_obj_dict_init(&MP_STATE_VM(dict_main), 1);
  82. mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(dict_main)), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
  83. // locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
  84. mp_locals_set(&MP_STATE_VM(dict_main));
  85. mp_globals_set(&MP_STATE_VM(dict_main));
  86. #if MICROPY_CAN_OVERRIDE_BUILTINS
  87. // start with no extensions to builtins
  88. MP_STATE_VM(mp_module_builtins_override_dict) = NULL;
  89. #endif
  90. #if MICROPY_PY_OS_DUPTERM
  91. for (size_t i = 0; i < MICROPY_PY_OS_DUPTERM; ++i) {
  92. MP_STATE_VM(dupterm_objs[i]) = MP_OBJ_NULL;
  93. }
  94. MP_STATE_VM(dupterm_arr_obj) = MP_OBJ_NULL;
  95. #endif
  96. #if MICROPY_FSUSERMOUNT
  97. // zero out the pointers to the user-mounted devices
  98. memset(MP_STATE_VM(fs_user_mount), 0, sizeof(MP_STATE_VM(fs_user_mount)));
  99. #endif
  100. #if MICROPY_VFS
  101. // initialise the VFS sub-system
  102. MP_STATE_VM(vfs_cur) = NULL;
  103. MP_STATE_VM(vfs_mount_table) = NULL;
  104. #endif
  105. #if MICROPY_PY_THREAD_GIL
  106. mp_thread_mutex_init(&MP_STATE_VM(gil_mutex));
  107. #endif
  108. MP_THREAD_GIL_ENTER();
  109. }
  110. void mp_deinit(void) {
  111. //mp_obj_dict_free(&dict_main);
  112. //mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map));
  113. // call port specific deinitialization if any
  114. #ifdef MICROPY_PORT_INIT_FUNC
  115. MICROPY_PORT_DEINIT_FUNC;
  116. #endif
  117. }
  118. mp_obj_t mp_load_name(qstr qst) {
  119. // logic: search locals, globals, builtins
  120. DEBUG_OP_printf("load name %s\n", qstr_str(qst));
  121. // If we're at the outer scope (locals == globals), dispatch to load_global right away
  122. if (mp_locals_get() != mp_globals_get()) {
  123. mp_map_elem_t *elem = mp_map_lookup(&mp_locals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
  124. if (elem != NULL) {
  125. return elem->value;
  126. }
  127. }
  128. return mp_load_global(qst);
  129. }
  130. mp_obj_t mp_load_global(qstr qst) {
  131. // logic: search globals, builtins
  132. DEBUG_OP_printf("load global %s\n", qstr_str(qst));
  133. mp_map_elem_t *elem = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
  134. if (elem == NULL) {
  135. #if MICROPY_CAN_OVERRIDE_BUILTINS
  136. if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
  137. // lookup in additional dynamic table of builtins first
  138. elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
  139. if (elem != NULL) {
  140. return elem->value;
  141. }
  142. }
  143. #endif
  144. elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
  145. if (elem == NULL) {
  146. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  147. mp_raise_msg(&mp_type_NameError, "name not defined");
  148. } else {
  149. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
  150. "name '%q' is not defined", qst));
  151. }
  152. }
  153. }
  154. return elem->value;
  155. }
  156. mp_obj_t mp_load_build_class(void) {
  157. DEBUG_OP_printf("load_build_class\n");
  158. #if MICROPY_CAN_OVERRIDE_BUILTINS
  159. if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
  160. // lookup in additional dynamic table of builtins first
  161. 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);
  162. if (elem != NULL) {
  163. return elem->value;
  164. }
  165. }
  166. #endif
  167. return MP_OBJ_FROM_PTR(&mp_builtin___build_class___obj);
  168. }
  169. void mp_store_name(qstr qst, mp_obj_t obj) {
  170. DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qst), obj);
  171. mp_obj_dict_store(MP_OBJ_FROM_PTR(mp_locals_get()), MP_OBJ_NEW_QSTR(qst), obj);
  172. }
  173. void mp_delete_name(qstr qst) {
  174. DEBUG_OP_printf("delete name %s\n", qstr_str(qst));
  175. // TODO convert KeyError to NameError if qst not found
  176. mp_obj_dict_delete(MP_OBJ_FROM_PTR(mp_locals_get()), MP_OBJ_NEW_QSTR(qst));
  177. }
  178. void mp_store_global(qstr qst, mp_obj_t obj) {
  179. DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qst), obj);
  180. mp_obj_dict_store(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(qst), obj);
  181. }
  182. void mp_delete_global(qstr qst) {
  183. DEBUG_OP_printf("delete global %s\n", qstr_str(qst));
  184. // TODO convert KeyError to NameError if qst not found
  185. mp_obj_dict_delete(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(qst));
  186. }
  187. mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) {
  188. DEBUG_OP_printf("unary " UINT_FMT " %q %p\n", op, mp_unary_op_method_name[op], arg);
  189. if (op == MP_UNARY_OP_NOT) {
  190. // "not x" is the negative of whether "x" is true per Python semantics
  191. return mp_obj_new_bool(mp_obj_is_true(arg) == 0);
  192. } else if (MP_OBJ_IS_SMALL_INT(arg)) {
  193. mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
  194. switch (op) {
  195. case MP_UNARY_OP_BOOL:
  196. return mp_obj_new_bool(val != 0);
  197. case MP_UNARY_OP_HASH:
  198. return arg;
  199. case MP_UNARY_OP_POSITIVE:
  200. return arg;
  201. case MP_UNARY_OP_NEGATIVE:
  202. // check for overflow
  203. if (val == MP_SMALL_INT_MIN) {
  204. return mp_obj_new_int(-val);
  205. } else {
  206. return MP_OBJ_NEW_SMALL_INT(-val);
  207. }
  208. case MP_UNARY_OP_ABS:
  209. if (val >= 0) {
  210. return arg;
  211. } else if (val == MP_SMALL_INT_MIN) {
  212. // check for overflow
  213. return mp_obj_new_int(-val);
  214. } else {
  215. return MP_OBJ_NEW_SMALL_INT(-val);
  216. }
  217. default:
  218. assert(op == MP_UNARY_OP_INVERT);
  219. return MP_OBJ_NEW_SMALL_INT(~val);
  220. }
  221. } 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. if (h == 0) {
  225. GET_STR_DATA_LEN(arg, data, len);
  226. h = qstr_compute_hash(data, len);
  227. }
  228. return MP_OBJ_NEW_SMALL_INT(h);
  229. } else {
  230. mp_obj_type_t *type = mp_obj_get_type(arg);
  231. if (type->unary_op != NULL) {
  232. mp_obj_t result = type->unary_op(op, arg);
  233. if (result != MP_OBJ_NULL) {
  234. return result;
  235. }
  236. }
  237. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  238. mp_raise_TypeError("unsupported type for operator");
  239. } else {
  240. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  241. "unsupported type for %q: '%s'",
  242. mp_unary_op_method_name[op], mp_obj_get_type_str(arg)));
  243. }
  244. }
  245. }
  246. mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
  247. DEBUG_OP_printf("binary " UINT_FMT " %q %p %p\n", op, mp_binary_op_method_name[op], lhs, rhs);
  248. // TODO correctly distinguish inplace operators for mutable objects
  249. // lookup logic that CPython uses for +=:
  250. // check for implemented +=
  251. // then check for implemented +
  252. // then check for implemented seq.inplace_concat
  253. // then check for implemented seq.concat
  254. // then fail
  255. // note that list does not implement + or +=, so that inplace_concat is reached first for +=
  256. // deal with is
  257. if (op == MP_BINARY_OP_IS) {
  258. return mp_obj_new_bool(lhs == rhs);
  259. }
  260. // deal with == and != for all types
  261. if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
  262. if (mp_obj_equal(lhs, rhs)) {
  263. if (op == MP_BINARY_OP_EQUAL) {
  264. return mp_const_true;
  265. } else {
  266. return mp_const_false;
  267. }
  268. } else {
  269. if (op == MP_BINARY_OP_EQUAL) {
  270. return mp_const_false;
  271. } else {
  272. return mp_const_true;
  273. }
  274. }
  275. }
  276. // deal with exception_match for all types
  277. if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
  278. // rhs must be issubclass(rhs, BaseException)
  279. if (mp_obj_is_exception_type(rhs)) {
  280. if (mp_obj_exception_match(lhs, rhs)) {
  281. return mp_const_true;
  282. } else {
  283. return mp_const_false;
  284. }
  285. } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
  286. mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(rhs);
  287. for (size_t i = 0; i < tuple->len; i++) {
  288. rhs = tuple->items[i];
  289. if (!mp_obj_is_exception_type(rhs)) {
  290. goto unsupported_op;
  291. }
  292. if (mp_obj_exception_match(lhs, rhs)) {
  293. return mp_const_true;
  294. }
  295. }
  296. return mp_const_false;
  297. }
  298. goto unsupported_op;
  299. }
  300. if (MP_OBJ_IS_SMALL_INT(lhs)) {
  301. mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
  302. if (MP_OBJ_IS_SMALL_INT(rhs)) {
  303. mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
  304. // This is a binary operation: lhs_val op rhs_val
  305. // We need to be careful to handle overflow; see CERT INT32-C
  306. // Operations that can overflow:
  307. // + result always fits in mp_int_t, then handled by SMALL_INT check
  308. // - result always fits in mp_int_t, then handled by SMALL_INT check
  309. // * checked explicitly
  310. // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
  311. // % if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
  312. // << checked explicitly
  313. switch (op) {
  314. case MP_BINARY_OP_OR:
  315. case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
  316. case MP_BINARY_OP_XOR:
  317. case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
  318. case MP_BINARY_OP_AND:
  319. case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
  320. case MP_BINARY_OP_LSHIFT:
  321. case MP_BINARY_OP_INPLACE_LSHIFT: {
  322. if (rhs_val < 0) {
  323. // negative shift not allowed
  324. mp_raise_ValueError("negative shift count");
  325. } 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)) {
  326. // left-shift will overflow, so use higher precision integer
  327. lhs = mp_obj_new_int_from_ll(lhs_val);
  328. goto generic_binary_op;
  329. } else {
  330. // use standard precision
  331. lhs_val <<= rhs_val;
  332. }
  333. break;
  334. }
  335. case MP_BINARY_OP_RSHIFT:
  336. case MP_BINARY_OP_INPLACE_RSHIFT:
  337. if (rhs_val < 0) {
  338. // negative shift not allowed
  339. mp_raise_ValueError("negative shift count");
  340. } else {
  341. // standard precision is enough for right-shift
  342. if (rhs_val >= (mp_int_t)BITS_PER_WORD) {
  343. // Shifting to big amounts is underfined behavior
  344. // in C and is CPU-dependent; propagate sign bit.
  345. rhs_val = BITS_PER_WORD - 1;
  346. }
  347. lhs_val >>= rhs_val;
  348. }
  349. break;
  350. case MP_BINARY_OP_ADD:
  351. case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
  352. case MP_BINARY_OP_SUBTRACT:
  353. case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
  354. case MP_BINARY_OP_MULTIPLY:
  355. case MP_BINARY_OP_INPLACE_MULTIPLY: {
  356. // If long long type exists and is larger than mp_int_t, then
  357. // we can use the following code to perform overflow-checked multiplication.
  358. // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
  359. #if 0
  360. // compute result using long long precision
  361. long long res = (long long)lhs_val * (long long)rhs_val;
  362. if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
  363. // result overflowed SMALL_INT, so return higher precision integer
  364. return mp_obj_new_int_from_ll(res);
  365. } else {
  366. // use standard precision
  367. lhs_val = (mp_int_t)res;
  368. }
  369. #endif
  370. if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
  371. // use higher precision
  372. lhs = mp_obj_new_int_from_ll(lhs_val);
  373. goto generic_binary_op;
  374. } else {
  375. // use standard precision
  376. return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
  377. }
  378. }
  379. case MP_BINARY_OP_FLOOR_DIVIDE:
  380. case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
  381. if (rhs_val == 0) {
  382. goto zero_division;
  383. }
  384. lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
  385. break;
  386. #if MICROPY_PY_BUILTINS_FLOAT
  387. case MP_BINARY_OP_TRUE_DIVIDE:
  388. case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
  389. if (rhs_val == 0) {
  390. goto zero_division;
  391. }
  392. return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
  393. #endif
  394. case MP_BINARY_OP_MODULO:
  395. case MP_BINARY_OP_INPLACE_MODULO: {
  396. if (rhs_val == 0) {
  397. goto zero_division;
  398. }
  399. lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
  400. break;
  401. }
  402. case MP_BINARY_OP_POWER:
  403. case MP_BINARY_OP_INPLACE_POWER:
  404. if (rhs_val < 0) {
  405. #if MICROPY_PY_BUILTINS_FLOAT
  406. lhs = mp_obj_new_float(lhs_val);
  407. goto generic_binary_op;
  408. #else
  409. mp_raise_ValueError("negative power with no float support");
  410. #endif
  411. } else {
  412. mp_int_t ans = 1;
  413. while (rhs_val > 0) {
  414. if (rhs_val & 1) {
  415. if (mp_small_int_mul_overflow(ans, lhs_val)) {
  416. goto power_overflow;
  417. }
  418. ans *= lhs_val;
  419. }
  420. if (rhs_val == 1) {
  421. break;
  422. }
  423. rhs_val /= 2;
  424. if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
  425. goto power_overflow;
  426. }
  427. lhs_val *= lhs_val;
  428. }
  429. lhs_val = ans;
  430. }
  431. break;
  432. power_overflow:
  433. // use higher precision
  434. lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
  435. goto generic_binary_op;
  436. case MP_BINARY_OP_DIVMOD: {
  437. if (rhs_val == 0) {
  438. goto zero_division;
  439. }
  440. // to reduce stack usage we don't pass a temp array of the 2 items
  441. mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
  442. tuple->items[0] = MP_OBJ_NEW_SMALL_INT(mp_small_int_floor_divide(lhs_val, rhs_val));
  443. tuple->items[1] = MP_OBJ_NEW_SMALL_INT(mp_small_int_modulo(lhs_val, rhs_val));
  444. return MP_OBJ_FROM_PTR(tuple);
  445. }
  446. case MP_BINARY_OP_LESS: return mp_obj_new_bool(lhs_val < rhs_val);
  447. case MP_BINARY_OP_MORE: return mp_obj_new_bool(lhs_val > rhs_val);
  448. case MP_BINARY_OP_LESS_EQUAL: return mp_obj_new_bool(lhs_val <= rhs_val);
  449. case MP_BINARY_OP_MORE_EQUAL: return mp_obj_new_bool(lhs_val >= rhs_val);
  450. default:
  451. goto unsupported_op;
  452. }
  453. // TODO: We just should make mp_obj_new_int() inline and use that
  454. if (MP_SMALL_INT_FITS(lhs_val)) {
  455. return MP_OBJ_NEW_SMALL_INT(lhs_val);
  456. } else {
  457. return mp_obj_new_int(lhs_val);
  458. }
  459. #if MICROPY_PY_BUILTINS_FLOAT
  460. } else if (mp_obj_is_float(rhs)) {
  461. mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
  462. if (res == MP_OBJ_NULL) {
  463. goto unsupported_op;
  464. } else {
  465. return res;
  466. }
  467. #if MICROPY_PY_BUILTINS_COMPLEX
  468. } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
  469. mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
  470. if (res == MP_OBJ_NULL) {
  471. goto unsupported_op;
  472. } else {
  473. return res;
  474. }
  475. #endif
  476. #endif
  477. }
  478. }
  479. // Convert MP_BINARY_OP_IN to MP_BINARY_OP_CONTAINS with swapped args.
  480. if (op == MP_BINARY_OP_IN) {
  481. op = MP_BINARY_OP_CONTAINS;
  482. mp_obj_t temp = lhs;
  483. lhs = rhs;
  484. rhs = temp;
  485. }
  486. // generic binary_op supplied by type
  487. mp_obj_type_t *type;
  488. generic_binary_op:
  489. type = mp_obj_get_type(lhs);
  490. if (type->binary_op != NULL) {
  491. mp_obj_t result = type->binary_op(op, lhs, rhs);
  492. if (result != MP_OBJ_NULL) {
  493. return result;
  494. }
  495. }
  496. #if MICROPY_PY_REVERSE_SPECIAL_METHODS
  497. if (op >= MP_BINARY_OP_OR && op <= MP_BINARY_OP_REVERSE_POWER) {
  498. mp_obj_t t = rhs;
  499. rhs = lhs;
  500. lhs = t;
  501. if (op <= MP_BINARY_OP_POWER) {
  502. op += MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
  503. goto generic_binary_op;
  504. }
  505. // Convert __rop__ back to __op__ for error message
  506. op -= MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
  507. }
  508. #endif
  509. if (op == MP_BINARY_OP_CONTAINS) {
  510. // If type didn't support containment then explicitly walk the iterator.
  511. // mp_getiter will raise the appropriate exception if lhs is not iterable.
  512. mp_obj_iter_buf_t iter_buf;
  513. mp_obj_t iter = mp_getiter(lhs, &iter_buf);
  514. mp_obj_t next;
  515. while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
  516. if (mp_obj_equal(next, rhs)) {
  517. return mp_const_true;
  518. }
  519. }
  520. return mp_const_false;
  521. }
  522. unsupported_op:
  523. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  524. mp_raise_TypeError("unsupported type for operator");
  525. } else {
  526. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  527. "unsupported types for %q: '%s', '%s'",
  528. mp_binary_op_method_name[op], mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs)));
  529. }
  530. zero_division:
  531. mp_raise_msg(&mp_type_ZeroDivisionError, "division by zero");
  532. }
  533. mp_obj_t mp_call_function_0(mp_obj_t fun) {
  534. return mp_call_function_n_kw(fun, 0, 0, NULL);
  535. }
  536. mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
  537. return mp_call_function_n_kw(fun, 1, 0, &arg);
  538. }
  539. mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
  540. mp_obj_t args[2];
  541. args[0] = arg1;
  542. args[1] = arg2;
  543. return mp_call_function_n_kw(fun, 2, 0, args);
  544. }
  545. // args contains, eg: arg0 arg1 key0 value0 key1 value1
  546. mp_obj_t mp_call_function_n_kw(mp_obj_t fun_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  547. // TODO improve this: fun object can specify its type and we parse here the arguments,
  548. // passing to the function arrays of fixed and keyword arguments
  549. DEBUG_OP_printf("calling function %p(n_args=" UINT_FMT ", n_kw=" UINT_FMT ", args=%p)\n", fun_in, n_args, n_kw, args);
  550. // get the type
  551. mp_obj_type_t *type = mp_obj_get_type(fun_in);
  552. // do the call
  553. if (type->call != NULL) {
  554. return type->call(fun_in, n_args, n_kw, args);
  555. }
  556. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  557. mp_raise_TypeError("object not callable");
  558. } else {
  559. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  560. "'%s' object is not callable", mp_obj_get_type_str(fun_in)));
  561. }
  562. }
  563. // 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)
  564. // if n_args==0 and n_kw==0 then there are only fun and self/NULL
  565. mp_obj_t mp_call_method_n_kw(size_t n_args, size_t n_kw, const mp_obj_t *args) {
  566. 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);
  567. int adjust = (args[1] == MP_OBJ_NULL) ? 0 : 1;
  568. return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
  569. }
  570. // This function only needs to be exposed externally when in stackless mode.
  571. #if !MICROPY_STACKLESS
  572. STATIC
  573. #endif
  574. void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args, mp_call_args_t *out_args) {
  575. mp_obj_t fun = *args++;
  576. mp_obj_t self = MP_OBJ_NULL;
  577. if (have_self) {
  578. self = *args++; // may be MP_OBJ_NULL
  579. }
  580. uint n_args = n_args_n_kw & 0xff;
  581. uint n_kw = (n_args_n_kw >> 8) & 0xff;
  582. mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // may be MP_OBJ_NULL
  583. mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // may be MP_OBJ_NULL
  584. 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);
  585. // We need to create the following array of objects:
  586. // args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
  587. // TODO: optimize one day to avoid constructing new arg array? Will be hard.
  588. // The new args array
  589. mp_obj_t *args2;
  590. uint args2_alloc;
  591. uint args2_len = 0;
  592. // Try to get a hint for the size of the kw_dict
  593. uint kw_dict_len = 0;
  594. if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
  595. kw_dict_len = mp_obj_dict_len(kw_dict);
  596. }
  597. // Extract the pos_seq sequence to the new args array.
  598. // Note that it can be arbitrary iterator.
  599. if (pos_seq == MP_OBJ_NULL) {
  600. // no sequence
  601. // allocate memory for the new array of args
  602. args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
  603. args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
  604. // copy the self
  605. if (self != MP_OBJ_NULL) {
  606. args2[args2_len++] = self;
  607. }
  608. // copy the fixed pos args
  609. mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
  610. args2_len += n_args;
  611. } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) {
  612. // optimise the case of a tuple and list
  613. // get the items
  614. size_t len;
  615. mp_obj_t *items;
  616. mp_obj_get_array(pos_seq, &len, &items);
  617. // allocate memory for the new array of args
  618. args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
  619. args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
  620. // copy the self
  621. if (self != MP_OBJ_NULL) {
  622. args2[args2_len++] = self;
  623. }
  624. // copy the fixed and variable position args
  625. mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
  626. args2_len += n_args + len;
  627. } else {
  628. // generic iterator
  629. // allocate memory for the new array of args
  630. args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
  631. args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
  632. // copy the self
  633. if (self != MP_OBJ_NULL) {
  634. args2[args2_len++] = self;
  635. }
  636. // copy the fixed position args
  637. mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
  638. args2_len += n_args;
  639. // extract the variable position args from the iterator
  640. mp_obj_iter_buf_t iter_buf;
  641. mp_obj_t iterable = mp_getiter(pos_seq, &iter_buf);
  642. mp_obj_t item;
  643. while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
  644. if (args2_len >= args2_alloc) {
  645. args2 = mp_nonlocal_realloc(args2, args2_alloc * sizeof(mp_obj_t), args2_alloc * 2 * sizeof(mp_obj_t));
  646. args2_alloc *= 2;
  647. }
  648. args2[args2_len++] = item;
  649. }
  650. }
  651. // The size of the args2 array now is the number of positional args.
  652. uint pos_args_len = args2_len;
  653. // Copy the fixed kw args.
  654. mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
  655. args2_len += 2 * n_kw;
  656. // Extract (key,value) pairs from kw_dict dictionary and append to args2.
  657. // Note that it can be arbitrary iterator.
  658. if (kw_dict == MP_OBJ_NULL) {
  659. // pass
  660. } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) {
  661. // dictionary
  662. mp_map_t *map = mp_obj_dict_get_map(kw_dict);
  663. assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above
  664. for (size_t i = 0; i < map->alloc; i++) {
  665. if (MP_MAP_SLOT_IS_FILLED(map, i)) {
  666. // the key must be a qstr, so intern it if it's a string
  667. mp_obj_t key = map->table[i].key;
  668. if (MP_OBJ_IS_TYPE(key, &mp_type_str)) {
  669. key = mp_obj_str_intern(key);
  670. }
  671. args2[args2_len++] = key;
  672. args2[args2_len++] = map->table[i].value;
  673. }
  674. }
  675. } else {
  676. // generic mapping:
  677. // - call keys() to get an iterable of all keys in the mapping
  678. // - call __getitem__ for each key to get the corresponding value
  679. // get the keys iterable
  680. mp_obj_t dest[3];
  681. mp_load_method(kw_dict, MP_QSTR_keys, dest);
  682. mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest), NULL);
  683. mp_obj_t key;
  684. while ((key = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
  685. // expand size of args array if needed
  686. if (args2_len + 1 >= args2_alloc) {
  687. uint new_alloc = args2_alloc * 2;
  688. if (new_alloc < 4) {
  689. new_alloc = 4;
  690. }
  691. args2 = mp_nonlocal_realloc(args2, args2_alloc * sizeof(mp_obj_t), new_alloc * sizeof(mp_obj_t));
  692. args2_alloc = new_alloc;
  693. }
  694. // the key must be a qstr, so intern it if it's a string
  695. if (MP_OBJ_IS_TYPE(key, &mp_type_str)) {
  696. key = mp_obj_str_intern(key);
  697. }
  698. // get the value corresponding to the key
  699. mp_load_method(kw_dict, MP_QSTR___getitem__, dest);
  700. dest[2] = key;
  701. mp_obj_t value = mp_call_method_n_kw(1, 0, dest);
  702. // store the key/value pair in the argument array
  703. args2[args2_len++] = key;
  704. args2[args2_len++] = value;
  705. }
  706. }
  707. out_args->fun = fun;
  708. out_args->args = args2;
  709. out_args->n_args = pos_args_len;
  710. out_args->n_kw = (args2_len - pos_args_len) / 2;
  711. out_args->n_alloc = args2_alloc;
  712. }
  713. mp_obj_t mp_call_method_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args) {
  714. mp_call_args_t out_args;
  715. mp_call_prepare_args_n_kw_var(have_self, n_args_n_kw, args, &out_args);
  716. mp_obj_t res = mp_call_function_n_kw(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args);
  717. mp_nonlocal_free(out_args.args, out_args.n_alloc * sizeof(mp_obj_t));
  718. return res;
  719. }
  720. // unpacked items are stored in reverse order into the array pointed to by items
  721. void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) {
  722. size_t seq_len;
  723. if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
  724. mp_obj_t *seq_items;
  725. mp_obj_get_array(seq_in, &seq_len, &seq_items);
  726. if (seq_len < num) {
  727. goto too_short;
  728. } else if (seq_len > num) {
  729. goto too_long;
  730. }
  731. for (size_t i = 0; i < num; i++) {
  732. items[i] = seq_items[num - 1 - i];
  733. }
  734. } else {
  735. mp_obj_iter_buf_t iter_buf;
  736. mp_obj_t iterable = mp_getiter(seq_in, &iter_buf);
  737. for (seq_len = 0; seq_len < num; seq_len++) {
  738. mp_obj_t el = mp_iternext(iterable);
  739. if (el == MP_OBJ_STOP_ITERATION) {
  740. goto too_short;
  741. }
  742. items[num - 1 - seq_len] = el;
  743. }
  744. if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
  745. goto too_long;
  746. }
  747. }
  748. return;
  749. too_short:
  750. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  751. mp_raise_ValueError("wrong number of values to unpack");
  752. } else {
  753. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  754. "need more than %d values to unpack", (int)seq_len));
  755. }
  756. too_long:
  757. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  758. mp_raise_ValueError("wrong number of values to unpack");
  759. } else {
  760. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  761. "too many values to unpack (expected %d)", (int)num));
  762. }
  763. }
  764. // unpacked items are stored in reverse order into the array pointed to by items
  765. void mp_unpack_ex(mp_obj_t seq_in, size_t num_in, mp_obj_t *items) {
  766. size_t num_left = num_in & 0xff;
  767. size_t num_right = (num_in >> 8) & 0xff;
  768. DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
  769. size_t seq_len;
  770. if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) {
  771. mp_obj_t *seq_items;
  772. mp_obj_get_array(seq_in, &seq_len, &seq_items);
  773. if (seq_len < num_left + num_right) {
  774. goto too_short;
  775. }
  776. for (size_t i = 0; i < num_right; i++) {
  777. items[i] = seq_items[seq_len - 1 - i];
  778. }
  779. items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
  780. for (size_t i = 0; i < num_left; i++) {
  781. items[num_right + 1 + i] = seq_items[num_left - 1 - i];
  782. }
  783. } else {
  784. // Generic iterable; this gets a bit messy: we unpack known left length to the
  785. // items destination array, then the rest to a dynamically created list. Once the
  786. // iterable is exhausted, we take from this list for the right part of the items.
  787. // TODO Improve to waste less memory in the dynamically created list.
  788. mp_obj_t iterable = mp_getiter(seq_in, NULL);
  789. mp_obj_t item;
  790. for (seq_len = 0; seq_len < num_left; seq_len++) {
  791. item = mp_iternext(iterable);
  792. if (item == MP_OBJ_STOP_ITERATION) {
  793. goto too_short;
  794. }
  795. items[num_left + num_right + 1 - 1 - seq_len] = item;
  796. }
  797. mp_obj_list_t *rest = MP_OBJ_TO_PTR(mp_obj_new_list(0, NULL));
  798. while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
  799. mp_obj_list_append(MP_OBJ_FROM_PTR(rest), item);
  800. }
  801. if (rest->len < num_right) {
  802. goto too_short;
  803. }
  804. items[num_right] = MP_OBJ_FROM_PTR(rest);
  805. for (size_t i = 0; i < num_right; i++) {
  806. items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
  807. }
  808. mp_obj_list_set_len(MP_OBJ_FROM_PTR(rest), rest->len - num_right);
  809. }
  810. return;
  811. too_short:
  812. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  813. mp_raise_ValueError("wrong number of values to unpack");
  814. } else {
  815. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  816. "need more than %d values to unpack", (int)seq_len));
  817. }
  818. }
  819. mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
  820. DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
  821. // use load_method
  822. mp_obj_t dest[2];
  823. mp_load_method(base, attr, dest);
  824. if (dest[1] == MP_OBJ_NULL) {
  825. // load_method returned just a normal attribute
  826. return dest[0];
  827. } else {
  828. // load_method returned a method, so build a bound method object
  829. return mp_obj_new_bound_meth(dest[0], dest[1]);
  830. }
  831. }
  832. #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
  833. // The following "checked fun" type is local to the mp_convert_member_lookup
  834. // function, and serves to check that the first argument to a builtin function
  835. // has the correct type.
  836. typedef struct _mp_obj_checked_fun_t {
  837. mp_obj_base_t base;
  838. const mp_obj_type_t *type;
  839. mp_obj_t fun;
  840. } mp_obj_checked_fun_t;
  841. STATIC mp_obj_t checked_fun_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  842. mp_obj_checked_fun_t *self = MP_OBJ_TO_PTR(self_in);
  843. if (n_args > 0) {
  844. const mp_obj_type_t *arg0_type = mp_obj_get_type(args[0]);
  845. if (arg0_type != self->type) {
  846. if (MICROPY_ERROR_REPORTING != MICROPY_ERROR_REPORTING_DETAILED) {
  847. mp_raise_TypeError("argument has wrong type");
  848. } else {
  849. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  850. "argument should be a '%q' not a '%q'", self->type->name, arg0_type->name));
  851. }
  852. }
  853. }
  854. return mp_call_function_n_kw(self->fun, n_args, n_kw, args);
  855. }
  856. STATIC const mp_obj_type_t mp_type_checked_fun = {
  857. { &mp_type_type },
  858. .name = MP_QSTR_function,
  859. .call = checked_fun_call,
  860. };
  861. STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) {
  862. mp_obj_checked_fun_t *o = m_new_obj(mp_obj_checked_fun_t);
  863. o->base.type = &mp_type_checked_fun;
  864. o->type = type;
  865. o->fun = fun;
  866. return MP_OBJ_FROM_PTR(o);
  867. }
  868. #endif // MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
  869. // Given a member that was extracted from an instance, convert it correctly
  870. // and put the result in the dest[] array for a possible method call.
  871. // Conversion means dealing with static/class methods, callables, and values.
  872. // see http://docs.python.org/3/howto/descriptor.html
  873. void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) {
  874. if (MP_OBJ_IS_TYPE(member, &mp_type_staticmethod)) {
  875. // return just the function
  876. dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
  877. } else if (MP_OBJ_IS_TYPE(member, &mp_type_classmethod)) {
  878. // return a bound method, with self being the type of this object
  879. // this type should be the type of the original instance, not the base
  880. // type (which is what is passed in the 'type' argument to this function)
  881. if (self != MP_OBJ_NULL) {
  882. type = mp_obj_get_type(self);
  883. }
  884. dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
  885. dest[1] = MP_OBJ_FROM_PTR(type);
  886. } else if (MP_OBJ_IS_TYPE(member, &mp_type_type)) {
  887. // Don't try to bind types (even though they're callable)
  888. dest[0] = member;
  889. } else if (MP_OBJ_IS_FUN(member)
  890. || (MP_OBJ_IS_OBJ(member)
  891. && (((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure
  892. || ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) {
  893. // only functions, closures and generators objects can be bound to self
  894. #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
  895. const mp_obj_type_t *m_type = ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type;
  896. if (self == MP_OBJ_NULL
  897. && (m_type == &mp_type_fun_builtin_0
  898. || m_type == &mp_type_fun_builtin_1
  899. || m_type == &mp_type_fun_builtin_2
  900. || m_type == &mp_type_fun_builtin_3
  901. || m_type == &mp_type_fun_builtin_var)) {
  902. // we extracted a builtin method without a first argument, so we must
  903. // wrap this function in a type checker
  904. dest[0] = mp_obj_new_checked_fun(type, member);
  905. } else
  906. #endif
  907. {
  908. // return a bound method, with self being this object
  909. dest[0] = member;
  910. dest[1] = self;
  911. }
  912. } else {
  913. // class member is a value, so just return that value
  914. dest[0] = member;
  915. }
  916. }
  917. // no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
  918. // normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
  919. // method attribute found, returns: dest[0] == <method>, dest[1] == <self>
  920. void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) {
  921. // clear output to indicate no attribute/method found yet
  922. dest[0] = MP_OBJ_NULL;
  923. dest[1] = MP_OBJ_NULL;
  924. // get the type
  925. mp_obj_type_t *type = mp_obj_get_type(obj);
  926. // look for built-in names
  927. if (0) {
  928. #if MICROPY_CPYTHON_COMPAT
  929. } else if (attr == MP_QSTR___class__) {
  930. // a.__class__ is equivalent to type(a)
  931. dest[0] = MP_OBJ_FROM_PTR(type);
  932. #endif
  933. } else if (attr == MP_QSTR___next__ && type->iternext != NULL) {
  934. dest[0] = MP_OBJ_FROM_PTR(&mp_builtin_next_obj);
  935. dest[1] = obj;
  936. } else if (type->attr != NULL) {
  937. // this type can do its own load, so call it
  938. type->attr(obj, attr, dest);
  939. } else if (type->locals_dict != NULL) {
  940. // generic method lookup
  941. // this is a lookup in the object (ie not class or type)
  942. assert(type->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now
  943. mp_map_t *locals_map = &type->locals_dict->map;
  944. mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
  945. if (elem != NULL) {
  946. mp_convert_member_lookup(obj, type, elem->value, dest);
  947. }
  948. }
  949. }
  950. void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
  951. DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
  952. mp_load_method_maybe(base, attr, dest);
  953. if (dest[0] == MP_OBJ_NULL) {
  954. // no attribute/method called attr
  955. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  956. mp_raise_msg(&mp_type_AttributeError, "no such attribute");
  957. } else {
  958. // following CPython, we give a more detailed error message for type objects
  959. if (MP_OBJ_IS_TYPE(base, &mp_type_type)) {
  960. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
  961. "type object '%q' has no attribute '%q'",
  962. ((mp_obj_type_t*)MP_OBJ_TO_PTR(base))->name, attr));
  963. } else {
  964. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
  965. "'%s' object has no attribute '%q'",
  966. mp_obj_get_type_str(base), attr));
  967. }
  968. }
  969. }
  970. }
  971. void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
  972. DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
  973. mp_obj_type_t *type = mp_obj_get_type(base);
  974. if (type->attr != NULL) {
  975. mp_obj_t dest[2] = {MP_OBJ_SENTINEL, value};
  976. type->attr(base, attr, dest);
  977. if (dest[0] == MP_OBJ_NULL) {
  978. // success
  979. return;
  980. }
  981. }
  982. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  983. mp_raise_msg(&mp_type_AttributeError, "no such attribute");
  984. } else {
  985. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError,
  986. "'%s' object has no attribute '%q'",
  987. mp_obj_get_type_str(base), attr));
  988. }
  989. }
  990. mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
  991. assert(o_in);
  992. mp_obj_type_t *type = mp_obj_get_type(o_in);
  993. // Check for native getiter which is the identity. We handle this case explicitly
  994. // so we don't unnecessarily allocate any RAM for the iter_buf, which won't be used.
  995. if (type->getiter == mp_identity_getiter) {
  996. return o_in;
  997. }
  998. // if caller did not provide a buffer then allocate one on the heap
  999. if (iter_buf == NULL) {
  1000. iter_buf = m_new_obj(mp_obj_iter_buf_t);
  1001. }
  1002. // check for native getiter (corresponds to __iter__)
  1003. if (type->getiter != NULL) {
  1004. mp_obj_t iter = type->getiter(o_in, iter_buf);
  1005. if (iter != MP_OBJ_NULL) {
  1006. return iter;
  1007. }
  1008. }
  1009. // check for __getitem__
  1010. mp_obj_t dest[2];
  1011. mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
  1012. if (dest[0] != MP_OBJ_NULL) {
  1013. // __getitem__ exists, create and return an iterator
  1014. return mp_obj_new_getitem_iter(dest, iter_buf);
  1015. }
  1016. // object not iterable
  1017. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1018. mp_raise_TypeError("object not iterable");
  1019. } else {
  1020. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  1021. "'%s' object is not iterable", mp_obj_get_type_str(o_in)));
  1022. }
  1023. }
  1024. // may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
  1025. // may also raise StopIteration()
  1026. mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
  1027. mp_obj_type_t *type = mp_obj_get_type(o_in);
  1028. if (type->iternext != NULL) {
  1029. return type->iternext(o_in);
  1030. } else {
  1031. // check for __next__ method
  1032. mp_obj_t dest[2];
  1033. mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
  1034. if (dest[0] != MP_OBJ_NULL) {
  1035. // __next__ exists, call it and return its result
  1036. return mp_call_method_n_kw(0, 0, dest);
  1037. } else {
  1038. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1039. mp_raise_TypeError("object not an iterator");
  1040. } else {
  1041. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  1042. "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
  1043. }
  1044. }
  1045. }
  1046. }
  1047. // will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
  1048. // may raise other exceptions
  1049. mp_obj_t mp_iternext(mp_obj_t o_in) {
  1050. MP_STACK_CHECK(); // enumerate, filter, map and zip can recursively call mp_iternext
  1051. mp_obj_type_t *type = mp_obj_get_type(o_in);
  1052. if (type->iternext != NULL) {
  1053. return type->iternext(o_in);
  1054. } else {
  1055. // check for __next__ method
  1056. mp_obj_t dest[2];
  1057. mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
  1058. if (dest[0] != MP_OBJ_NULL) {
  1059. // __next__ exists, call it and return its result
  1060. nlr_buf_t nlr;
  1061. if (nlr_push(&nlr) == 0) {
  1062. mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
  1063. nlr_pop();
  1064. return ret;
  1065. } else {
  1066. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
  1067. return MP_OBJ_STOP_ITERATION;
  1068. } else {
  1069. nlr_jump(nlr.ret_val);
  1070. }
  1071. }
  1072. } else {
  1073. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1074. mp_raise_TypeError("object not an iterator");
  1075. } else {
  1076. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  1077. "'%s' object is not an iterator", mp_obj_get_type_str(o_in)));
  1078. }
  1079. }
  1080. }
  1081. }
  1082. // TODO: Unclear what to do with StopIterarion exception here.
  1083. mp_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) {
  1084. assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
  1085. mp_obj_type_t *type = mp_obj_get_type(self_in);
  1086. if (type == &mp_type_gen_instance) {
  1087. return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
  1088. }
  1089. if (type->iternext != NULL && send_value == mp_const_none) {
  1090. mp_obj_t ret = type->iternext(self_in);
  1091. *ret_val = ret;
  1092. if (ret != MP_OBJ_STOP_ITERATION) {
  1093. return MP_VM_RETURN_YIELD;
  1094. } else {
  1095. // Emulate raise StopIteration()
  1096. // Special case, handled in vm.c
  1097. return MP_VM_RETURN_NORMAL;
  1098. }
  1099. }
  1100. mp_obj_t dest[3]; // Reserve slot for send() arg
  1101. // Python instance iterator protocol
  1102. if (send_value == mp_const_none) {
  1103. mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
  1104. if (dest[0] != MP_OBJ_NULL) {
  1105. nlr_buf_t nlr;
  1106. if (nlr_push(&nlr) == 0) {
  1107. *ret_val = mp_call_method_n_kw(0, 0, dest);
  1108. nlr_pop();
  1109. return MP_VM_RETURN_YIELD;
  1110. } else {
  1111. *ret_val = MP_OBJ_FROM_PTR(nlr.ret_val);
  1112. return MP_VM_RETURN_EXCEPTION;
  1113. }
  1114. }
  1115. }
  1116. // Either python instance generator protocol, or native object
  1117. // generator protocol.
  1118. if (send_value != MP_OBJ_NULL) {
  1119. mp_load_method(self_in, MP_QSTR_send, dest);
  1120. dest[2] = send_value;
  1121. // TODO: This should have exception wrapping like __next__ case
  1122. // above. Not done right away to think how to optimize native
  1123. // generators better, see:
  1124. // https://github.com/micropython/micropython/issues/2628
  1125. *ret_val = mp_call_method_n_kw(1, 0, dest);
  1126. return MP_VM_RETURN_YIELD;
  1127. }
  1128. assert(throw_value != MP_OBJ_NULL);
  1129. {
  1130. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(throw_value)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
  1131. mp_load_method_maybe(self_in, MP_QSTR_close, dest);
  1132. if (dest[0] != MP_OBJ_NULL) {
  1133. // TODO: Exceptions raised in close() are not propagated,
  1134. // printed to sys.stderr
  1135. *ret_val = mp_call_method_n_kw(0, 0, dest);
  1136. // We assume one can't "yield" from close()
  1137. return MP_VM_RETURN_NORMAL;
  1138. }
  1139. } else {
  1140. mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
  1141. if (dest[0] != MP_OBJ_NULL) {
  1142. dest[2] = throw_value;
  1143. *ret_val = mp_call_method_n_kw(1, 0, dest);
  1144. // If .throw() method returned, we assume it's value to yield
  1145. // - any exception would be thrown with nlr_raise().
  1146. return MP_VM_RETURN_YIELD;
  1147. }
  1148. }
  1149. // If there's nowhere to throw exception into, then we assume that object
  1150. // is just incapable to handle it, so any exception thrown into it
  1151. // will be propagated up. This behavior is approved by test_pep380.py
  1152. // test_delegation_of_close_to_non_generator(),
  1153. // test_delegating_throw_to_non_generator()
  1154. *ret_val = throw_value;
  1155. return MP_VM_RETURN_EXCEPTION;
  1156. }
  1157. }
  1158. mp_obj_t mp_make_raise_obj(mp_obj_t o) {
  1159. DEBUG_printf("raise %p\n", o);
  1160. if (mp_obj_is_exception_type(o)) {
  1161. // o is an exception type (it is derived from BaseException (or is BaseException))
  1162. // create and return a new exception instance by calling o
  1163. // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
  1164. // could have const instances in ROM which we return here instead
  1165. return mp_call_function_n_kw(o, 0, 0, NULL);
  1166. } else if (mp_obj_is_exception_instance(o)) {
  1167. // o is an instance of an exception, so use it as the exception
  1168. return o;
  1169. } else {
  1170. // o cannot be used as an exception, so return a type error (which will be raised by the caller)
  1171. return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
  1172. }
  1173. }
  1174. mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
  1175. DEBUG_printf("import name '%s' level=%d\n", qstr_str(name), MP_OBJ_SMALL_INT_VALUE(level));
  1176. // build args array
  1177. mp_obj_t args[5];
  1178. args[0] = MP_OBJ_NEW_QSTR(name);
  1179. args[1] = mp_const_none; // TODO should be globals
  1180. args[2] = mp_const_none; // TODO should be locals
  1181. args[3] = fromlist;
  1182. args[4] = level; // must be 0; we don't yet support other values
  1183. // TODO lookup __import__ and call that instead of going straight to builtin implementation
  1184. return mp_builtin___import__(5, args);
  1185. }
  1186. mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
  1187. DEBUG_printf("import from %p %s\n", module, qstr_str(name));
  1188. mp_obj_t dest[2];
  1189. mp_load_method_maybe(module, name, dest);
  1190. if (dest[1] != MP_OBJ_NULL) {
  1191. // Hopefully we can't import bound method from an object
  1192. import_error:
  1193. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %q", name));
  1194. }
  1195. if (dest[0] != MP_OBJ_NULL) {
  1196. return dest[0];
  1197. }
  1198. #if MICROPY_ENABLE_EXTERNAL_IMPORT
  1199. // See if it's a package, then can try FS import
  1200. if (!mp_obj_is_package(module)) {
  1201. goto import_error;
  1202. }
  1203. mp_load_method_maybe(module, MP_QSTR___name__, dest);
  1204. size_t pkg_name_len;
  1205. const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
  1206. const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
  1207. char *dot_name = mp_local_alloc(dot_name_len);
  1208. memcpy(dot_name, pkg_name, pkg_name_len);
  1209. dot_name[pkg_name_len] = '.';
  1210. memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
  1211. qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
  1212. mp_local_free(dot_name);
  1213. mp_obj_t args[5];
  1214. args[0] = MP_OBJ_NEW_QSTR(dot_name_q);
  1215. args[1] = mp_const_none; // TODO should be globals
  1216. args[2] = mp_const_none; // TODO should be locals
  1217. args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module
  1218. args[4] = MP_OBJ_NEW_SMALL_INT(0);
  1219. // TODO lookup __import__ and call that instead of going straight to builtin implementation
  1220. return mp_builtin___import__(5, args);
  1221. #else
  1222. // Package import not supported with external imports disabled
  1223. goto import_error;
  1224. #endif
  1225. }
  1226. void mp_import_all(mp_obj_t module) {
  1227. DEBUG_printf("import all %p\n", module);
  1228. // TODO: Support __all__
  1229. mp_map_t *map = mp_obj_dict_get_map(MP_OBJ_FROM_PTR(mp_obj_module_get_globals(module)));
  1230. for (size_t i = 0; i < map->alloc; i++) {
  1231. if (MP_MAP_SLOT_IS_FILLED(map, i)) {
  1232. qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
  1233. if (*qstr_str(name) != '_') {
  1234. mp_store_name(name, map->table[i].value);
  1235. }
  1236. }
  1237. }
  1238. }
  1239. #if MICROPY_ENABLE_COMPILER
  1240. // this is implemented in this file so it can optimise access to locals/globals
  1241. mp_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) {
  1242. // save context
  1243. mp_obj_dict_t *volatile old_globals = mp_globals_get();
  1244. mp_obj_dict_t *volatile old_locals = mp_locals_get();
  1245. // set new context
  1246. mp_globals_set(globals);
  1247. mp_locals_set(locals);
  1248. nlr_buf_t nlr;
  1249. if (nlr_push(&nlr) == 0) {
  1250. qstr source_name = lex->source_name;
  1251. mp_parse_tree_t parse_tree = mp_parse(lex, parse_input_kind);
  1252. mp_obj_t module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, false);
  1253. mp_obj_t ret;
  1254. if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
  1255. // for compile only, return value is the module function
  1256. ret = module_fun;
  1257. } else {
  1258. // execute module function and get return value
  1259. ret = mp_call_function_0(module_fun);
  1260. }
  1261. // finish nlr block, restore context and return value
  1262. nlr_pop();
  1263. mp_globals_set(old_globals);
  1264. mp_locals_set(old_locals);
  1265. return ret;
  1266. } else {
  1267. // exception; restore context and re-raise same exception
  1268. mp_globals_set(old_globals);
  1269. mp_locals_set(old_locals);
  1270. nlr_jump(nlr.ret_val);
  1271. }
  1272. }
  1273. #endif // MICROPY_ENABLE_COMPILER
  1274. NORETURN void m_malloc_fail(size_t num_bytes) {
  1275. DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes);
  1276. #if MICROPY_ENABLE_GC
  1277. if (gc_is_locked()) {
  1278. mp_raise_msg(&mp_type_MemoryError, "memory allocation failed, heap is locked");
  1279. }
  1280. #endif
  1281. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
  1282. "memory allocation failed, allocating %u bytes", (uint)num_bytes));
  1283. }
  1284. NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg) {
  1285. if (msg == NULL) {
  1286. nlr_raise(mp_obj_new_exception(exc_type));
  1287. } else {
  1288. nlr_raise(mp_obj_new_exception_msg(exc_type, msg));
  1289. }
  1290. }
  1291. NORETURN void mp_raise_ValueError(const char *msg) {
  1292. mp_raise_msg(&mp_type_ValueError, msg);
  1293. }
  1294. NORETURN void mp_raise_TypeError(const char *msg) {
  1295. mp_raise_msg(&mp_type_TypeError, msg);
  1296. }
  1297. NORETURN void mp_raise_OSError(int errno_) {
  1298. nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno_)));
  1299. }
  1300. NORETURN void mp_raise_NotImplementedError(const char *msg) {
  1301. mp_raise_msg(&mp_type_NotImplementedError, msg);
  1302. }
  1303. #if MICROPY_STACK_CHECK || MICROPY_ENABLE_PYSTACK
  1304. NORETURN void mp_raise_recursion_depth(void) {
  1305. nlr_raise(mp_obj_new_exception_arg1(&mp_type_RuntimeError,
  1306. MP_OBJ_NEW_QSTR(MP_QSTR_maximum_space_recursion_space_depth_space_exceeded)));
  1307. }
  1308. #endif