runtime.c 56 KB

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