runtime.c 55 KB

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