runtime.c 59 KB

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