runtime.c 57 KB

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