obj.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 <stdint.h>
  27. #include <stdio.h>
  28. #include <stdarg.h>
  29. #include <assert.h>
  30. #include "py/obj.h"
  31. #include "py/objtype.h"
  32. #include "py/objint.h"
  33. #include "py/objstr.h"
  34. #include "py/runtime.h"
  35. #include "py/stackctrl.h"
  36. #include "py/stream.h" // for mp_obj_print
  37. mp_obj_type_t *mp_obj_get_type(mp_const_obj_t o_in) {
  38. if (MP_OBJ_IS_SMALL_INT(o_in)) {
  39. return (mp_obj_type_t*)&mp_type_int;
  40. } else if (MP_OBJ_IS_QSTR(o_in)) {
  41. return (mp_obj_type_t*)&mp_type_str;
  42. #if MICROPY_PY_BUILTINS_FLOAT
  43. } else if (mp_obj_is_float(o_in)) {
  44. return (mp_obj_type_t*)&mp_type_float;
  45. #endif
  46. } else {
  47. const mp_obj_base_t *o = MP_OBJ_TO_PTR(o_in);
  48. return (mp_obj_type_t*)o->type;
  49. }
  50. }
  51. const char *mp_obj_get_type_str(mp_const_obj_t o_in) {
  52. return qstr_str(mp_obj_get_type(o_in)->name);
  53. }
  54. void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
  55. // There can be data structures nested too deep, or just recursive
  56. MP_STACK_CHECK();
  57. #ifndef NDEBUG
  58. if (o_in == MP_OBJ_NULL) {
  59. mp_print_str(print, "(nil)");
  60. return;
  61. }
  62. #endif
  63. mp_obj_type_t *type = mp_obj_get_type(o_in);
  64. if (type->print != NULL) {
  65. type->print((mp_print_t*)print, o_in, kind);
  66. } else {
  67. mp_printf(print, "<%q>", type->name);
  68. }
  69. }
  70. void mp_obj_print(mp_obj_t o_in, mp_print_kind_t kind) {
  71. mp_obj_print_helper(MP_PYTHON_PRINTER, o_in, kind);
  72. }
  73. // helper function to print an exception with traceback
  74. void mp_obj_print_exception(const mp_print_t *print, mp_obj_t exc) {
  75. if (mp_obj_is_exception_instance(exc)) {
  76. size_t n, *values;
  77. mp_obj_exception_get_traceback(exc, &n, &values);
  78. if (n > 0) {
  79. assert(n % 3 == 0);
  80. mp_print_str(print, "Traceback (most recent call last):\n");
  81. for (int i = n - 3; i >= 0; i -= 3) {
  82. #if MICROPY_ENABLE_SOURCE_LINE
  83. mp_printf(print, " File \"%q\", line %d", values[i], (int)values[i + 1]);
  84. #else
  85. mp_printf(print, " File \"%q\"", values[i]);
  86. #endif
  87. // the block name can be NULL if it's unknown
  88. qstr block = values[i + 2];
  89. if (block == MP_QSTR_NULL) {
  90. mp_print_str(print, "\n");
  91. } else {
  92. mp_printf(print, ", in %q\n", block);
  93. }
  94. }
  95. }
  96. }
  97. mp_obj_print_helper(print, exc, PRINT_EXC);
  98. mp_print_str(print, "\n");
  99. }
  100. bool mp_obj_is_true(mp_obj_t arg) {
  101. if (arg == mp_const_false) {
  102. return 0;
  103. } else if (arg == mp_const_true) {
  104. return 1;
  105. } else if (arg == mp_const_none) {
  106. return 0;
  107. } else if (MP_OBJ_IS_SMALL_INT(arg)) {
  108. if (MP_OBJ_SMALL_INT_VALUE(arg) == 0) {
  109. return 0;
  110. } else {
  111. return 1;
  112. }
  113. } else {
  114. mp_obj_type_t *type = mp_obj_get_type(arg);
  115. if (type->unary_op != NULL) {
  116. mp_obj_t result = type->unary_op(MP_UNARY_OP_BOOL, arg);
  117. if (result != MP_OBJ_NULL) {
  118. return result == mp_const_true;
  119. }
  120. }
  121. mp_obj_t len = mp_obj_len_maybe(arg);
  122. if (len != MP_OBJ_NULL) {
  123. // obj has a length, truth determined if len != 0
  124. return len != MP_OBJ_NEW_SMALL_INT(0);
  125. } else {
  126. // any other obj is true per Python semantics
  127. return 1;
  128. }
  129. }
  130. }
  131. bool mp_obj_is_callable(mp_obj_t o_in) {
  132. mp_call_fun_t call = mp_obj_get_type(o_in)->call;
  133. if (call != mp_obj_instance_call) {
  134. return call != NULL;
  135. }
  136. return mp_obj_instance_is_callable(o_in);
  137. }
  138. // This function implements the '==' operator (and so the inverse of '!=').
  139. //
  140. // From the Python language reference:
  141. // (https://docs.python.org/3/reference/expressions.html#not-in)
  142. // "The objects need not have the same type. If both are numbers, they are converted
  143. // to a common type. Otherwise, the == and != operators always consider objects of
  144. // different types to be unequal."
  145. //
  146. // This means that False==0 and True==1 are true expressions.
  147. //
  148. // Furthermore, from the v3.4.2 code for object.c: "Practical amendments: If rich
  149. // comparison returns NotImplemented, == and != are decided by comparing the object
  150. // pointer."
  151. bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) {
  152. // Float (and complex) NaN is never equal to anything, not even itself,
  153. // so we must have a special check here to cover those cases.
  154. if (o1 == o2
  155. #if MICROPY_PY_BUILTINS_FLOAT
  156. && !mp_obj_is_float(o1)
  157. #endif
  158. #if MICROPY_PY_BUILTINS_COMPLEX
  159. && !MP_OBJ_IS_TYPE(o1, &mp_type_complex)
  160. #endif
  161. ) {
  162. return true;
  163. }
  164. if (o1 == mp_const_none || o2 == mp_const_none) {
  165. return false;
  166. }
  167. // fast path for small ints
  168. if (MP_OBJ_IS_SMALL_INT(o1)) {
  169. if (MP_OBJ_IS_SMALL_INT(o2)) {
  170. // both SMALL_INT, and not equal if we get here
  171. return false;
  172. } else {
  173. mp_obj_t temp = o2; o2 = o1; o1 = temp;
  174. // o2 is now the SMALL_INT, o1 is not
  175. // fall through to generic op
  176. }
  177. }
  178. // fast path for strings
  179. if (MP_OBJ_IS_STR(o1)) {
  180. if (MP_OBJ_IS_STR(o2)) {
  181. // both strings, use special function
  182. return mp_obj_str_equal(o1, o2);
  183. } else {
  184. // a string is never equal to anything else
  185. goto str_cmp_err;
  186. }
  187. } else if (MP_OBJ_IS_STR(o2)) {
  188. // o1 is not a string (else caught above), so the objects are not equal
  189. str_cmp_err:
  190. #if MICROPY_PY_STR_BYTES_CMP_WARN
  191. if (MP_OBJ_IS_TYPE(o1, &mp_type_bytes) || MP_OBJ_IS_TYPE(o2, &mp_type_bytes)) {
  192. mp_warning("Comparison between bytes and str");
  193. }
  194. #endif
  195. return false;
  196. }
  197. // generic type, call binary_op(MP_BINARY_OP_EQUAL)
  198. mp_obj_type_t *type = mp_obj_get_type(o1);
  199. if (type->binary_op != NULL) {
  200. mp_obj_t r = type->binary_op(MP_BINARY_OP_EQUAL, o1, o2);
  201. if (r != MP_OBJ_NULL) {
  202. return r == mp_const_true ? true : false;
  203. }
  204. }
  205. // equality not implemented, and objects are not the same object, so
  206. // they are defined as not equal
  207. return false;
  208. }
  209. mp_int_t mp_obj_get_int(mp_const_obj_t arg) {
  210. // This function essentially performs implicit type conversion to int
  211. // Note that Python does NOT provide implicit type conversion from
  212. // float to int in the core expression language, try some_list[1.0].
  213. if (arg == mp_const_false) {
  214. return 0;
  215. } else if (arg == mp_const_true) {
  216. return 1;
  217. } else if (MP_OBJ_IS_SMALL_INT(arg)) {
  218. return MP_OBJ_SMALL_INT_VALUE(arg);
  219. } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) {
  220. return mp_obj_int_get_checked(arg);
  221. } else {
  222. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  223. mp_raise_TypeError("can't convert to int");
  224. } else {
  225. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  226. "can't convert %s to int", mp_obj_get_type_str(arg)));
  227. }
  228. }
  229. }
  230. mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg) {
  231. if (MP_OBJ_IS_INT(arg)) {
  232. return mp_obj_int_get_truncated(arg);
  233. } else {
  234. return mp_obj_get_int(arg);
  235. }
  236. }
  237. // returns false if arg is not of integral type
  238. // returns true and sets *value if it is of integral type
  239. // can throw OverflowError if arg is of integral type, but doesn't fit in a mp_int_t
  240. bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value) {
  241. if (arg == mp_const_false) {
  242. *value = 0;
  243. } else if (arg == mp_const_true) {
  244. *value = 1;
  245. } else if (MP_OBJ_IS_SMALL_INT(arg)) {
  246. *value = MP_OBJ_SMALL_INT_VALUE(arg);
  247. } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) {
  248. *value = mp_obj_int_get_checked(arg);
  249. } else {
  250. return false;
  251. }
  252. return true;
  253. }
  254. #if MICROPY_PY_BUILTINS_FLOAT
  255. bool mp_obj_get_float_maybe(mp_obj_t arg, mp_float_t *value) {
  256. mp_float_t val;
  257. if (arg == mp_const_false) {
  258. val = 0;
  259. } else if (arg == mp_const_true) {
  260. val = 1;
  261. } else if (MP_OBJ_IS_SMALL_INT(arg)) {
  262. val = MP_OBJ_SMALL_INT_VALUE(arg);
  263. #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
  264. } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) {
  265. val = mp_obj_int_as_float_impl(arg);
  266. #endif
  267. } else if (mp_obj_is_float(arg)) {
  268. val = mp_obj_float_get(arg);
  269. } else {
  270. return false;
  271. }
  272. *value = val;
  273. return true;
  274. }
  275. mp_float_t mp_obj_get_float(mp_obj_t arg) {
  276. mp_float_t val;
  277. if (!mp_obj_get_float_maybe(arg, &val)) {
  278. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  279. mp_raise_TypeError("can't convert to float");
  280. } else {
  281. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  282. "can't convert %s to float", mp_obj_get_type_str(arg)));
  283. }
  284. }
  285. return val;
  286. }
  287. #if MICROPY_PY_BUILTINS_COMPLEX
  288. void mp_obj_get_complex(mp_obj_t arg, mp_float_t *real, mp_float_t *imag) {
  289. if (arg == mp_const_false) {
  290. *real = 0;
  291. *imag = 0;
  292. } else if (arg == mp_const_true) {
  293. *real = 1;
  294. *imag = 0;
  295. } else if (MP_OBJ_IS_SMALL_INT(arg)) {
  296. *real = MP_OBJ_SMALL_INT_VALUE(arg);
  297. *imag = 0;
  298. #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
  299. } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) {
  300. *real = mp_obj_int_as_float_impl(arg);
  301. *imag = 0;
  302. #endif
  303. } else if (mp_obj_is_float(arg)) {
  304. *real = mp_obj_float_get(arg);
  305. *imag = 0;
  306. } else if (MP_OBJ_IS_TYPE(arg, &mp_type_complex)) {
  307. mp_obj_complex_get(arg, real, imag);
  308. } else {
  309. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  310. mp_raise_TypeError("can't convert to complex");
  311. } else {
  312. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  313. "can't convert %s to complex", mp_obj_get_type_str(arg)));
  314. }
  315. }
  316. }
  317. #endif
  318. #endif
  319. // note: returned value in *items may point to the interior of a GC block
  320. void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items) {
  321. if (MP_OBJ_IS_TYPE(o, &mp_type_tuple)) {
  322. mp_obj_tuple_get(o, len, items);
  323. } else if (MP_OBJ_IS_TYPE(o, &mp_type_list)) {
  324. mp_obj_list_get(o, len, items);
  325. } else {
  326. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  327. mp_raise_TypeError("expected tuple/list");
  328. } else {
  329. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  330. "object '%s' is not a tuple or list", mp_obj_get_type_str(o)));
  331. }
  332. }
  333. }
  334. // note: returned value in *items may point to the interior of a GC block
  335. void mp_obj_get_array_fixed_n(mp_obj_t o, size_t len, mp_obj_t **items) {
  336. size_t seq_len;
  337. mp_obj_get_array(o, &seq_len, items);
  338. if (seq_len != len) {
  339. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  340. mp_raise_ValueError("tuple/list has wrong length");
  341. } else {
  342. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  343. "requested length %d but object has length %d", (int)len, (int)seq_len));
  344. }
  345. }
  346. }
  347. // is_slice determines whether the index is a slice index
  348. size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool is_slice) {
  349. mp_int_t i;
  350. if (MP_OBJ_IS_SMALL_INT(index)) {
  351. i = MP_OBJ_SMALL_INT_VALUE(index);
  352. } else if (!mp_obj_get_int_maybe(index, &i)) {
  353. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  354. mp_raise_TypeError("indices must be integers");
  355. } else {
  356. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  357. "%q indices must be integers, not %s",
  358. type->name, mp_obj_get_type_str(index)));
  359. }
  360. }
  361. if (i < 0) {
  362. i += len;
  363. }
  364. if (is_slice) {
  365. if (i < 0) {
  366. i = 0;
  367. } else if ((mp_uint_t)i > len) {
  368. i = len;
  369. }
  370. } else {
  371. if (i < 0 || (mp_uint_t)i >= len) {
  372. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  373. mp_raise_msg(&mp_type_IndexError, "index out of range");
  374. } else {
  375. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError,
  376. "%q index out of range", type->name));
  377. }
  378. }
  379. }
  380. // By this point 0 <= i <= len and so fits in a size_t
  381. return (size_t)i;
  382. }
  383. mp_obj_t mp_obj_id(mp_obj_t o_in) {
  384. mp_int_t id = (mp_int_t)o_in;
  385. if (!MP_OBJ_IS_OBJ(o_in)) {
  386. return mp_obj_new_int(id);
  387. } else if (id >= 0) {
  388. // Many OSes and CPUs have affinity for putting "user" memories
  389. // into low half of address space, and "system" into upper half.
  390. // We're going to take advantage of that and return small int
  391. // (signed) for such "user" addresses.
  392. return MP_OBJ_NEW_SMALL_INT(id);
  393. } else {
  394. // If that didn't work, well, let's return long int, just as
  395. // a (big) positive value, so it will never clash with the range
  396. // of small int returned in previous case.
  397. return mp_obj_new_int_from_uint((mp_uint_t)id);
  398. }
  399. }
  400. // will raise a TypeError if object has no length
  401. mp_obj_t mp_obj_len(mp_obj_t o_in) {
  402. mp_obj_t len = mp_obj_len_maybe(o_in);
  403. if (len == MP_OBJ_NULL) {
  404. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  405. mp_raise_TypeError("object has no len");
  406. } else {
  407. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  408. "object of type '%s' has no len()", mp_obj_get_type_str(o_in)));
  409. }
  410. } else {
  411. return len;
  412. }
  413. }
  414. // may return MP_OBJ_NULL
  415. mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) {
  416. if (
  417. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  418. // It's simple - unicode is slow, non-unicode is fast
  419. MP_OBJ_IS_STR(o_in) ||
  420. #endif
  421. MP_OBJ_IS_TYPE(o_in, &mp_type_bytes)) {
  422. GET_STR_LEN(o_in, l);
  423. return MP_OBJ_NEW_SMALL_INT(l);
  424. } else {
  425. mp_obj_type_t *type = mp_obj_get_type(o_in);
  426. if (type->unary_op != NULL) {
  427. return type->unary_op(MP_UNARY_OP_LEN, o_in);
  428. } else {
  429. return MP_OBJ_NULL;
  430. }
  431. }
  432. }
  433. mp_obj_t mp_obj_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value) {
  434. mp_obj_type_t *type = mp_obj_get_type(base);
  435. if (type->subscr != NULL) {
  436. mp_obj_t ret = type->subscr(base, index, value);
  437. if (ret != MP_OBJ_NULL) {
  438. return ret;
  439. }
  440. // TODO: call base classes here?
  441. }
  442. if (value == MP_OBJ_NULL) {
  443. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  444. mp_raise_TypeError("object does not support item deletion");
  445. } else {
  446. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  447. "'%s' object does not support item deletion", mp_obj_get_type_str(base)));
  448. }
  449. } else if (value == MP_OBJ_SENTINEL) {
  450. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  451. mp_raise_TypeError("object is not subscriptable");
  452. } else {
  453. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  454. "'%s' object is not subscriptable", mp_obj_get_type_str(base)));
  455. }
  456. } else {
  457. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  458. mp_raise_TypeError("object does not support item assignment");
  459. } else {
  460. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  461. "'%s' object does not support item assignment", mp_obj_get_type_str(base)));
  462. }
  463. }
  464. }
  465. // Return input argument. Useful as .getiter for objects which are
  466. // their own iterators, etc.
  467. mp_obj_t mp_identity(mp_obj_t self) {
  468. return self;
  469. }
  470. MP_DEFINE_CONST_FUN_OBJ_1(mp_identity_obj, mp_identity);
  471. mp_obj_t mp_identity_getiter(mp_obj_t self, mp_obj_iter_buf_t *iter_buf) {
  472. (void)iter_buf;
  473. return self;
  474. }
  475. bool mp_get_buffer(mp_obj_t obj, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  476. mp_obj_type_t *type = mp_obj_get_type(obj);
  477. if (type->buffer_p.get_buffer == NULL) {
  478. return false;
  479. }
  480. int ret = type->buffer_p.get_buffer(obj, bufinfo, flags);
  481. if (ret != 0) {
  482. return false;
  483. }
  484. return true;
  485. }
  486. void mp_get_buffer_raise(mp_obj_t obj, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  487. if (!mp_get_buffer(obj, bufinfo, flags)) {
  488. mp_raise_TypeError("object with buffer protocol required");
  489. }
  490. }
  491. mp_obj_t mp_generic_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
  492. switch (op) {
  493. case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in);
  494. default: return MP_OBJ_NULL; // op not supported
  495. }
  496. }