runtime.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  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. if (ret != MP_OBJ_STOP_ITERATION) {
  1092. *ret_val = ret;
  1093. return MP_VM_RETURN_YIELD;
  1094. } else {
  1095. // Emulate raise StopIteration()
  1096. // Special case, handled in vm.c
  1097. *ret_val = MP_OBJ_NULL;
  1098. return MP_VM_RETURN_NORMAL;
  1099. }
  1100. }
  1101. mp_obj_t dest[3]; // Reserve slot for send() arg
  1102. // Python instance iterator protocol
  1103. if (send_value == mp_const_none) {
  1104. mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
  1105. if (dest[0] != MP_OBJ_NULL) {
  1106. nlr_buf_t nlr;
  1107. if (nlr_push(&nlr) == 0) {
  1108. *ret_val = mp_call_method_n_kw(0, 0, dest);
  1109. nlr_pop();
  1110. return MP_VM_RETURN_YIELD;
  1111. } else {
  1112. *ret_val = MP_OBJ_FROM_PTR(nlr.ret_val);
  1113. return MP_VM_RETURN_EXCEPTION;
  1114. }
  1115. }
  1116. }
  1117. // Either python instance generator protocol, or native object
  1118. // generator protocol.
  1119. if (send_value != MP_OBJ_NULL) {
  1120. mp_load_method(self_in, MP_QSTR_send, dest);
  1121. dest[2] = send_value;
  1122. // TODO: This should have exception wrapping like __next__ case
  1123. // above. Not done right away to think how to optimize native
  1124. // generators better, see:
  1125. // https://github.com/micropython/micropython/issues/2628
  1126. *ret_val = mp_call_method_n_kw(1, 0, dest);
  1127. return MP_VM_RETURN_YIELD;
  1128. }
  1129. assert(throw_value != MP_OBJ_NULL);
  1130. {
  1131. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(throw_value)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
  1132. mp_load_method_maybe(self_in, MP_QSTR_close, dest);
  1133. if (dest[0] != MP_OBJ_NULL) {
  1134. // TODO: Exceptions raised in close() are not propagated,
  1135. // printed to sys.stderr
  1136. *ret_val = mp_call_method_n_kw(0, 0, dest);
  1137. // We assume one can't "yield" from close()
  1138. return MP_VM_RETURN_NORMAL;
  1139. }
  1140. } else {
  1141. mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
  1142. if (dest[0] != MP_OBJ_NULL) {
  1143. dest[2] = throw_value;
  1144. *ret_val = mp_call_method_n_kw(1, 0, dest);
  1145. // If .throw() method returned, we assume it's value to yield
  1146. // - any exception would be thrown with nlr_raise().
  1147. return MP_VM_RETURN_YIELD;
  1148. }
  1149. }
  1150. // If there's nowhere to throw exception into, then we assume that object
  1151. // is just incapable to handle it, so any exception thrown into it
  1152. // will be propagated up. This behavior is approved by test_pep380.py
  1153. // test_delegation_of_close_to_non_generator(),
  1154. // test_delegating_throw_to_non_generator()
  1155. *ret_val = throw_value;
  1156. return MP_VM_RETURN_EXCEPTION;
  1157. }
  1158. }
  1159. mp_obj_t mp_make_raise_obj(mp_obj_t o) {
  1160. DEBUG_printf("raise %p\n", o);
  1161. if (mp_obj_is_exception_type(o)) {
  1162. // o is an exception type (it is derived from BaseException (or is BaseException))
  1163. // create and return a new exception instance by calling o
  1164. // TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
  1165. // could have const instances in ROM which we return here instead
  1166. return mp_call_function_n_kw(o, 0, 0, NULL);
  1167. } else if (mp_obj_is_exception_instance(o)) {
  1168. // o is an instance of an exception, so use it as the exception
  1169. return o;
  1170. } else {
  1171. // o cannot be used as an exception, so return a type error (which will be raised by the caller)
  1172. return mp_obj_new_exception_msg(&mp_type_TypeError, "exceptions must derive from BaseException");
  1173. }
  1174. }
  1175. mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
  1176. DEBUG_printf("import name '%s' level=%d\n", qstr_str(name), MP_OBJ_SMALL_INT_VALUE(level));
  1177. // build args array
  1178. mp_obj_t args[5];
  1179. args[0] = MP_OBJ_NEW_QSTR(name);
  1180. args[1] = mp_const_none; // TODO should be globals
  1181. args[2] = mp_const_none; // TODO should be locals
  1182. args[3] = fromlist;
  1183. args[4] = level; // must be 0; we don't yet support other values
  1184. // TODO lookup __import__ and call that instead of going straight to builtin implementation
  1185. return mp_builtin___import__(5, args);
  1186. }
  1187. mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
  1188. DEBUG_printf("import from %p %s\n", module, qstr_str(name));
  1189. mp_obj_t dest[2];
  1190. mp_load_method_maybe(module, name, dest);
  1191. if (dest[1] != MP_OBJ_NULL) {
  1192. // Hopefully we can't import bound method from an object
  1193. import_error:
  1194. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %q", name));
  1195. }
  1196. if (dest[0] != MP_OBJ_NULL) {
  1197. return dest[0];
  1198. }
  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. }
  1222. void mp_import_all(mp_obj_t module) {
  1223. DEBUG_printf("import all %p\n", module);
  1224. // TODO: Support __all__
  1225. mp_map_t *map = mp_obj_dict_get_map(MP_OBJ_FROM_PTR(mp_obj_module_get_globals(module)));
  1226. for (size_t i = 0; i < map->alloc; i++) {
  1227. if (MP_MAP_SLOT_IS_FILLED(map, i)) {
  1228. qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key);
  1229. if (*qstr_str(name) != '_') {
  1230. mp_store_name(name, map->table[i].value);
  1231. }
  1232. }
  1233. }
  1234. }
  1235. #if MICROPY_ENABLE_COMPILER
  1236. // this is implemented in this file so it can optimise access to locals/globals
  1237. 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) {
  1238. // save context
  1239. mp_obj_dict_t *volatile old_globals = mp_globals_get();
  1240. mp_obj_dict_t *volatile old_locals = mp_locals_get();
  1241. // set new context
  1242. mp_globals_set(globals);
  1243. mp_locals_set(locals);
  1244. nlr_buf_t nlr;
  1245. if (nlr_push(&nlr) == 0) {
  1246. qstr source_name = lex->source_name;
  1247. mp_parse_tree_t parse_tree = mp_parse(lex, parse_input_kind);
  1248. mp_obj_t module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, false);
  1249. mp_obj_t ret;
  1250. if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
  1251. // for compile only, return value is the module function
  1252. ret = module_fun;
  1253. } else {
  1254. // execute module function and get return value
  1255. ret = mp_call_function_0(module_fun);
  1256. }
  1257. // finish nlr block, restore context and return value
  1258. nlr_pop();
  1259. mp_globals_set(old_globals);
  1260. mp_locals_set(old_locals);
  1261. return ret;
  1262. } else {
  1263. // exception; restore context and re-raise same exception
  1264. mp_globals_set(old_globals);
  1265. mp_locals_set(old_locals);
  1266. nlr_jump(nlr.ret_val);
  1267. }
  1268. }
  1269. #endif // MICROPY_ENABLE_COMPILER
  1270. NORETURN void m_malloc_fail(size_t num_bytes) {
  1271. DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes);
  1272. #if MICROPY_ENABLE_GC
  1273. if (gc_is_locked()) {
  1274. mp_raise_msg(&mp_type_MemoryError, "memory allocation failed, heap is locked");
  1275. }
  1276. #endif
  1277. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError,
  1278. "memory allocation failed, allocating %u bytes", (uint)num_bytes));
  1279. }
  1280. NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg) {
  1281. if (msg == NULL) {
  1282. nlr_raise(mp_obj_new_exception(exc_type));
  1283. } else {
  1284. nlr_raise(mp_obj_new_exception_msg(exc_type, msg));
  1285. }
  1286. }
  1287. NORETURN void mp_raise_ValueError(const char *msg) {
  1288. mp_raise_msg(&mp_type_ValueError, msg);
  1289. }
  1290. NORETURN void mp_raise_TypeError(const char *msg) {
  1291. mp_raise_msg(&mp_type_TypeError, msg);
  1292. }
  1293. NORETURN void mp_raise_OSError(int errno_) {
  1294. nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno_)));
  1295. }
  1296. NORETURN void mp_raise_NotImplementedError(const char *msg) {
  1297. mp_raise_msg(&mp_type_NotImplementedError, msg);
  1298. }
  1299. #if MICROPY_STACK_CHECK || MICROPY_ENABLE_PYSTACK
  1300. NORETURN void mp_raise_recursion_depth(void) {
  1301. nlr_raise(mp_obj_new_exception_arg1(&mp_type_RuntimeError,
  1302. MP_OBJ_NEW_QSTR(MP_QSTR_maximum_space_recursion_space_depth_space_exceeded)));
  1303. }
  1304. #endif